Can I get more variables instead of string in jquery $ ajax?

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 inserting into the database, I repeat "comment updated", then I attach to the container and slowly fade out. In the meantime, I want to insert a new comment into the container. So I tried echo "comment updated! & Com =". $ Comment; but it was returned as a string, not 2 variables. \

EDIT:

So strange, I am getting undefined in my php file,

$ comment = $ _POST ['comment']

is there something wrong in my js or php code?

+1


a source to share


2 answers


The answer contains no variables. It contains the text, the result of the query 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.

+2


a source


Just request a JSON object that you can manipulate on the client side: it can be a simple string, an array, a complex tree of objects.



Look at the request type $. ajax ; you can find many samples on the net.

0


a source







All Articles