JSON parse error response "status":200,"statusText":"OK" - json

I am trying to send JSON object but in result it is sending a parse error .
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
here is code
var data = {
fb_id: response.id,
email: response.email,
name: response.name,
first_name: response.first_name,
last_name: response.last_name,
verified: response.verified,
birthday:response.birthday,
picture: response.picture.data.url,
hometown: response.hometown.name,
gender: response.gender
};
$.ajax({
url:'connect.php',
type: 'POST',
data: {
user: data
},
dataType: 'JSON',
success: function(html){
//page();
console.log(JSON.stringify(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log(JSON.stringify(XMLHttpRequest));
}
}
});
and the backend is here:
The JSON object is sending here
if(isset($_POST['user'])) {
//convert json object to php associative array
$data = $_POST['user'];
$fbid = $data['fb_id']; // To Get Facebook ID
$fbfullname = $data['name']; // To Get Facebook full name
$femail = $data['email']; // To Get Facebook email ID
$fbname = $data['first_name'];
$fblname = $data['last_name'];
$fbgender = $data['gender'];
$fverified = $data['verified'];
$faddress = $data['hometown'];
$fbirth = $data['birthday'];
$img = $data['picture'];
}
The object is sending something like that:
{
"fb_id":"xxxxxxxxxxx99",
"email":"sxxxxxx#xxx.in",
"name":"Sagar xxxx",
...
}
PS: I am using 1.12.4 version of jquery.min.js
Updated
When I tries to send request using this query to connect.php page it returns error in console log. and If i change dataType to "text" or exclude it then it doesn't return any error but then connect.php cannot identify any query posted using ajax request ,i.e., isset($_POST['user']) will not be able to identify any query .

In your php script add this code after reading json:
if(isset($_POST['user']))
{
//convert json object to php associative array
$data = $_POST['user'];
$fbid = $data['fb_id']; // To Get Facebook ID
$fbfullname = $data['name']; // To Get Facebook full name
$femail = $data['email']; // To Get Facebook email ID
$fbname = $data['first_name'];
$fblname = $data['last_name'];
$fbgender = $data['gender'];
$fverified = $data['verified'];
$faddress = $data['hometown'];
$fbirth = $data['birthday'];
$img = $data['picture'];
Add this code:
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode("Success");
/* Stop Execution */
exit;
}
"Success" text is sent in onSuccess(html)

I'm not a PHP expert, but could be the problem is you are sending JSON as a post body and on backend operate with it as urlencoded form.
I suppose you need to get a plain json from request, parse it to an array and then process. You can find useful example here Issue reading HTTP request body from a JSON POST in PHP
Also change dataType to "application/json"

Related

Send API data and image but always empty

I'm trying to send a user picture to my api with Slim 3, PHP 7 and JQuery 2.1.1
But when I call api in HTML page then I get couple errors in Apache log, it seems that data arguments are empty and I dont know why.
Someone could help?
-------HTML source code api call
function savePicture(){
var fID = $('#edtIDUser').val();
var fPicture = document.getElementById('img').src;
$.ajax({
type:"POST",
cache:false,
url:"index.php/user_picture/",
timeout:3000,
contentType:"application/json; charset=utf-8",
data:{'id_user': fID, 'picture': fPicture},
dataType:"text",
async:false,
error: function (request, error) {
alert("error");
},
success: function (result) {
alert("ok");
}
});
}
AND API
----API source code
$app->post('/user_picture/', function(Request $request, Response $response) {
$params = $request->getParsedBody();
$iduser = $params['id_user'];
$uploadedFile = $request->getUploadedFiles();
$img = $uploadedFile['picture'];
$data = file_get_contents($img);
$escaped = bin2hex($data);
//TO-DO
}
Error #1: Trying to access array offset on value of type null in $params['id_user']
Error #2: Undefined index 'picture'
Error #3: file_get_contents(): Filename cannot be empty

How to fetch a JSON with SparkAR networking module

I want to fetch data from an URL with SparkAR's networking module
and display it.
I tried the example found in the Spark AR documentation but it doesn't do much: https://developers.facebook.com/docs/ar-studio/reference/classes/networkingmodule/
Don't forget to add "jsonplaceholder.typicode.com"
to Spark AR's whitelisted domains first. :)
// Load in the required modules
const Diagnostics = require('Diagnostics');
const Networking = require('Networking');
//==============================================================================
// Create the request
//==============================================================================
// Store the URL we're sending the request to
const url = 'https://jsonplaceholder.typicode.com/posts';
// Create a request object
const request = {
// The HTTP Method of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
method: 'POST',
// The HTTP Headers of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)
headers: {'Content-type': 'application/json; charset=UTF-8'},
// The data to send, in string format
body: JSON.stringify({title: 'Networking Module'})
};
//==============================================================================
// Send the request and log the results
//==============================================================================
// Send the request to the url
Networking.fetch(url, request).then(function(result) {
// Check the status of the result
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
if ((result.status >= 200) && (result.status < 300)) {
// If the request was successful, chain the JSON forward
return result.json();
}
// If the request was not successful, throw an error
throw new Error('HTTP status code - ' + result.status);
}).then(function(json) {
// Log the JSON obtained by the successful request
Diagnostics.log('Successfully sent - ' + json.title);
}).catch(function(error) {
// Log any errors that may have happened with the request
Diagnostics.log('Error - ' + error.message);
});
All I get is : ">> Successfully sent - Networking Module"
Does anybody know how I could get the json content to be displayed in the console I want to store it and use it in a text object afterwards.
In my case a have a url that give me a random item in json format.
URL: https://gabby-airbus.glitch.me/random
Result: {"item":"Item 14"}
In the code, replace the line:
Diagnostics.log('Successfully sent - ' + json.title);
with this:
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
First line shows the json data in console.
Second line asign the json data to a text object in the scene, in this case the "itemText" text object.
Full code:
const Diagnostics = require('Diagnostics');
const Scene = require('Scene');
const Networking = require('Networking');
const URL = 'https://gabby-airbus.glitch.me/random';
var itemText = Scene.root.find('itemText');
Networking.fetch(URL).then(function(result){
if( (result.status >=200) && (result.status < 300)){ return result.json(); }
else { throw new Error('HTTP Status Code: ' + result.status); }
}).then(function(json){
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
}).catch(function(error){
itemText = 'Failed to start';
Diagnostics.log(result.status + error);
});

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

Parse JSON from JQuery.ajax success data

I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});

