I will be passing a json string to a servlet via an ajax request :
function add() {
$.ajax({
url: "pathToServlet" ,
dataType: "text",
data: ({
name : 'myJsonString'
}),
success: function(data) {
alert('returned!!');
});
}
To build up this json string I have a listener which when fired appends a new piece of json to string :
var json = "";
json += "{ new json ..... }"
Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?
What I would recommend doing is building up an object, and then when you're ready to send it to the server, serialize the object via JSON.stringify.
So for instance, you might have an object called data:
var data = {};
...to which you might periodically add properties:
data.foo = "bar";
data.stuff = {nifty: "stuff"};
Or perhaps data is an array:
var data = [];
...to which you add things:
data.push({nifty: "stuff"});
Then, when you're ready to send it:
function add() {
$.ajax({
url: "<%=savePortlet%>" ,
dataType: "text",
data: {
name : JSON.stringify(data)
},
success: function(data) {
alert('returned!!');
});
}
Because you're passing an object into ajax, you don't have to worry about URL-encoding the JSON string; jQuery will do it for you.
JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page.
If using jQuery you can use jquery-json, a really handy plugin to handle JSON with JavaScript and jQuery.
Usage:
var jsonString = $.toJSON(myObject);
Related
I have different results by using filter_input(INPUT_POST, 'attribute') and $_POST['attribute'] and don't know why this happens.
The Post-Request is send by a JavaScript build with JQuery and looks like that:
// type javaScript
var formData = {
field_a: "valueA",
field_b: "",
field_c: undefined
};
$.ajax({
url: 'serverAddress',
data: {action: 99, formData: formData},
dataType: 'json',
method: 'post',
success: function(){
console.log(arguments)
}
});
My PHP-Script looks like that:
// type php
$requestMethod = INPUT_POST;
$response = [
"fi-result" => filter_input($requestMethod, 'formData'),
"direct-result" => $_POST['formData'];
];
echo json_encode($response);
the result what is coming back is not what i was awaiting because the access via filter_input returns falsein my tests and not an json object like the direct access on the super global $_POST.
// type json response
{
"fi_result": false,
"direct-result": {
"field_a": "valueA",
"field_b": ""
}
}
Why are there differences between using filter_input and direct access on $_POST?
I don't want to access the super global $_POST. Is there any way to use filter_input like above without encode formData to a String in JavaScript and decode it in PHP one simple step after encoding?
By the way. I'm using TypeScript to generate my JavaScript. That is not supporting the FormData Object (transpiler throws error on new FormData()). So i can't use this.
I found the answer deep in the PHP docs. POST is not build to transport deep object. And filter_input method tries to get simple datatypes like string or int. this method does not parse internal so i have to send it as JSON string and decode it or i can't use filter_input in my case.
i took the first and send now strings.
I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,
http://pastebin.com/0BY3eptF
According to me the above is a very complex JSON.
I'm trying to fetch the out from a WSDL via ajax
success: function(api) {
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.
Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.
success: function(api) {
if (api.constructor === String) {
api = JSON.parse(api);
}
console.log(api.SearchResult);
}
To loop through api.SearchResult.Result.WSResult array, please find below code
$(api.SearchResult.Result.WSResult).each(function (index, val) {
// here val is single object of WSResult array
});
success: function(api) {}, here, api is still a string, you have to parse it to JSON first:
success: function(api) {
var api = JSON.parse(api);
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
Not a complete answer, but some useful pointers:
$ajax({
url: 'http://myURL',
// specify the datatype; I think it overrides inferring it from the document MIME type
dataType: 'json',
success: function (api) {
// provided your data does come back as a JSON document
// you should be able to access api.SearchResult
},
error: function( jsXHR, textStatus, errorThrown) {
// always have an error handler, so you can see how it went wrong.
}
);
Read the section on dataType here, as it may solve your problem
I am storing some JSON data in a text file to query using jQuery Ajax in my page. Currently, my text file contains around 10 facets of data (which could contain an additional 30 facets of data). The JSON data contains a questions and answers to those questions.
In my JavaScript files, I have setup different functions to get specific bits of data.
For example:
function GetAnswer(questionName) {
var correctAnswer = null;
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
$.each(result, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
},
error: function () { },
complete: function () { }
});
return correctAnswer ;
}
As you can see from my code-snippet, I am looping through my JSON to get the data I need. I have other functions coded in a similar fashion to get the question type, question name etc.
What I am finding is that I am calling these functions one after another to get the data I need. I think the way I am querying my JSON data is not good from a performance point-of-view since I am looping through the whole of my JSON dataset until I find a match.
Is there a better way to query my JSON data?
NOTE: I am having to use a text file to store questions due to restrictions of the technology I am using (SCORM 1.2).
Looping through your JSON object is relatively quick. What is slow (comparatively) is loading in that text file each time (though it may be cached).
Either way, I would suggest loading in the JSON either the first time the user initiates a question/answer situation, or just load it in on page load (you can do it asynchronously) and store it for later use.
Example of the latter:
jQuery(document).ready(function(){
var questions = '';
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
questions = result;
},
error: function () { },
complete: function () { }
});
function GetAnswer(questionName) {
var correctAnswer = null;
$.each(questions, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
return correctAnswer ;
}
});
The problem is that you have async set to false. This is bad. This halts the browser while it waits for your requests, and will cause the performance to feel very laggy.
Why not change the structure of your Q&A object to include an id for each question, and make the id an attribute in the object? Then you could pass the id to GetAnswer() and just have it go directly to the right question by referencing the correct attribute? The object could look like this:
{"myQuiz" :
"Q1" :
{ "q" : "What color was George Washington's white horse?",
"a" : "White"
},
"Q2" :
{ "q" : "In what city would you find the Leaning Tower of Pisa?",
"a" : "Pisa"
}
}
If this is assigned to result, and an id of Q2 was passed to GetAnswer(id), you could easily return result.myQuiz[id].a;
As an alternative, if the order of the questions is consistent, you could use an object that contains an array of q and a pairs, and refer to them by index rather than id.
Why not move the logic to a server-side script like PHP that can take in POST parameters and perform the queries against the JSON set and return only the record(s) you wish to receive. Or, if you are intent on keeping this in all js, you could simply store the JSON (as long as it is non-sensitive data) in a local variable and query against it locally.
You could make somekind of mechanism on the server to load data. Then you could send parameters like QuestionName and filter data. This will lower payload sent on the wire.
If I have a ajax call:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(json_data){
//What's the efficient way to extract the JSON data and get the value
}
});
Server returned to my js the following JSON data
{"contact":[{"address":[{"city":"Shanghai","street":"Long
Hua Street"},{"city":"Shanghai","street":"Dong Quan
Street"}],"id":"huangyim","name":"Huang Yi Ming"}]}
In my jQuery AJAX success callback function, how to extract the value of "name", value of "address" (which is a list of object) elegantly?
I am not experienced with jQuery and JSON data handling in javascript. So, I would like to ask some suggestions on how to handle this data efficiently. Thanks.
A JSON string gets parsed into a JavaScript object/array. So you can access the values like you access any object property, array element:
var name = json_data.contact[0].name;
var addresses = json_data.contact[0].address;
Do access the values inside each address, you can iterate over the array:
for(var i = addresses.length; i--;) {
var address = addresses[i];
// address.city
// address.street
// etc
}
If you have not so much experience with JavaScript, I suggest to read this guide.
How can I send a JavaScript array as a JSON variable in my AJAX request?
This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.
var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
data:{
param: myJson
}
});
As the JSON object is not present in older browsers you should include Douglas Crockfords json2 library
If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode
If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org
Just encode the array and send it as part of your AJAX recuest:
http://www.openjs.com/scripts/data/json_encode.php
There are too many others encoders, or even plugins for JQuery and Mootools :D
Here's an example:
var arr = [1, 2, 3];
$.ajax({
url: "get.php",
type: "POST",
data: {ids:arr},
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
In get.php:
echo json_encode($_POST['ids']);
Array will be converted to object using {ids:arr}, pass the object itself and letting jQuery do the query string formatting.