Post JSON data to server and parse the response in JavaScript - javascript

I need to POST the JSON format data to the server URL. The server will send the response in same JSON format. I need to parse it and get the data. How to do it? please help me with an example.

at client side (to convert into the json)--->
var myJSONText = JSON.stringify(myObject, replacer);
& at server side to get the actual data--->
var dynObj = JsonConvert.DeserializeObject(myJSONText);
php--->
<?php
$jsonTxt = '{"abc":1111,"xyz":222}';
var_dump(json_decode($jsonTxt));
var_dump(json_decode($jsonTxt, true));
?>

You can use JSON.parse() which may be supported in most browsers.
var response = {"success":true, "data":"My data"};
var json_res = JSON.parse(response);
console.log(json_res.data)
Alternatively, if you are using some javascript library, for example jQuery you may have an helper. See this similar question

Should look something like this.
var data = $(":input").serializeArray();
$.ajax({
url: url,
data: JSON.stringify(data),
type: "GET",
dataType: 'json',
contentType: 'application/json'
});
On Server side :
public static function createFromJson( $jsonString )
{
$object = json_decode( $jsonString );
return new self( $object->firstName, $object->lastName );
}

Related

jQuery ajax post URL with query string cannot get $_POST in server side

My url parameter need to included the query string due to the system need to pass the token everytime request a link. I would like to use ajax POST to my PHP page.
Below is my ajax code:-
var data = new Array();
data[0] = $('#coupon_code').val();
data[1] = $('#coupon_value').val();
var jsondata = {"data": data}
var json = JSON.stringify(jsondata);
$.ajax({
url:"index.php?route=coupon/create&token=csrf1234567",
cache:false,
processData: false,
type: 'post',
dataType: 'json',
contentType: 'application/json',
data:{json},
success:function(){}
});
However, my PHP script is like below to make sure I have everything passed to server side:
public function create()
{
var_dump($_REQUEST);
}
It only have following output:-
array(2) {
["route"]=>
string(13) "coupon/create"
["token"]=>
string(11) "csrf1234567"
}
Inside the chrome insepct it shows
**Query String Paramaters**
route:coupon/create
token:csrf1234567
**Request Payload**
[object Object]
It does not have POST variable to pass to my PHP. I want to use type POST, and json to accomplish this, any idea how to solve it?
SOLVED:
data:{json},
change to
data:json,
Thanks for the solution!
SOLVED:
data:{json},
change to
data:json,
Thanks for guest271314!

How to access AJAX returned data with PHP?

