tabaiba tabaiba - 1 month ago 5
Javascript Question

Getting multimple results from Ajax post

Maybe this is a duplicate but I can not understand why mo code does not work. I am trying to get multiple results via Ajax/php.

This is from my php file:

$result11 = 'test1'
$result22 = 'test2';

echo json_encode(array("data1" => $result11, "data2" => $result22));


Ajax call:

$(document.body).on('submit','#sendmessage',function() {

$.ajax({
type: "POST",
url: "/send.php",
data: {par:par,kid:kid,ha:ha,sform:sform,editors:editors},
cache: false,
dataType:'json',
success: function(datax) {
alert(datax.data1);
}

});
return false;
});


Problem:

When I submit a form, the page refreshes instead of sending ajax request.

At the same time this works but I can't get multiple results from Php file:

$(document.body).on('submit','#sendmessagex',function() {

var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}

});
return false;
});

Answer

Add a preventDefault() call to your script

$(document.body).on('submit','#sendmessagex',function(event) {
//----------------------------------------------------^^^^^
    event.preventDefault();
    var str = $(this).serialize();
    $.ajax({
            type: "POST",
            url: "/send.php",
            data:str,    
            success: function(data) {
                alert(data);
            }

    });
    return false;
});