Adding options to select field using javascript from a json file - javascript

var json = $.getJSON("../category.json", function() {
alert(2);
})
.done(function() {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
var1.innerHTML = "<option value='" + key + "'>" + val + "</option>";
alert(var1);
})
.fail(function() {
alert( "error" );
});
I want to values from json file as options to my select field. But my code always shows alert error. Please tell me what is wrong with it ?

You're not setting your key and value parameters. In fact it doesn't look like you're getting your JSON results at all.
Change your done method to
.done(function( data ) { /* do stuff */ }
Now your JSON results will be stored in data.
Then you may need to loop through the results. See the example here

try this
var json = $.getJSON("../category.json", function(data) {
alert(2);
})
.done(function(data) {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
$.each( data, function( key, val ) {
var1.innerHTML += "<option value='" + key + "'>" + val + "</option>";
alert(var1);
});
alert(var1);
})
.fail(function() {
alert( "error" );
});

Your JSON is not valid: You cannot use a number as a JSON key
[
{
"NAME":"chair",
"0":"chair" <-- error
},
{
"NAME":"bed",
"0":"bed" <-- error
},
{
"NAME":"table",
"0":"tabl‌​e" <-- error
},
{
"NAME":"almira",
"0":"almira" <-- error
}
]
Try running your JSON through an online JSON parser and the error will come up.
Alternatively, change your error handler to include more information
.fail(function (jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText) }
});

Related

How to get phone validator info to display

I'm working with an API that includes validating a phone number and its information. Its works in the console log but will not display on screen itself.
in the (#info).html is suppose to be shown on screen but keeps returing as undeclared, been doing my best to change the wording without the use of dashes but hasn't helped.
Does anyone know what went wrong?
Thank you!
$.ajax({
type: "POST",
url: "https://neutrinoapi-phone-validate.p.mashape.com/phone-validate",
data: { "country-code": country, number: number },
success: function(data){ // if code works in console
console.log( data );
$('#info').html('international-number: ' + data.country + '<br>international-calling-code: ' + data.callingcode + '<br>localNumber: ' + data.localNumber + '<br>countryCode: ' + data.countryCode + '<br>is-Mobile: ' + data.mobile + '<br>type: ' + data.type); // show results on screen
}, // found a way to display code without dashes
error: function(jqXHR,textStatus){; // if code fails
console.log( jqXHR );
console.log( textStatus );
},
beforeSend: function(xhr){ // check for access key before
xhr.setRequestHeader( 'X-Mashape-Key', 'OnHOGDfyMLmshCe0o3CtIU6L4DDZp1sukFtjsn9LynwSBQbznL' );
xhr.setRequestHeader( 'Accept', 'application/json' );
xhr.setRequestHeader( 'Content-Type','application/x-www-form-urlencoded' );
}
});
});
});
There are a number of ways to solve this issue. One includes using [] to access the property names that have dashes in them like so: data['country-code'].
But I noticed you've tried to access some properties that don't exist in the data. You can over come that by using a generic loop like so:
let output = '';
for (item in data) {
output += item + ':' + data[item] + '<br>';
}
That simply builds up a string of each data element's name followed by its value and a <br> tag. Here it is in code:
let country = 'us';
let number = '8881231234';
$.ajax({
type: "POST",
url: "https://neutrinoapi-phone-validate.p.mashape.com/phone-validate",
data: {
"country-code": country,
number: number
},
success: function(data) { // if code works in console
let output = '';
for (item in data) {
output += item + ':' + data[item] + '<br>';
}
$('#info').html(output); // show results on screen
}, // found a way to display code without dashes
error: function(jqXHR, textStatus) {; // if code fails
console.log(jqXHR);
console.log(textStatus);
},
beforeSend: function(xhr) { // check for access key before
xhr.setRequestHeader('X-Mashape-Key', 'OnHOGDfyMLmshCe0o3CtIU6L4DDZp1sukFtjsn9LynwSBQbznL');
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='info'></div>

Writing fail case for ajax call in getJSON

I have following code of ajax call and I would like to write custom error on failed ajax call.In following piece of code block, where I can write the same:
$.getJSON("/ProductMatrix/CaptureCategoryTypeList/" + $("#categoryFilter > option:selected").attr("value"),
function (data) {
var items = "<option> Default </option>";
$.each(data,
function (i, captureCategoryType) {
items += "<option value=' " + captureCategoryType.Value + "'>" + captureCategoryType.Text + "</option>";
});
$("#categoryTypeFilter").html(items);
SherlockAdmin.Shared.closeProcessingWheel();
});
It's as simple as
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});
Code from http://api.jquery.com/jquery.getjson/

cannot get the results to be displayed on the page

I cannot display the results which I got from database:
{"results": ["USA", "Canada"]}
{"message":"Could not find any countries."} //else
I got this error from console:
Uncaught TypeError: Cannot read property 'length' of undefined.
Could you please check my code to find out what is my mistake.
Here is my view:
My Travel Plans
<div id="my_div">
<div id="country_list_is_got"></div>
<div id="country_list_is_not_got"></div>
</div>
Controller:
if ($this->my_model->did_get_country_list($user_id)) {
$country["results"]= $this->model_users->did_get_country_list($user_id);
echo json_encode($country);
}
else {
$country = array('message' => "Could not find any countries." );
echo json_encode($country);
}
JS file:
$("#load_country_list").click(function() {
$.post('cont/get_country_list', function (country) {
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});
});
You need to tell jQuery what content type is coming back from the server (json)
It defaults to 'string' and it has no reason to think that's incorrect.
See the documentation for the correct parameter order.
Your .each iterator is trying to loop over a string, and - obviously - failing.
Edit: As a point of pedantry, why are you using POST to GET data? "Get" is literally in your URL.
I think it should be $.get or the $.getJSON shortcut, instead of $.post
$.getJSON("cont/get_country_list", function( data ) {
console.log(data);
// something like this for list construction and append to body
var countries = [];
// maybe you need data.results here, give it a try or see console
$.each( data, function( key, val ) {
countries.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "country-list",
html: countries.join( "" )
}).appendTo( "body" );
});
Live Demotry this, issue is results contain array.but you try to use key,value
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
for(i=0;i<country.results.length;i++){
var item = $('<div>'),
title = $('<h3>');
title.text(country.results[i]);
item.append(title);
item.appendTo($("#country_list_is_got"));
}
}

