How To Reduce Multiple Ajax Calls - html

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>`

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.

Database Not Showing Data in Json Ajax

This is my view file Book.cshtml script section. The problem coming is that it not fetching my data from my database.
Instead it is giving a error:
alert("Failed! Please try again.")
If I truncate the data from the database it shows ONLY the heading "BOOK ID" "BOOK NAME" "BOOK SERIAL NUMBER" "BOOK AUTHER" "BOOK PUBLISHER NAME"
$(document).ready(function () {
// This is for Get All Data
$("#btnAllBook").click(function () {
$.ajax({
url: "#Url.Action("GetAllBook","Books")",
data: "",
type: "GET",
dataType: "json",
success: function (data)
{
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
// this will use for Get Data based on parameter
$("#btnSearch").click(function () {
$.ajax({
url: "#Url.Action("GetBookWithParameter", "Books")",
data: { prefix: $('#txtSearch').val() },
type: "GET",
dataType: "json",
success: function (data) {
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function loadData(data) {
// Here we will format & load/show data
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Book ID</th>');
thead.append('<th>Book Name</th>');
thead.append('<th>Book Serial Number</th>');
thead.append('<th>Book Auther</th>');
thead.append('<th>Book Publisher</th>');
tab.append(thead);
$.each(data, function (i, val) {
// Append database data here
var trow = $('<tr></tr>');
trow.append('<td>' + val.BookID + '</td>');
trow.append('<td>' + val.BookName + '</td>');
trow.append('<td>' + val.BookSerialNumber + '</td>');
trow.append('<td>' + val.BookAuther + '</td>');
trow.append('<td>' + val.BookPublisher + '</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#UpdatePanel").html(tab);
};
});
Looking into the documentation on http://api.jquery.com/jquery.ajax/, the callback error is called because the request failed. Then, I suggest you to check if the url #Url.Action("GetAllBook","Books") is returning the right string of the url, maybe you are trying to request in a url that doesn't exists.
Another point, being about a GET request, I suggest you to check opening in a browser if this URL that you are trying to return data, is returning the JSON data expected as you need to append to the HTML.

Trouble to fetch data from JSON

Am working in jQuery Mobile and PhoneGap.
Currently I have a Trouble to fetch data from JSON.
My JSON format is ;
{
payment: {
1: "Visa",
2: "American Express",
3: "Mastercard/Eurocard",
4: "Visa – Verified by Visa",
5: "Mastercard/Eurocard – Securecode"
}
}
And Its XML will looks like this ;
<payment>
<1>Visa</1>
<2>American Express</2>
<3>Mastercard/Eurocard</3>
<4>Visa – Verified by Visa</4>
<5>Mastercard/Eurocard – Securecode</5>
</payment>
I want to fetch the details in to a selectbox.
and My Code is ;
function loadpayment() {
$.ajax({
url: 'https://www.sample.net/json/jsn_payments.php?json=1&rcg_mobile=2',
data: '',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain: true,
cache: false,
async: false,
success: function (data, textStatus, jqXHR) {
var count = data.payment.length;
var card_type_ = $('#card_type_');
var card_type = '';
card_type_.empty();
card_type += '<option selected="selected" value="">' + BookCar2_Cardtype_label + '</option>';
for (i = 1; i < count; i++) {
card_type += '<option value=' + data.payment.[i] + '>' + data.payment.[i] + '</option>';
alert(data.payment.payment[i]);
alert(0);
}
card_type_.append(card_type);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + "-" + errorThrown);
}
});
}
But Its not working !!! I thinks its a simple mistake but i lost lot of time to solve this issue.. so please help me :(
when you use the json as in the question you cannot access them as property beacuse it is a number remember you cannot define number variable. or cannot access it like array as it is an object.
but it s and object with key so you should be able to acces them like below
obj["1"], obj["2"] etc
in your case try data.payment[i] or just in case data.payment[i.toString()]
also just notices you are using for loop as it s an array but it not so data.payment.length returns undefined. you should use foreach loop for payment, try below code.
for (var key in data.payment)
{
card_type += '<option value=' + data.payment[key] + '>' + data.payment[key] + '</option>';
alert(data.payment[key]);
alert(0);
}
Instead of using a for loop, use $.each()
$.each(data.payment,function(key,option)
{
card_type_.append('<option value="'+key+'">'+option+'</option>');
});
Other than that, I would say data.payment.[i] should be data.payment[i]
*and as cfs pointed out the missing quotes for value=""
I'm not exactly what error you're seeing, but I can see that the HTML you are creating is not valid: you're missing quotes around the value attribute in your option elements.
EDIT You are also accessing your arrays incorrectly. You don't need a dot between the data.payment and the [i]
Try this instead:
card_type += '<option value="' + data.payment[i] + '">' + data.payment[i] + '</option>';
I have put your JSON code inside a JSONLinter and it seems your JSON code is invalid.
You should use this code instead:
{
"payment": [
"Visa",
"American Express",
"Mastercard/Eurocard",
"Visa – Verified by Visa",
"Mastercard/Eurocard – Securecode"
]
}
You can also use $.each instead of the "for".
Finally I got the Solution :-)
And My code is :
function loadpayment(){
$.ajax({
url: 'https://www.sample.net/json/jsn_payments.php?json=1&rcg_mobile=2',
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success: function(data, textStatus, jqXHR){
var count = data.payment.length;
//alert(count);
var card_type_=$('#card_type_');
var card_type = '';
card_type_.empty();
card_type +='<option selected="selected" value="">'+BookCar2_Cardtype_label+'</option>';
for (var key in data.payment)
{
card_type += '<option value=' + data.payment[key] + '>' + data.payment[key] + '</option>';
}
card_type_.append(card_type);
},
error: function(XMLHttpRequest, textStatus, errorThrown){alert(textStatus +"-"+ errorThrown);}
});
}
Thank you.. # Onur TOPAL!!

Unable to recieve JSON from Webmethod using $.getJSON or Ajax call

I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help

Read Json Value using Ajax/Jquery

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