Passing JSON data to .getJSON in jQuery? - javascript

I am trying to pass a JSON object to .getJSON but I keep getting a bad request error. This is what I am trying:
var data = {
"SomeID": "18",
"Utc": null,
"Flags": "324"
};
$.getJSON("https://somewhere.com/AllGet?callback=?", JSON.stringify(data), function (result) {
alert(result);
});
Currently to get it working, I have to do this, but I do not like how I have to manually construct the query string:
$.getJSON("https://somewhere.com/AllGet?SomeID=18&Utc=&Flags=324&callback=?", null, function (result) {
alert(result);
});
Anyone know how to make requests easier with JSON objects being passed in? I would appreciate any help or advise.

according to the site, this is valid:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
alert("JSON Data: " + json.users[3].name);
});
so try:
var data = {
SomeID: "18",
Utc: null,
Flags: "324"
};
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});
edit: http://api.jquery.com/jQuery.getJSON/

Dont use JSON.stringfy, just pass data as it is.
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});

When you provide data to a jQuery GET request, it expects an object, not a JSON string, for constructing the query string parameters. Try changing your original code to just this:
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});

You don't need to do JSON.stringfy, just pass the JSON object, jQuery will construct your URL parameter with that
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});

why exactly do you need a callback? (Ow wait, jsonp) I'd try the following first:
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function(result) {
alert(result);
});
somewhere in firebug and see if it returns what you expect. I'm not sure what a string as data does, but just giving an object works fine afaik.

$.getJSON("https://somewhere.com/AllGet?callback=?", {SomeID:"18",Utc:null,Flags:"324"}, function (result) {
alert(result);
});
OR
var data = {
"SomeID": "18",
"Utc": null,
"Flags": "324"
};
$.getJSON("https://somewhere.com/AllGet?callback=?",
{
SomeID:data.SomeID,
Utc:data.Utc,
Flags:data.Flags
},
function (result) {
alert(result);
});

I tried encoding the json and it worked.
Not sure how efficient or practical it is, sharing it just as a work around for above question.
$.getJSON("https://somewhere.com/AllGet?data="+encodeURI(JSON.stringify(data)), function (result) {
alert(result);
});

Related

what's the correct way of pulling from a JSON file with jQuery/plain JS?

Solved
Turns out I messed up my JSON while trying to fix it. Thanks for helping. Showed me some new methods to use json :)
I searched through a lot of other questions, tried the responses, some did something others just threw an error. If it worked, it logged this whole list of metadata (including the json data I want) to the console:
{…}
​
abort: function abort(e)​
always: function always()​
catch: function catch(e)​
done: function add()​
fail: function add()​
getAllResponseHeaders: function getAllResponseHeaders()​
getResponseHeader: function getResponseHeader(e)​
overrideMimeType: function overrideMimeType(e)​
pipe: function pipe()​
progress: function add()​
promise: function promise(e)
​
readyState: 4
​
responseText: "<JSON content>"
​
setRequestHeader: function setRequestHeader(e, t)​
state: function state()
​
status: 200
​
statusCode: function statusCode(e)
​
statusText: "OK"
​
then: function then(t, n, r)​
<prototype>: Object { … }
So, my question is: how do I get the json contents from this?
Code used:
function start() {
var j = $.ajax({
url: 'users.json',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
Json:
"UsersByID":[ {
"id": 1
"Name": ["K", "L", "Smiths"],
"Birthday": ["03", "10", "1987"],
"Username": "user1",
"Password": "verysafepassword",
"Hollidays": [{
"HollidayId": 1
"HollidayType": 2,
"AmountOfPeople": 5,
"Date": ["18", "08", "2020"]
}{
"HollidayId": 2
"HollidayType": 3,
"AmountOfPeople": 2,
"Date": ["24", "10", "2020"]
}
}]
}]
}
}
What you normally do (in plain javascript) is to filter throughthe delivered JSON. Since I do not know what you want to filter, some pseudo code how it works:
function start() {
var j = $.ajax({
url: 'users.json',
type: "GET",
dataType: "json",
success: function (response) { //data is a keyword so better use response
console.log(response);
response.data.forEach(function(field) { // we iterate through each field in the JSON
if (field.typeField == "UsersByID") { // Given the JSON part looks like {"UsersByID":{"myBigData": "secrets","yourBigData": "noSecrets"}}
console.info("My content found");
// Do whatever you have to do with the content
}
}); // for each END
}
});
}
EDITT To process the JSON there are different posibilities If you know what is comming you filter like I have done above and then do something with the result.
Another way if you don't have to extract, but the whole response is the needed JSON you do as follows (and of course you can combine)
function start() {
var j = $.ajax({
url: 'users.json',
type: "GET",
dataType: "json",
success: function (response) { //data is a keyword so better use response
console.log(response);
var myObj = JSON.parse(response);
// Do whatever you have to do with myObj e.g.
var u_username = myObj.Username; // you retrieve from the object with the field names
// when nested you get a new object and then you retrieve
var objHollidays = myObj.Hollidays;
var u_HollidayId = objHollidays.HollidayId;
// OR you iterate over all objHollidays
objHollidays.HollidayId.forEach(function(field) { // we iterate through each
//Do whatever you need
});
}
});
}
Parsing Dates
Date objects are not allowed in JSON.
If you need to include a date, write it as a string.
You can convert it back into a date object later:
var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

