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!!
Related
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.
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>`
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
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');
});
});
I am trying to get JQueryUI's Autocomplete code working with an ASMX web service. I am getting close, but hit yet another wall yesterday. The JSON data is being returned in {d:"data"} format (see http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx). My data now looks like:
d: "[{"DOTNumber":"001061010","JobTitle":"Project Architect"},{"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]"
My code is:
$(function() {
function log(message) {
$("<div/").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
});
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(data) {
var safe = data;
response($.map(safe.d, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value);
$get("DOTNumber").value = ui.item.value;
},
});
The problem lies in the success function.
What is the right syntax to get past the "d" issue?
Your data should look like this:
{"d":[{"DOTNumber":"001061010","JobTitle":"Project Architect"},"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]}
It appears you are missing quotes around your "d" and you have extra quotes around your array.
Don't eval() your data - this opens you up to more security issues than the d: prevented.. You should have access to JSON.parse() or if not jQuery.parseJSON() (which wraps JSON.parse() if available... depends on your target platform(s)).
This has been an incredibly difficult process, but I finally got it working. There were a number of hurdles:
1) My JSON return string was getting wrapped in an XML blanket, so it would not parse
2) Solving this problem required the contentType: 'application/json' line
3) With that content type, a POST was required. GET would not work
4) POST required putting the data together using the JSON.stringify. I am still not sure about this one, but I found some code somewhere that did it.
5) Data coming back from the POST was prefixed with a "d " (see: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
6) getting access to the data itself required the "eval(data.d)" line.
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = eval(data.d);
response($.map(output, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
If I ever have this much trouble writing a few lines of code again, I am going to take a very large guage shotgun to my computer!
Bob Jones
If you use a WCF JSON service with the webHttpBehavior (instead of enableWebScriptBehavior), it will not emit the "d"