Php ajax ответ json

ajax to a php and get JSON from it

I have a php file that i connect to it with ajax and callback value is JSON when i get data from php it dosnt show and when alert data i see Object Where is my problem ? PHP:

if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])) < $query = mysql_query("select * from tab"); for ($i=0;$i> echo(json_encode($title)); exit(); ?> 

2 Answers 2

Here’s a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.

And yes, DON’T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?

function example() < var select = true; var url = '../scripts/ajax.php'; $.ajax( < // Post select to url. type : 'post', url : url, dataType : 'json', // expected returned data format. data : < 'select' : select // the variable you're posting. >, success : function(data) < // This happens AFTER the PHP has returned an JSON array, // as explained below. var result1, result2, message; for(var i = 0; i < data.length; i++) < // Parse through the JSON array which was returned. // A proper error handling should be added here (check if // everything went successful or not) result1 = data[i].result1; result2 = data[i].result2; message = data[i].message; // Do something with result and result2, or message. // For example: $('#content').html(result1); // Or just alert / log the data. alert(result1); >>, complete : function(data) < // do something, not critical. >>); > 

Now we need to receive the posted variable in ajax.php:

$select = isset($_POST['select']) ? $_POST['select'] : false; 

The ternary operator lets $select’s value become false if It’s not set.

Читайте также:  Php fpm install pdo mysql

Make sure you got access to your database here:

$db = $GLOBALS['db']; // An example of a PDO database connection 

Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:

if($select) < // Fetch data from the database. // Return the data with a JSON array (see below). >else < $json[] = array ( 'message' =>'Not Requested' ); > echo json_encode($json); flush(); 

How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.

Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):

function selectMultipleRows($db, $query) < $array = array(); $stmt = $db->prepare($query); $stmt->execute(); if($result = $stmt->fetchAll(PDO::FETCH_ASSOC)) < foreach($result as $res) < foreach($res as $key=>$val) < $temp[$key] = utf8_encode($val); >array_push($array, $temp); > return $array; > return false; > 

Then you can do something like this:

if($select) < $array = array(); $i = 0; $query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;'; foreach(selectMultipleRows($db, $query) as $row) < $array[$i]["result1"] = $row['result1']; $array[$i]["result2"] = $row['result2']; $i++; >if(!(empty($array))) // If something was fetched < while(list($key, $value) = each($array)) < $json[] = array ( 'result1' =>$value["result1"], 'result2' => $value["result2"], 'message' => 'success' ); > > else // Nothing found in database < $json[] = array ( 'message' =>'nothing found' ); > > // . 

Or, if you want to KISS (Keep it simple stupid):

Init a basic function which select some values from the database and returns a single row:

function getSingleRow($db, $query) < $stmt = $db->prepare($query); $stmt->execute(); // $stmt->execute(array(":id"=>$someValue)); another approach to execute. $result = $stmt->fetch(PDO::FETCH_ASSOC); if($result) < $array = ( 'result1' =>$result['result1'], 'result2' => $result['result2'] ); // An array is not needed for a single value. return $array; > return false; > 

And then fetch the row (or the single value) and return it with JSON:

if($select) < // Assume that the previously defined query exists. $results = getSingleRow($db, $query); if($results !== false) < $json[] = array ( 'result1' =>$results['result1'], 'result2' => $results['result2'], 'message' => 'success' ); > else // Nothing found in database < $json[] = array ( 'message' =>'nothing found' ); > > // . 

And if you want to get the value of $(«#tab») then you have to do something like $(«#tab»).val() or $(«#tab»).text().

Источник

Return JSON response from AJAX using jQuery and PHP

JSON or JavaScript Object Notation is a widely used transmitting format for passing data between a server and a web application. It is the most efficient way to return multiple values as a response from the PHP script to jQuery.

It is not possible to return an array directly from AJAX, and it must be converted into a valid format. You can either use the XML or JSON format.

In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.

On the basis of response show data in tabular format.

Return JSON response from AJAX using jQuery and PHP

Table of Content

1. Table structure

I am using users table in the example.

CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Database connection

Create config.php for database configuration.

Then now we will add our javascript code get() function inside scripts.js.

function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function () , success: function (response) >); >); >

Loop the JSON Response

Since you already know how to display your JSON response to your web page. Now I will give you an example of how to loop the JSON. Below are the screenshot example on listing the employees via ajax with JSON response.

Before we dive in I will show you first a basic code on how to do it. As you can see in the code below I use «$.each(response, function(key,value)

Kindly check the console result below of the above code.

Loop the JSON Response

So that’s the basic way on how to loop the JSON. So we will apply it in the advance by displaying the list of employees using the bootstrap list group as you can see the result below:

Lop the JSON Response

Now let do the code. First set up our HTML code inside index.html.

Then next our PHP Code inside all.php.

query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now let’s code the javascript for looping the employee’s result via ajax. You will find this code inside scripts.js with all() functions.

function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response) '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "

" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

"; html += "

" + value.address + "

"; html += ""; html += ""; html += ''; >); html += '
'; > else < html += '
'; html += 'No records found!'; html += '
'; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); >

Now you have the foundation already about JSON Response from your server-side. I hope this article may help you. To see the action capability of this code just click the «Download» button below.

Thank you for reading. Happy Coding!

Источник

Оцените статью