Laravel ajax response get values

I have ajax like this:
$(".cq").on("input", function() {
$.ajax({
url: "create/reefFormAjax",
type: "POST",
data: $(this.form).serialize(),
success: function(data) {
callback(data);
}
});
});
function callback(response) {
$(".sum_whl").val(response);
$(".sum_rtl").val(response);
}
So in my controller I have something like this:
$test = $request->all();
return json_encode($test);
Then I retrieve data back to my view:
{
"material": "0",
"mquantity": null,
"cq": "2",
"sum_rtl": null,
"sum_whl": null
}
The question is how I can get each value from response ?
I tried $(response).find('cq').val() or filter but I an have error.
Any ideas?
The result you get is a JSON response
var response =
{
"material": "0",
"mquantity": null,
"cq": "2",
"sum_rtl": null,
"sum_whl": null
};
If the JSON is in your response variable, you can simply access the element like this
response.material; // should print 0
response.cq; // will print 2
When you return a json(or array) from laravel it automatically turn into a js object. so you can access like this:
function callback(response) {
$(".sum_whl").val(response.sum_whl);
$(".sum_rtl").val(response.sum_rtl);
}
console.log(response.data[0]) or console.log(reponse.material) must be work. Because its json object.
Give it a try.
$("#div).html(response.data[0])
$("#div).html(response.material)
I solved this problem, i was using return json_encode instead of return response->json($var); So i grab my values!

Results From A JSON Call to Variable

I am trying to get a ID from a JSON call, and not sure what the issue is. I have a Callback function set up to set a global variable as such.
GOAL: Make a call to a DB, get the ID from the results returning.
STEP 1 - Make call to JSON and Parse Results
callAjaxGet(<set url>,function(myReturn){
var noteID = ''
$.each(myReturn.results, function(i, note){
noteID = JSON.parse(note.id);
});
})
STEP 2 - JSON/Callback Function
function callAjaxGet(url, callBack){
$.ajax({
url: url,
type: 'GET',
timeout: 10000,
success: function(data,textStatus,xhr){
return callBack(xhr);
},
error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
STEP 3 - The Returning JSON
{
"next": "http://selleck.beta.org/playlist/notes/?limit=20&offset=20&play=437",
"previous": null,
"results": [
{
"id": 258,
"url": "/playlist/notes/258/",
"content": "testing",
"play": 437
}
]
}
No matter what I'm doing, the noteID comes back without value. I've looked in Google Development Tools, XHR, and can see the JSON coming back, so thinking I've misunderstood something.
Thank you for any thoughts and suggestions
Steve
Figured it out. Two things were wrong.
Was using XHR instead of Data
Wasn't parsing the JSON properly, the ID is in an array, so had to set the first entry, so
noteID = myReturn.results[0].id;
Thanks A.Sharma and ron tornambe for the pointer on the XHR error
Steve

jQuery json ajax function

I am having a kind of a weird problem, or maybe I do not understand how js and jQuery is working.
I have a small js that is sending an id and a value using AJAX. After a lot of experimentation I finally found a working solution which is:
$.post('dashboard/xhrDeleteListing', "id=" + id, function() {
alert(1);
});
However, I would like to use json format for the data part of the call. So what I did (to make sure that my JSON is correct) was the following:
var myJSON = {
id: id
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
But this didn't work. First, php server didn't get anything (nothing in $_POST), second, the callback function didn't run (alert(1) was never executed). To my surprise, the following call did create a $_POST['id'] value:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
but again the callback function didn't run. It only run after removal of 'json' datatype argument).
The version of jQuery is v1.11.0.
Can anyone help me to figure out what am I doing wrong?
Regards,
The important point here is when you do this like:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
the 'json' paramter is the dataType of data expected from the server, not from you to send.
It means in your backend after doing your server side task you have to return a valid json string but it seems you want to do a server action without any return value, that's why you have to remove 'json' from your arguments.
var myJSON = {
"id": "id"
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
Try this :
$.ajax({
url: 'dashboard/xhrDeleteListing',
type : 'POST',
dataType : 'json',
data: {
'id':id,
},
success : function(callback_record) {
alert(callback_record);
}
});

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Categories