I Have a jQuery Post to a PHP page with generates a JSON Response. It successfully generates JSON because I have it display the whole response. But on the .each I cannot get it to alert. Any Ideas Appreciated. Thank You. The JSON looks like:
[{"Part_Field":"Part_Note:3","Part_Value":"ValueofPart"},{"Part_Field":"Ft_In:3","Part_Value":"12"}, ...
jQuery:
$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){
var d = document.getElementById("displayjson");
d.innerHTML = data;
$.each( data, function( key, value ) {
alert( value.Part_Field );
});
});
You forgot the string },"json"); in the end.
The corrected code should be:
$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){
var d = document.getElementById("displayjson");
d.innerHTML = data;
$.each( data, function( key, value ) {
alert( value.Part_Field );
});
},"json"); // Here, you need to tell jQuery that whatever response
// we are getting from server is a JSON string, in your case,
//it was considering it as a string.
Related
My ajax retrieves the following response in the console:
PHP
$checkout_session_data = json_encode(['id' => $checkout_session->id]);
wp_send_json_success( $checkout_session_data );
// this is then retuend to the JS ajax function.
data: "{\"id\":\"cs_test_a1SOgBGIPsRrECu5pP8TDCW16JYMMHnGnmfh7Lp6qf8bvwTk3hK97sI7e7\"}"
success: true
I'm unclear how to get the ID value from the response from within the .done part of my ajax function.
.done( function(response) {
if( response.success == true ) {
console.log(response);
}
Attempts:
console.log(response.data.id);
console.log(response[0].id);
Your data is double encoded, wp_send_json_success encodes the data passed to it to JSON so do not json_encode your data before you pass it to wp_send_json_success,
$checkout_session_data = ['id' => $checkout_session->id];
wp_send_json_success( $checkout_session_data );
.done( function(response) {
if( response.success == true ) {
console.log(response.data.id);
}
}
Instead of using the ajax request, you would be better served by using the getJSON function here. A sample of the code is shown below.
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
});
You can find further details from this link https://api.jquery.com/jquery.getJSON/
I am a beginner in Javascript. I hope to get some help.
I built a local server using MAMP, and all my files are local. I want to read a value from a json file. This json file(data.json) has only one item {"type":2}, and I only want to use the value(2 in this case). But the value of "type" changes, so Javascript should read it constantly and maybe save it into a var in Javascript.
Can I listen for changes to that file so that I can be sure I always have the most up to date value for type?
I am still not familiar with Javascript. I would really appreciate it if you could give me some specific codes or examples.
//Either
var json = {test:"test"};
console.log(json);
//Access JSON
console.log(json.test);
//Or
$.getJSON( "test.json", function( data ) {
//Assign the json to your JSON variable
json = data;
});
console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JSON can come from anywhere, inbuilt into jquery is parseJSON which will return the json input string as a javascript object.
http://api.jquery.com/jquery.parsejson/
var obj = $.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
where the json can come from anywhere.. an ajax call or where ever else.
$.ajax({
url:'some url',
data: someobject,
type: 'get',
success: function( responseFromServer ){
var obj = $.parseJSON( responseFromServer );
alert( obj.name === "John" );
}
});
this is my first question here! New to using Ajax, and have hit an issue that maybe someone could catch what I am doing wrong.
var featuredList;
$.ajax({
url: "myurl",
type: 'GET',
success: function(result){
featuredList = JSON.stringify(result);
alert(result);
$.each( result, function( key, value ) {
alert('not working');
});
},
error: function(){alert('error');}
});
I have gone this path before with no issues, this time around I cannot get inside the loop. The alert(result) is returning my data just fine.
Thanks!
Hi,
Hope this might help you to process JSON data received from AJAX request, try below code:
jQuery.ajax({
url:'myurl',
dataType: "json",
data:{
classId:'C001'
},
type: "GET",
success: function(data) {
for (var j=0; j < data.length; j++) {
//syntax to get value for given key
//data[j].yourKey
var userId = data[j].userId;
var name = data[j].name;
var address = data[j].address;
}
}
});
Thanks,
~Chandan
As per your code try doing this:it should work
var data = JSON.parse(result);//here result should be json encoded data
$.each( data, function( key, value ) {
alert(value);
});
Use jQuery promises, gives you more semantic and readable code
var featuredList;
$.getJSON("myurl", {"optional": "data"})
.done(function(data){
// successful ajax query
$.each( data, function( key, value ) {
// do whatever you want with your iterated data.
});
});
.fail(function(){
// catch errors on ajax query
});
I do it this way
$.getJSON('url',
function(dataList) { // on server side I do the json_encode of the response data
if(dataList !== null) {
$.each(dataList, function(index, objList ) {
// rest of code here
});
}
});
Hope this works for you as well.
function getArray(){
return $.getJSON('url');
}
var gdata = [];
getArray().then(function(json) {
$.each(json, function(key, val) {
gdata[key] = val ;
});
console.log(gdata);
I had the Same Problem It took 2 days to got the solution.
You have to resolve the promise and return the json object to access the value.
You could easily do this using the open source project http://www.jinqJs.com
/* For Async Call */
var result = null;
jinqJs().from('http://.....', function(self){
result = self.select();
});
/* For Sync Call */
var result = jinqJs().from('http://....').select();
You can also use $.Json to get your solution , here is an example
$.getJSON('questions.json', function (data) {
$.each(data,function(index,item){
console.log(item.yourItem); // here you can get your data
}
}
You can use or print Index if you want it. Its show the data index.
Hope it may help you, I am exactly not sure its your requirement or not, But i have tried my best to solve it.
This will work as the result from ajax call is a string.
$.each($.parseJSON(result), function( key, value ) {
alert('This will work');
});
I am trying to loop through some data received from a page, and if the price of the item (it's in the data) is under a certain amount I want to make an alert. But I was wondering how I can successfully loop through all the data from this site.
http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&PageNumber=1&LegendExpanded=true&Category=2
I think I can do the part of the alerts and such if I can just figure out the looping.
setTimeout(function(){
var myjson;
var page = 1;
$.getJSON("http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&PageNumber="+page+"&LegendExpanded=true&Category=2", function(json){
myjson = json;
alert(myjson[0].Description);
});
//var new_json = JSON.parse(myjson);
}, 2000);
Try this
$.getJSON("http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&PageNumber="+page+"&LegendExpanded=true&Category=2", function(json){
$.each(json, function(i, field){
console.log(field["Description"]);
});
});
You need to parse the JSON string to an object.
var obj = jQuery.parseJSON( '{ "foo": "bar" }' );
alert( obj.foo );
http://jsfiddle.net/w2xcT/
I'm rendering page using ajax and json. Structure of my json is {"status":"ok","rewards":[{"id":201,"points":500},{"id":202,"points":500}]
How do i make ajax loading data only once one if 'points' duplicates in any of hashes?
E.g. i have json with few hashes in which 'points' have same value
Here is my code
$("#page").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/file.json",
dataType: "json",
error: function (data, tex
tStatus){
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var seen = {};
$.each(data.rewards, function(key, val){
lis += "<div class = 'reward-ui ui-block-" + String.fromCharCode(97 + key%3) + "'><a href ='#' class ='ui-link-inherit'>" + val.points + "</a></div>";
});
$(".ui-grid-b").html(lis);
});
//$('.even-odd').listview('refresh');
})
});
Add a local array which will store all the items used. Push into this array in $.each function and before doing lis += " " check if the value already exists in the temp array.
Other than that you could try server side sorting before retrieving data ... like suggested above.