How to access result array returned in ajax?

Arg!! I had this working flawlessly and now I am back to banging head against the keyboard.
I want access defined columns inside the array, but I am getting undefined but if I display the results using an alert as detailed in snipped of code below I see the following:
[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}]
***
g
***
e
***
undefined
Here is the Ajax code:
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: "handler=getStActivitySharingList&stu_id="+stu_id,
datatype: "json",
success: function(result){
var count = 0;
if (result !== null)
{
//display results
alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />" + result[0]["firstname"]);
//clears choice list
clearOptions();
//result = $.parseJSON(result); //if this is used cannot display result again
alert (result);
$.each(result, function (i, elem) {
alert("elem"+elem.st_usage_id ); //displays as undefined and won't break
if (elem.st_usage_id === null)
{
count++;
alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
appendOption(elem);
}
});
}
alert(count);
if (count === 0){
noResultsAvailableOption();
}else{
resultsAvailableOption();
}
ShowDialog(false);
e.preventDefault();
},
error: function(){
alert("ajax failure: could not retrieve a list of contacts");
}
});
i not know how you return it from PHP, but in jquery try:
sucess: function (result)
{
console.log(JSON.parse(result)); // parse string to json
}
See json.org
To better answer this question is to implement better debugging procedures.
Here is the code that I used for debugging this issue. The breaking down of the xmlHttpRequest clearly displayed to me that issue was with the data and that I was encountering an illegal character exception when trying to encode the data to json.
A great way to solve any issue is to first implement the correct debugging procedures, and everything else will work itself out.
error: function(xmlHttpRequest, status, error){
alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xmlHttpRequestStr= "";
for(x in xmlHttpRequest)
xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
alert(xmlHttpRequest);
}

How do I loop through a JSON response and inserting into different elements

I'm very limited in javascript knowledge.. i'd appreciate any suggestions..
I've looked through previous JSON questions and answers, but didn't see anything that was similar to this.
I'm using jQuery. I have a JSON server response in the following format:
{
"aNumBids_1": "4",
"aHighBid_1": "100.00",
"aBidAmount_1": "110.00",
"aBidEnd_1": "09/27/2013 17:00",
"aNumBids_2": "42",
"aHighBid_2": "1,210.00",
"aBidAmount_2": "1,260.00",
"aBidEnd_2": "09/27/2013 17:01",
"aNumBids_3": "12",
"aHighBid_3": "1,100.00",
"aBidAmount_3": "1,150.00",
"aBidEnd_3": "09/27/2013 17:02",
"aNumBids_4": "26",
"aHighBid_4": "1,460.00",
"aBidAmount_4": "1,510.00",
"aBidEnd_4": "09/27/2013 17:03",
"aNumBids_5": "32",
"aHighBid_5": "1,210.00",
"aBidAmount_5": "1,260.00",
"aBidEnd_5": "09/27/2013 17:04"
}
the first element of each pair is the element name on the page ( name='aBidAmount_5' ). The second element of each pair is the content to be placed into that element.
How do i go about looping through this json response ?
I've gotten this far:
AJAX.getPrice = function(){
var request = $.ajax({
url: serverScript,
data: JSON.stringify(aItems) ,
dataType: "json"
});
request.done(function() {
// update the element value
/* i'm lost here */
});
request.fail(function(jqXHR, textStatus) {
// If console is available output the error to console log
if (typeof console == "object") {
console.log( "Request failed: " + textStatus +data );
}
});
}
Assuming "element name" is the id of the element, this should work :
request.done(function(data) {
for(var k in data) {
if(data.hasOwnProperty(k)) {
$('#'+k).html(data[k]);
}
}
});
if these are input names then in the done call back use
request.done(function(data) {
for(i in data) {
$("input[name="+i+"]").val(data[i]);
}
});
Js Fiddle: http://jsfiddle.net/vuQLu/
JS:
var output = '<ul>';
$.each(data, function(key, value){
$.each(value, function(key, value){
output += '<li>' + key + ' => ' + value + '</li>';
});
});
output += '</ul>';
$(".myClass").html(output);
Html:
<div class="myClass"> </div>

Categories

Resources