views:

245

answers:

2

I have this script:

$.ajax({    
    url: 'submit_to_db.php',
    type: 'POST',
    data: 'name=' + name + '&email=' + email + '&comments=' + comments,

success: function(result) {
    $('#response').remove();
    $('#container').append('<p id="response">' + result + '</p>');
    $('#loading').fadeOut(500, function() {
    $(this).remove();
});

}
});

Then in my php file, after insert to database, I echo "comment updated", then append to my container and slowly fade away. In the meantime, I want to insert the new comment into the container as well. So I tried echo "comment updated!&com=".$comment; but it was returned as string rather than 2 variables. \

EDIT:

So weird, i am getting undefined in my php file,

$comment = $_POST['comment']

is there something wrong in my js or php code?

A: 

Just request for a JSON object you can manipulate client-side: it could be a simple string, an array, a complex object tree.

Look at the $.ajax request type; you can find a lot of samples on the net.

Andrea Balducci
i just come back from http://docs.jquery.com/Ajax/jQuery.ajax#optionsCant found the answer, thats why I ask here.. Can u help?
+2  A: 

The response doesn't contain variables. It contains text, the result of the request you made. I recommend using JSON.

#in submit_to_db.php
$response = array();

if($submitted) { #if the comment was inserted successfully
  $response['status'] = 'OK';
  $response['message'] = 'Your comment was added';
  $response['comment'] = $_POST['comments'];
}
else {
  $response['status'] = 'ERROR';
  $response['error'] = 'You must enter your name'; #just an example
}
echo json_encode($response);
#would yield {"status":"OK","comment":"the comment just added"}


#in yourJsFile.js
$.ajax({    
    url: 'submit_to_db.php',
    type: 'POST',
    data: 'name=' + name + '&email=' + email + '&comments=' + comments,
    dataType: 'json',
    success: function(response) {

        if(response.status == 'OK') {
           $('#response').remove();
           $('#container').append('<p id="response">' + response.message + '</p>');
           $('#loading').fadeOut(500, function() {
             $(this).remove();
           });

           $('#comments').append('<li>' + response.comment + '</li>'); //just an example
        }
        else {
           $('#container').append('<p id="response">' + response.error + '</p>');
        }
    }
});

More info on JSON.

andi
you are so cool man.. You saved my day...
glad I could help..
andi
btw, this method does not work on jquery 1.2.6?
It should. I don't see any reason for it not to.
andi
Yeah, it works perfectly now. Thank you very much