Retrieving data from a database from an ajax function

I have an ajax function that will retrieve data from my database and display it in my text box. I am using jQuery Form Plugin to shorten ajax process a bit. Now what I want to do is return the data from the php script that I called from the ajax function.

Layout Form:

<form action="searchFunction.php" method="post" id="searchForm">
  <input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
  <input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>

Server code in searchFunction.php

$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);

return $row;

ajax script processing php,

$(document).ready(function() {
  $('#searchForm').ajaxForm({
    dataType: 'json',
    success: processSearch
  });
});

function processSearch(data) {
  alert(data['username']); //Am I doing it right here?
}

In PHP, if I want to call data, I just simply create a function for the database and just, for example, echo $row['username']it. But how do I do this with ajax? I am new to this, please explain this process.

+4
source share
3
$('#Search').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/<SolutionName>/<MethodName>",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        error: function () {
                    alert('Unable to load feed, Incorrect path or invalid feed');
                },
                 success: processSearch,
    });
});
 function processSearch(data) {
var username= ($(data).find('#username'));

}

0

. , . ajax, .

0

Everything seems beautiful except this bit -

function processSearch(data) {
   alert(data['username']); //Am I doing it right here?
}

You need to change it to

function processSearch(data) {
   // data is a JSON object. Need to access it with dot notation
   alert(data.username);
}

UPDATE

You also need to return a JSON response from your PHP file. Sort of -

// Set the Content Type to JSON
header('Content-Type: application/json');

$data = [
    "key" => "value"
];

return json_encode($data);

In your case, you can directly code $rowlike this:

return json_encode($row);
0
source

All Articles