I hava data structure like this which is then returned to another file with AJAX:
$data = array();
$data['message'] = "You are searching: $domain!";
$data['domain:name'] = "domain.tld";
$data['domain:registrar'] = "Registrar Ltd.";
$data['domain:creation'] = "2015-26-05";
$data['domain:expiry'] = "2016-26-05";
$data['ns'] = "ns1.somedns.tld";
$data['owner']['name'] = "Owner Name";
$data['owner']['type'] = "Org";
echo json_encode($data);
That data is then append to html with AJAX like this:
$.ajax({
type: 'POST',
url: 'carnetEpp.php',
data: $(this).serialize(),
success: function (data) {
dataType: 'json',
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
Now I want to pass that returned JSON object to PHP variable, so I can easy manipulate date with PHP. How do I do that? Or is best practice to do it with JS? Basically I want to print every key:pair value, so maybe for in is good choice.
And, I am not sure, should, or must I echo data in my script so AJAX can pick it up, or can I just pass data to variable and then fetch it in AJAX?
You need to add this code in success.
var obj = jQuery.parseJSON(data);
alert(obj.message);
OR
var obj = $.parseJSON(data);
alert(obj.message);
You will get the message sent from PHP.
before sending data in php, setup header for response:
$data = [
'key' => 'value',
'key2' => 'vlue2'
];
header('Content-Type: application/json');
echo json_encode($data);
then if u use jquery, $.getJson() it really cool solution for handle input json data.

Array of objects for PHP (AJAX)

I've been struggling with converting an Array of objects to JSON, or any other PHP readable format so I can send it over AJAX.
I'm using localStorage and I save an object into it, I save it using
JSON.stringify(data)
Now when I loop through all the localStorage data, I add it to an array using the following code
var locations = new Array();
for(var i = 0; i < localStorage.length; i++){
locations[i] = JSON.parse(localStorage.getItem(localStorage.key(i)));
}
The end result looks like this.
This is my $.ajax request
$.ajax({
type: "POST",
url: "store.php",
dataType: "json",
data: locations,
success: function(data) {
console.log(data);
}
});
The only problem is that I can't seem to convert it to a readable format to send to PHP
Any clues? Thanks!
Make your post data an object.
$.ajax({
type: "POST",
url: "store.php",
dataType: "json",
data: {location: locations},
success: function(data) {
console.log(data);
}
});
Then on your PHP: print($_POST['location']);
You can also simplify like this.
$.post('store.php', {location: locations}, function(data) {
console.log(data);
});
You should also be able to pass the content directly from localStorage -- no need to build an array from it.
Data formed with JSON.stringify() can be sent through $.ajax and interpreted by PHP.
You can use PHP's input stream to read your data:
$json = file_get_contents('php://input');
$array = json_decode($json);
For more info on PHP's I/O streams, see http://php.net/manual/en/wrappers.php.php

send json object from javascript to php

I am trying to send JSON object from Javascript/Jquery to PHP and I am getting and error msg in my console. What am I doing wrong. I am new to JS and PHP.
JQuery file:
$(document).ready(function() {
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
// console.log(typeof(flickr));
var makeFlickrCall = function(flickrObj){
$.ajax({
url: '../phpincl/apiConnect.php',
type: 'POST',
data: flickrObj
})
.done(function(data) {
console.log("success");
console.log(JSON.stringify(data));
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
};
makeFlickrCall(flickr);
});
PHP file
<?php
$obj = $_POST['data'];
// print_r($obj);
return $obj;
?>
The standard jQuery .ajax() method uses the data property to create an x-www-form-urlencoded string to pass in the request body. Something like this
action=Flickr&get=getPublicPhotos
Therefore, your PHP script should not look for $_POST['data'] but instead, $_POST['action'] and $_POST['get'].
If you want to send a raw JSON data payload to PHP, then do the following...
Set the AJAX contentType parameter to application/json and send a stringified version of your JSON object as the data payload, eg
$.ajax({
url: '../phpincl/apiConnect.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(flickrObj),
dataType: 'json'
})
Your PHP script would then read the data payload from the php://input stream, eg
$json = file_get_contents('php://input');
You can then parse this into a PHP object or array...
$dataObject = json_decode($json);
$dataArray = json_decode($json, true);
And, if you're just wanting to echo it back to the client..
header('Content-type: application/json');
// unmodified
echo $json;
// or if you've made changes to say $dataArray
echo json_encode($dataArray);
Excellent answer by Phil, however since the OP title says
send json object from javascript (not jQuery ) to php
this is how to do it with (vanilla) javascript, in case it helps somebody looking for this method:
var jsondata;
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
var data = JSON.stringify(flickr);
var xhr = new XMLHttpRequest();
xhr.open("POST", "../phpincl/apiConnect.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
console.log(jsondata);
}
}
Notice we still need to convert the server's response into a javascript object using JSON.parse()
Now, on the server side (based on Phil's answer) if you are sending back a response to the client, you could do:
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;
NOTE:
The reason behind decoding first and then encoding back the raw json input is to properly escape slashes in (possible) URLs within the data, e.g.
json_encode will convert this URL
http://example.com
into
http:\/\/example.com
... which is not the case in the OP but useful in some other scenarios.
Use:
makeFlickrCall( { data: JSON.stringify( flickr )} );
Instead of
makeFlickrCall(flickr);
Your server-side script should receive your JSON as follows:
data="{"action":"Flickr","get":"getPublicPhotos"}"

Post JSON to PHP in AJAX for MongoDB Querying

I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.
I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:
var numpages=$('.page').length;
var book=new Object();
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);
book.user=data.username;
}
});
book.title=title;
book.pages=new Array();
var page;
var link;
for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();
for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();
page.links.push(link);
}
book.pages.push(page);
}
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);
console.log(msg);
//alert(msg);
}
});
}
Here is the PHP:
<?php
$dbhost = 'localhost';
$dbname = 'story';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->stories;
$story=$_POST['json'];
if (isset($story)){
$collection->save($story);
}
?>
The document is being inserted into the database but I get this:
Notice: Undefined index: json
You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:
book.owner=data.username;
Is likely to actually be empty when you come to JSON encode in the second ajax call.
To solve this you can use JQuery promises like so:
$.get().done(function(data){
/// extra processing
}).then(function(){ $.get() // etc });
This will ensure that one Ajax calls runs after the other.
As for the missing index you don't actually need to stringify your data at all instead you can just do:
$.get('some_url', {book: book})
And JQuery will actually serialize it for you ready for PHP.
This
JSON.stringify(book),
creates an object something like:
{"title":"East of Eden","author":"John Steinbeck"}
better completely remove the JSON.stringify() bit and just pass the book variable
And it in the ajax call it should be type: "POST", not method: "POST"
So in your php script you can do
$_POST['title'];
$_POST['author'];
Hope that helps
If you want to work exclusively with JSON, you should set your content-type header to application/json and then read that content from PHP raw input:
The javascript:
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
The PHP:
$story = file_get_contents('php://input');
So really you just need to add one line of code and change another.
The reason $_POST['json'] was not being populated is that nowhere did you define a query string (or let jQuery define for you) that has a key json.
You could have, for example done something like this:
data: {'json': JSON.stringify(book)}
And that would have populated $POST['json'], but again if all you are looking to do is pass around a JSON string and directly insert it into Mongo, there is no reason to use form-encoding for this at all, just work with raw POST data.
Note also the problem mentioned by #Sammaye about needing to properly work with event delegation.

Categories

Resources