Search code examples
phpjqueryajaxpost-parameter

Passing POST data from Javascript(jquery) to php problems?


I been trying to passing this value:

// Content to submit to php
Others string here. And this link:
http://www.youtube.com/watch?v=CUUgKj2i1Xc&feature=rec-LGOUT-exp_fresh+div-1r-2-HM

to a php page, and insert it to database. here is my current code:

... // javascript

var content = $("#mcontent").val();
$.ajax({
    url : '<?php echo PATH; ?>functions/save.php',
    type: 'POST',
    data: 'id=<?php echo $_GET['id']; ?>&content=' + content + '&action=save&val=<?php echo md5("secr3t" . $_SESSION['userid_id']); ?>',
    dataType: 'json',

    success: function(response) {
        if (response.status == 'success') {
            alert(response.message);
        } else {
            alert(response.message);
        }
    }
});

No errors actually, but in database, what it saved is:

Others string here. And this link:
http://www.youtube.com/watch?v=CUUgKj2i1Xc

I guess i know whats the problem, the problem is the:

http://www.youtube.com/watch?v=CUUgKj2i1Xc&feature=rec-LGOUT-exp_fresh+div-1r-2-HM

I think it takes the "&feature=" as another POST data. What I have tried:

But both does not work. Do you have any others way?

EDIT:

Do you foresee any others problem that might occurs? The content are type/write by user. Meaning that, the user can type/write anything. On backhand, I did others checking though, including the "mysql_real_escape_string"


Solution

  • A nice thing about jQuery is that the data parameter can take a JS object, so you don't need to try to build a query string manually.

    <?php
    
        $data = array("id" => $_GET['id'], 
                      "action" => "save", 
                      "val" => md5("secr3t",$_SESSION['userid_id'])
                     );
        $json_data = encode_json($data);
        $json_data = str_ireplace($json_data, '</script>', '<\/script>');
        echo "var data = $json_data;";
    ?>
    data.content = content;
    $.ajax({
                url : '<?php echo PATH; ?>functions/save.php',
                type: 'POST',
                data: data,
                dataType: 'json',