Read Json Value using Ajax/Jquery - json

I want to read and assign value to a DIV as it is printed on this web service http://abc.com/new2/app/android/get_product_size.php?productID=113
For example get_product_size.php page may return Text or Number.
I have used following code for the same, the problem is its returning 0 Value when i do an alert.. my code is as follows
<div class="home%%GLOBAL_ProductId%%"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var productsize = $('.siz').val();
var id =%%GLOBAL_ProductId%%;
var AllData="" ;
var html="";
//alert(id);
$.ajax({
type: "POST",
url: "http://abc.com/new2/app/android/get_product_size.php?productID="+id,
data: "{Size:'" + productsize + "'}",
//data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: true,
success: function(msg) {
AjaxSucceeded(msg);
AllData = html.fromhtml(data.d);
$("#home%%GLOBAL_ProductId%%").html(AllData);
//42.toFixed(2);
},
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
});
</script>

AllData = html.fromhtml(data.d);
What is this "data" in your success function ? The success function's signature is
"success(data, textStatus, jqXHR)" ... Try using this one.
Also, you don't have to provide a stringified map like this
data: "{Size:'" + productsize + "'}"
You can just say {"Size" : productSize}.

at this point in your ajax block:
data: "{Size:'" + productsize + "'}",
you should remove the quotes surrounding productSize, like this:
data: "{Size:" + productsize + "}",
whatever value you put on the other side of that colon will be the value that gets returned when you call data.Size

Related

calculatematrix using the javascript API rather than REST

I'm trying to use the calculatematrix API to take a load of destinations and calculate the driving distance to them from a given location (my examples first convert the postcode to a latlng)
Using the REST api and JQuery I can get this to work fine. See this JSFiddle - https://jsfiddle.net/vostrx9m/
$.ajax({
url: 'https://geocoder.api.here.com/6.2/geocode.json',
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: {
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
searchtext: 'TR9 6QA'
},
success: function(data) {
var LatLon = data.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude + "," + data.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude;
$.ajax({
url: 'https://matrix.route.api.here.com/routing/7.2/calculatematrix.json',
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: {
mode: 'fastest;truck;traffic:disabled;',
start0: LatLon,
destination0: '50.395118,-4.934356',
destination1: '50.464852,-5.031908',
destination2: '50.541548,-4.938789',
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
summaryAttributes: 'distance,traveltime'
},
success: function(data) {
for (i in data.response.matrixEntry) {
$('p').append("dest(" + i + "), " + data.response.matrixEntry[i].summary.distance + " meters, " + data.response.matrixEntry[i].summary.travelTime + " seconds<br\>");
}
}
});
}
});
However our site uses MooTools, so I've rewritten this against mootools and I now get CORS issues. "has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." It looks like the preflight gets a permission error - see this JSFiddle here - https://jsfiddle.net/1av2wkye/5/
getDistancesFromPostCode('TR84LP')
function getDistancesFromPostCode(StartPostCode) {
console.log('getDistancesFromPostCode: ' + StartPostCode)
var req = new Request({
method: 'get',
url: "https://geocoder.api.here.com/6.2/geocode.json",
data: {
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
searchtext: StartPostCode
},
onComplete: function(data) {
console.log(data)
var StartLatLon = data.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude + "," + data.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude;
console.log(StartLatLon)
getDistancesFromLatLng(StartLatLon)
},
}).send();
}
function getDistancesFromLatLng(StartLatLon) {
console.log('getDistancesFromLatLng: ' + StartLatLon)
var req = new Request({
method: 'get',
url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
data: {
mode: 'fastest;truck;traffic:disabled;',
start0: StartLatLon,
destination0: '50.4153650,-5.0698703',destination1: '50.4154830,-5.0698890',destination2: '50.473036820553446, -4.707902895605457',
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
summaryAttributes: 'distance,traveltime'
},
onComplete: function(data) {
console.log(data)
for (i in data.response.matrixEntry) {
console.log("dest(" + i + "), " + data.response.matrixEntry[i].summary.distance + " meters, " + data.response.matrixEntry[i].summary.travelTime + " seconds<br\>");
}
},
}).send();
}
Any ideas what MooTools is doing wrong or how I fix that?
If not, I tried a different tactic by writing things against the Javascript API and I got the geoencode working, but I cannot see any reference to the calculatematric API in the JavaScript documentation, any ideas?
Thanks
As the request should be a JSONP type request , i would guess using Request.JSONP from MooTools should help with the CORS issue. HERE Javascript API does not have support for the calculate matrix end point of the API.

