send json object from javascript to php - javascript

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"}"

Related

Sending JSON data with jQuery not working

Simple request being made
var username = {'username' : 'tom'};
var request = $.ajax({
url : 'test.php',
method : 'GET',
data : JSON.stringify(username),
dataType : 'json'
});
request.done(function(response) {
response = JSON.parse(response);
console.log(response);
});
request.fail(function(xhr, status, error) {
console.log(error);
});
PHP:
<?php
echo json_encode(array("bar" => "bar"));
?>
Still getting error, no idea why
that's because the server is returning a non valid JSON string. Try to check what the server is returning. This may happen if your server is throwing an error. In your case, I think the error you are trying to parse is not a JSON string. You might want to check that out as well.
You can use this link to validate your JSON.

Unexpected token in JSON at positon 0

I always get Unexpected token in JSON at positon 0 in my code
the echo json will be
["pen","pencil","apple","cat","dog"]
and the console will get Uncaught SyntaxError: Unexpected token p in JSON at position 0
php code :
<?php
include 'Connect_2.php';
header('Content-Type: application/json;charset=utf-8');
$Store_int =$_GET['num'];
#execute sql function and return result
$sql = "SELECT * FROM `store` WHERE `Place_int` = ".$Store_int;
mysqli_select_db($link,"web");
$link -> set_charset("utf8");
$result = mysqli_query($link,$sql);
$arr = array();
while ($row = mysqli_fetch_object($result)){
$p =(string) $row -> Name;
$arr[]=$p;
}
//print_r($arr);
$jsonArr = json_encode($arr,JSON_UNESCAPED_UNICODE);
echo ($jsonArr);
mysqli_free_result($result);
mysqli_close($link);
?>
.js code
function getArr(store_int){
var jsArray = new Array();
$.ajax({
url: "fromSQL_store.php",
data: {
num: store_int
},
type: "GET",
dataType: "json",
success: function(data) {
jsArray = JSON.parse(data);
//jsArray = data;
},error: function(data,XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
console.log(errorThrown);
}
});
//alert(jsArray.length);
console.log(jsArray[0]);
return jsArray;
}
if I use jsArray = data ;the console(jsArray[0]) will show undefined.
It's already JSON. Don't call jsArray = JSON.parse(data); Instead, just treat data like a JSON object.
Instead of console(jsArray[0]) call console(jsArray) The data object doesn't seem to be an array.
Also, it looks like you're console.log is being called right after you send the ajax request, which isn't giving you any time to receive the response to populate the object, so it's going to be empty. Put the console.log in the success callback of the ajax request.
JSON.parse() throws this error when it's parsing something that's already JSON which is really annoying since it sure would be nice if it instead just returned the original JSON back to you or at least threw a more precise error like "Error: This is already JSON."
May be your response header Content-Type is text/html instead of application/json.
Hence, If the response header is text/html you need to parse the text into JSON Object but if the response header is application/json then it is already parsed into JSON Object.
The solution is to set correct Content-Type header.
If response header (Content-Type) is text/html :
var jsonObj = JSON.parse(responseData);
If response header (Content-Type) is application/json :
var jsonObj = responseData;

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.

Loop Through json_encoded PHP Array in JavaScript

I am having an issue with looping through an array that was passed from PHP through an Ajax request.
For some reason my javascript thinks that either every character is a part of the array or my response variable is just being passed as a string.
Here is my javascript:
<script>
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
success: function(response) {
console.log(response);
}
});
});
</script>
And here is my PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
echo json_encode($names);
?>
The response that I get looks like this:
["Test Person","Test2 Person"]
However, if I loop through this using javascript or just print out response[0] I get each character as part of the array. The first element would be [, next would be ", etc.
I would like Test Person to be one element and Test2 Person to be another.
Does anybody know what I am doing wrong? Thanks!
You need to use JSON.parse on the response. Wihtout calling that function you are just getting the index of characters in the JavaScript string.
var resultArray = JSON.parse(response);
resultArray[0]; //Should Be "test Person"
The result of the .ajax method is interpreted according to the Content-Type header of the response. If it is incorrect or not specified, the response variable will contain the raw json code as a string.
So one solution is change the PHP code by adding this line:
header("Content-Type: text/json");
Docs:
The type of pre-processing depends by default upon the Content-Type of
the response, but can be set explicitly using the dataType option. If
the dataType option is provided, the Content-Type header of the
response will be disregarded.
You can parse that text to an object, or you can let JQuery do that for you by specifying a datatype in the call. The response parameter will then hold the object instead of the raw json string.
Docs:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: "json",
success: function(response) {
console.log(response);
}
});
});
In this particular situation, you can use
success: function(response) {
response = eval(response);
console.log(response);
}
But this is bad practice.
Really the best solution here is to modify your ajax call as follow:
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: 'json',
success: function(response) {
console.log(response);
}
});
});
The specified datatype, will request the returned data to be json, and the jquery will automatically parse it to a javascript object.
You must parse JSON to array. You can do this using the following code:
var arr = $.parseJSON(response);
Now arr[0] should be "Test Person".
You can do it the hard way, or this way:
First, you need to specify the return type for AJAX.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Alternatively, you could do it this way:
$(function() {
$.getJSON("/dev/editButton/get_names.php", function(response) {
console.log(response);
});
});
For this to work, you will need to specify the HTML headers accordingly in PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
header("Content-Type: application/json");
echo json_encode($names);
exit();
?>
The exit(); is just for safety so you wouldn't ruin the valid JSON format.
JSON stands for JavaScript Object Notation, so you should not have to do anything complicated there. Here is a simple loop you could use for example:
for(var i in response) {
console.log(response[i]);
}
Alternatively, if the response is not an array but an object with properties, you could loop through the object properties by getting the right keys first:
var objKeys = Object.keys(response);
for(var i in objKeys) {
var key = objKeys[i];
console.log(response[key]);
}
I hope this helps!

Post JSON data to server and parse the response in 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 );
}

Categories

Resources