I'm having a problem reading JSON; my PHP server encodes an object created with the stdClass, then sends this object on my Ajax asynchronous script. I tried to alert the object and the
representation is like this:
alert(prova) //Gives {"idProva":"3","name":"test"}
Now if the variable name is prova, how can I read the value 3?
I tried using prova.idProva, but it doesn't work.
try parsing json into a object
var json = '{"idProva":"3","name":"test"}',
obj = JSON.parse(json);
alert(obj.idProva);
i hope this will help
In ajax all add dataType:'json'
$.ajax({url: '',
dataType: 'json',
type: 'GET',
success: function (prova) {
alert(prova.idProva);
}
);
This may help you,
var data = {"idProva":"3","name":"test"}
console.log(data['idProva']);
Related
So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.
My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.
Good day guys, I'm using jQuery-form to submit a multipart form.
This is my PHP code:
foreach($addedData as $key => $value)
$result[$key] = $value;
echo json_encode($result);
Javascript:
function showResponse(responseText){
alert(responseText);
}
$('button').click(function(){
$("form").ajaxForm({
success: showResponse,
clearForm: true,
dataType: "json",
contentType: "application/json; charset=utf-8"
});
});
With this, the response was [object Object]. But when I removed these two lines:
dataType: "json",
contentType: "application/json; charset=utf-8"
The response became:
{"key1":"val1","key2":"va2","key3":"val3"}
My questions are: Do I really have to remove those two lines? And how can I get the values of the responseText using Json?
By having the dataType:"json", .. you are telling the request that you want the returned item to be an object (like $.parseJSON(responseText);). Without it you will be given plain text.
To print the object you will need something like this:
function showResponse(responseObj){
$.each(responseObj,function(i,v) {
alert(i+' = '+v);
});
}
If you specify dataType: 'json' then your success callback function will be passed the object the JSON represents, rather than a JSON string. jQuery implicitly handles converting the responseText to the object for you, so you don't have to do JSON.parse(responseText) for yourself. If the response isn't valid JSON, the success callback won't be executed; even if the AJAX request returned successfully.
To get the values out, just use responseText like any other Javascript object; though you may want to give it a different name to make it clearer what it actually is.
No you don't, but the alert-box can't display the JSON-object. Try doing Console.log(responseText) instead, and inspecting the result in the developertools in your browser. [object Object] is a object literal
If you remove the lines then you get string ('{"key1":"val1","key2":"va2","key3":"val3"}') in JavaScript (because it use respone as file with text/text mime tipe), if you don't then you get Object ({"key1":"val1","key2":"va2","key3":"val3"}), so I think you should not remove them, if you want loop though this for example. By the way, when you alert an object JavaScript convert object to string (always '[Object object]').
don't remove the below code from your script and add the below code you will get the alert correctly
dataType: "json",
contentType: "application/json; charset=utf-8"
var htmlstr;
for(var i in responsetext)
{
htmlstr += i +"="+responsetext[i]+"\n";
}
alert(htmlstr);
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);
I have this ajax request,
$.ajax({
url : '<?php echo current_url(); ?>',
data : "txtKeywords="+$("#txtKeywords").val()+"&search=Search For Item",
type : 'POST',
dataType : 'JSON',
success : function(html)
{
console.log(html);
}
});
return false;
I get the following in my console,
[{"productId":"5","productTitle":"Small Brasserie Dining Table","productPath":"small-brasserie-dining-table\/","productRangeId":"6","productSecondaryRangeId":"0","productTypeId":"2","productRefNo":"0080","productShortDesc":"","productBestSeller":"0","productFeatured":"0","productIsSet":"0","productPrice":"275","productSavingType":"none","productSavingPrice":"0","productSavingMessage":"","productDimWidth":"90","productDimHeight":"74","productDimDepth":"90","productTechnical":"Powder coated aluminium frame with welded joints.","productTemplateId":"5","productMetadataTitle":"","productMetadataKeywords":"","productMetadataDescription":"","productBandingColour":"grey","productActualPrice":"275","rangeTitle":"Dining","parentRangeTitle":"Aegean","fullRangePath":"aegean\/dining\/","fullProductPath":"aegean\/dining\/small-brasserie-dining-table\/","hasImage":"0"}]
But when I do something like,
alert(html.productTitle)
all I get is undefined?
What am I doing wrong?j
Is it because your html variable is an array? Wouldn't you have to do...
alert(html[0].productTitle);
Try html[0].productTitle, I have run into this problem a few times.
Try using Jquery's JSON ajax function instead of the $.ajax it will parse the JSON for you.
http://api.jquery.com/jQuery.getJSON/
try doing something like this:
alert(html.d); // this will show the result of your ajax call
i don't know what the reason is to use the property 'd' but if you can take a look at your result, use a debug tool to see what data is getting back your ajax call.
if you want convert your JSON string to and object, you can do with the following code:
var respuesta = jQuery.parseJSON(html.d);