dojo newbie read json response from web service

i have a webservice that is returning this response :
<string xmlns="http://tempuri.org/">{ "H...[ { "ID":"1","Name":"Test"} ]}</string>
when i try to get the response back, i keep getting the error :
"missing ; before statement"
i am just starting to get into this so am probably doing something very wrong.
why is the response not working for me?
my dojo code looks like this
var targetNode = document.getElementById("foo");
var def = dojo.io.script.get({
url: "http://localhost/WebData/PublicData.asmx/HelloWorld",
timeout: 30000,
handleAs: "json",
preventCache: true,
handle: function(error, ioargs) {
var message = "";
switch (ioargs.xhr.status) {
case 200:
message = "Good request.";
break;
case 404:
message = "The requested page was not found";
break;
case 500:
message = "The server reported an error.";
break;
case 407:
message = "You need to authenticate with a proxy.";
break;
default:
message = "Unknown error.";
}
targetNode.innerHTML = message;
}
});
thanks!
david
The get function is trying to parse the response as pure json, as the handleAs attribute is set to 'json'; but the response actually is an xml document containing some json text, causing the error you have.
Either change the response to pure json, like this:
{ "H": [ { "ID":"1","Name":"Test"} ]}
or set the handleAs attribute to 'xml' and parse the response to extract the json content; you can then unmarshall the json string using dojo.fromJson.