jQuery Test

How do I encode JSON in PHP via jQuery Ajax post data?

The result is [object object] . yes, that’s what you’ll get if JS casts an object to a string. Your JSON may be correct; you’re just not examining it properly. Try using console.log() instead. Also, use the dev tools to look at the http response that PHP sends back — you should be able to see exactly what the data looks like.

I agree with Spudley and if you just want to ensure try to console.log or alert data.Amount or data.FirstName and it will give you the value.

5 Answers 5

Code example with JSON.stringify:

       
Amount:
firstName:
lastName:
email:

text.php

 $amount, "firstName" => $firstName, "lastName" => $lastName, "email" => $email ); echo json_encode($data); > ?> 

Your object is most likely being passed properly. It’s the way you’re capturing the result that returns [object object] as @Spudley explained. The console doesn’t know how to display the construct but you can display specific attributes using the object.attribute syntax. Use console.log() on the JS side or the code below for a prettified output.

// Indent with tabs // Data is the parameter sent to the success function in the ajax handler JSON.stringify( data , null, '\t'); 

Also Temporarily remove dataType on the ajax handler if you sense there’s a bug somewhere. Getting the ouput to show on a GET request should do. Change this back to POST for any operation that modifies something like a database delete or alter.

Читайте также:  Определить сумму элементов массива html

Lastly, modify the header as shown in @GroovyCarrot’s answer. If you’re using Chrome the extra whitespace seems to be a bug: Tab and pre wrapped around JSON output in Chrome

Источник

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.

3. Create HTML Layout

Create an HTML table element with an id of “userTable” to display the user list using the AJAX response.

Читайте также:  All css image slider

4. AJAX – Returning JSON Response from PHP

Create ajaxfile.php to handle AJAX requests. Inside the file, create an array called $return_arr to store the response that will be sent back to the client.

Next, fetch all records from the users table and loop through them. For each user, add their details (id, username, name, and email) to the $return_arr array.

Finally, using json_encode() function convert $return_arr Array to JSON format before returning it to the client side.

 $id, "username" => $username, "name" => $name, "email" => $email); > // Encoding array in JSON format echo json_encode($return_arr);

5. jQuery – AJAX Request and JSON Response

An AJAX GET request is sent to ajaxfile.php once the document has reached the ready state. A new row is added to the table with the ID userTable after a successful callback, which loops through all response values.

In AJAX request set dataType to ‘json’ to handle the JSON response or you can use JSON.parse() to convert returned JSON string to an object.

$(document).ready(function()< $.ajax(< url: 'ajaxfile.php', type: 'get', dataType: 'JSON', success: function(response)< var len = response.length; for(var i=0; i" + "" + (i+1) + "" + "" + username + "" + "" + name + "" + "" + email + "" + ""; $("#userTable tbody").append(tr_str); > > >); >);

6. Demo

7. Conclusion

The PHP array must be encoded into JSON using the json_encode() function before a response can be returned. To handle returned JSON response you can either set dataType to ‘json’ or use JSON.parse() function.

With practice and further exploration, you can use these concepts to build more advanced and interactive web applications.

Additionally, you may refer to a tutorial to learn how to send a JavaScript array with an AJAX request.

If you found this tutorial helpful then don’t forget to share.

Читайте также:  Событие при нажатии кнопки java

Источник

Sending JSON to PHP using ajax

I want to send some data in json format to php and do some operation in php. My problem is i can’t send json data via ajax to my php file.Please help me how can i do that. I have tried this way..

  

8 Answers 8

Lose the contentType: «application/json; charset=utf-8», . You’re not sending JSON to the server, you’re sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don’t need to use JSON.stringify or json_decode here at all. Just do:

@Ayyash: If you were sending JSON, you’d have to read the raw input data (from php://input ). I don’t know anything about MVC.NET, so I can’t answer that.

or maybe its an IIS vs Apache issue? I use the same ajax function in both, but in .NET i just grab Request.Post, in PHP that doesn’t work, neither did php://input for some reason, the only thing that worked was passing query string attributes and using $_REQUEST. that hurts

@Ayyash: What’s wrong with using query strings and $_POST ? That’s how HTML forms are submitted. If you really want to send JSON, you can try $HTTP_RAW_POST_DATA if php://input doesn’t work.

I think I get it, «I THINK», see in MVC if you do not set content-type to json, you won’t be a happy person sending back json objects that map to models, but it also is possible to read it from Request. that isn’t the case in PHP. On the other hand if you do choose to go with JSON contentType, JSON.stringify the whole data object is required in MVC forms, but it wouldn’t pass in my PHP form!

Источник

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