How To Reduce Multiple Ajax Calls

I'm Developing A windows Phone 7 Application Using Phone Gap.Language Used[HTML,css,JavaScript]
I'm using A web Service For Get Json Data Web service And Bind In Drop Down List.
In Single Page I'M Using 5 AJAX Calls Ex[Age,Height,Religion,Cast,Country,Language,Status,Education]
My Sample Ajax Call For Age given Below.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "https://www.xxxxxxxx.com/yyyyyyyy/zzzzzzzzzz.svc/GetMasterDataoverHTTPS?AuthToken=" + encodeAuthtoken + "&ListKey=" + encodeListkey + "&ListValue=" + encodeMinAge,
crossDomain: true,
dataType: "jsonp",
success: function (data) {
var result = data;
$.each(result, function (key, value) {
var appenddata = "<option value = '" + value.ListKey + "'>" + value.ListValue + " </option>";
$('#ddlSFromAge').html($('#ddlSFromAge').html() + appenddata);
});
//alert(result);
},
error: errorResponse
});
function errorResponse(xhr, ajaxOptions, thrownError) {
alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);
}enter code here
For Each And Ever Drop Down I call Like This . I know This Is Not Good.
Any One Tell Me How To Reduce This AJAX call's [For Each Drop down Separate URL Used]
I am guessing you are using so many ajax calls because the data types are dynamic? If they are not dynamic, then you should really consider using the device sqlite database to store your values and just query that. Documentation can be found here.
If you really really need to make that many calls because the data is dynamic then so be it. But instead of having 5 seperate AJAX functions you can just use 1 function and either pass the function your url you want it to use function ajaxCall('http://www.myserviceurl') or pass it a value to run agains a switch to determine what url to use.
I Changed My Code Like This Credits Go To #Dom
<script type="text/javascript">
doAjaxCall("Country");
doAjaxCall("Language");
doAjaxCall("religion");
doAjaxCall("Caste");
function doAjaxCall(type) {
var url;
switch (type) {
case "Country":
url = "https://www.xxxxxx.com/yyyyyyy/GetCountryoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlCountry');
break;
case "Language":
url = "https://www.xxxxxx.com/yyyyyyy/GetLanguageoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlLanguage');
break;
case "religion":
url = "https://www.xxxxxx.com/yyyyyyy/GetReligionoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlReligion');
break;
case "Caste":
url = "https://www.xxxxxx.com/yyyyyyy/GetMotherTongueoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlMother');
break;
default:
url = ""; //or some other code to execute if type doesnt match anything
}
function ajaxCall(paramurl,paramControlId) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
crossDomain: true,
dataType: "jsonp",
success: function (data) {
var result = data;
$.each(result, function (key, value) {
var appenddata = "<option value = '" + value.ListKey + "'>" + value.ListValue + " </option>";
$(paramControlId).html($(paramControlId).html() + appenddata);
});
//alert(result);
},
error: errorResponse
});
function errorResponse(xhr, ajaxOptions, thrownError) {
alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);
}
}
}
</script>`

creating an array and sending to ajax

I'm trying to gather information from all of the textareas on my page, and then put that information into an array so I can send to the server via ajax/json.
Although I am not quite sure how to go about doing it.
I'm not sure how to pull the information I need from the
Here is what I have so far:
Example of my HTML
"<textarea id='tbObjective_" + counter + "' name='txtObjective' class='objectives' sequence='" + counter + "'></textarea>"
jQuery:
var objectiveList = [];
$('.objectives').each(function (objective) {
objectiveList.push({
id: objective.id,
sequence: objective.sequence,
text: objective.val()
});
});
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: objectiveList
});
Any help would be appreciated
Thanks
you can proceed with the following procedure. i have used python django and html5 for the purpose
1. make a text box which is hidden and after generating your json document set it in this text box (suppose id of textbox is "submit_json") than use
$("#submit_json").val(JSON.stringify(formData, null, '\t')), // (formData, null, '\t') this is js function that i have written for the ourpose
data = JSON.stringify({"jsonDoc":Generated JSON})
console.log(data);
$.ajax({
url: 'http://127.0.0.1:8000/catchjson/',
type: 'POST',
async: false,
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false,
success: function(data){
alert('Done')
//Goto Next Page
},
error: function(jqXHR, textStatus, errorThrown){
alert("Some Error!")
}
})
Now on server you can catch this json if u have problem creating json from your text box let me know
I often use:
var formData = $("form").serialize();
for posting data over ajax, so maybe you could try:
var textareaData = $(".objectives").serialize();
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: textareaData
});
or alternatively make sure all the fields are in a form element and use the first example.
You can parameterise it with $.param(objectiveList)
see jQuery.param()

How to display json feed to user?

I have a valid json feed that I am pulling from the server by accessing a php file using jquery. An example of the json feed returned from querying the php file is
{"items":[{"acc_number":"11111","acc_name":"TestAccount","demographics":["Some
Street","SomeState","99999"],"last_thirty":null,"phone":null,"sms":null,"email":null}, {"acc_number":"22222","acc_name":"MyAccount","demographics":"MyStreet","MyState","99999"],"last_thirty":null,"phone":null,"sms":null,"email":null}],"total_items":"80","md5sum":"c7a834d45bdf348abfdcdb95994c7608"}
I am using the code below which I though would go through feed and bring down all of the records and fields that were not NULL. But I am not getting anything.
$.ajax({
type= 'GET',
url: 'http://MyURL.com',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var items = [];
$.each(data, function(key,val) {
items.push('<li id="' = key = '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
});
}
Any help/tips is appreciated as always.
Thanks!
Updated based on answers below.
$(document).ready(function() {
testNews();
});
function testNews() {
$('body').append('<h1>News</h1>');
$('body').append('<h2>Main Display</h2>');
$('body').append("<div id='success_news_main' class='waiting'>Waiting for response</div>");
$.ajax({
type: "GET",
url: 'http://MyURL.com/news.php',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var ul = $('<ul/>').addClass('my-new-list').appendTo('body');
$.each(data.items, function(k,v) {
$('<li/>').attr('id', k).html(v).appendTo(ul);
});
}
});
}
Try iterating over data.items and not over data as this is your collection:
success: function(data) {
var items = [];
$.each(data.items, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
...
}
Also your items.push method seems broken with those multiple = characters. You probably meant +.
Another remark is the val variable inside the $.each statement. It will be an object. You probably want to select a specific property from this object, like:
items.push('<li id="' + key + '">' + val.acc_number + '</li>');
And the key will be the index of the array. And because ids in HTML cannot start with a number if you want to have valid HTML you might need to prefix your li id:
items.push('<li id="item_' + key + '">' + val.acc_number + '</li>');
You shouldn't use string concatenation when forming the html tags for display. Instead use jQuery's functions create the dom elements, add attribute values to them and add them to the page.
Here's a suggestion on modifying your code:
$.ajax({
type= 'GET',
url: 'http://MyURL.com',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var ul = $('<ul/>').addClass('my-new-list').appendTo('body');
$.each(data.items, function(k,v) {
$('<li/>').attr('id', k).html(v).appendTo(ul);
});
}
});
This is also easier to read and doesn't look through the array twice.
Also, the "v" variable within "$.each" will be the objects of the array within the json. You'll need to access their individual properties and create the necessary html/elements within the li instead of setting it directly as the html property.
Iterate over the data.items since the JSON returns the values in that array. This code example also fixes "=" where "+" should have been.
$.ajax({
type= 'GET',
url: 'http://MyURL.com',
dataType: 'json',
username: myusername,
password: mypassword,
success: function(data) {
var items = [];
$.each(data, function(key,val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
});

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);