user2997418 user2997418 - 2 months ago 5
HTML Question

AJAX jQuery doesn't display returned data

I have a script to fetch data and load it in a div, the code works fine and display the user id list if I don't use any form value and if I don't use type="POST", but it doesn't work (no result and no console error message) when I use $_POST values :

HTML :

<form name='newUser' id="searchForm" method="POST">
<input type="text" name="look_for" id="look_for">
<input type="text" name="lookage_from" id="age_from">
<input type="text" name="age_to" id="age_to">
</form>


fetchusers.php

$look_for = $_POST['look_for'];
$age_from = $_POST['age_from'];
$age_to = $_POST['age_to'];
$array = getProfilePicsList($look_for,$age_from,$age_to); //a function that select * from ...
echo json_encode($array);


jquery code:

$("#searchForm").submit(function(event)
{
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
return false;
});

Answer

In your ajax request, you are missing the data. just add this:

data: $("#searchForm").serialize(),

Example:

$.ajax({
    type: 'POST',
    url: 'models/fetchUsers.php', //the script to call to get data
    dataType: 'json',             //data format
    data: $("#searchForm").serialize(),
    success: function(data)       //on recieve of reply
    {
        $.each($(data), function(key, value) {
            $('#itemContainer').append(value.user_id);
        });
    }
});

Without using data param, you can't get the values in $_POST array.

Some References: https://api.jquery.com/jquery.post/ http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Comments