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>
Related
I'm working on making an API call in PhoneGap. I wrote a function and calling it from a button click event, and I'm getting a response too, but I want to know how to display it. I have tried, but it's not working.
function getContactList() {
console.log("Entering getContactList()");
$.ajax({
url: "https://api.androidhive.info/contacts/",
dataType: "json",
cache: false,
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success: function(json) {
console.log("====CONTACTLIST ---->", json);
$(json).find("contacts").each(function() {
var html = '<li>' + $(this).find("name").text() +
' ' + $(this).find("name").text() + '</li>';
$('#contacts').append(html);
});
}
});
}
You're receiving JSON string which is then automatically converted by jQuery to a JavaScript object, so you can interact with it directly and shouldn't convert it to a jQuery object like $(json). Change the code inside your success to this:
for (var i = 0; i < json.contacts.length; i++) {
var c = json.contacts[i];
var html = '<li>' + c.name + ' ' + c.email + '</li>';
$('#contacts').append(html);
}
Note: it seems that there is an error in your code, you're using the find("name") twice. I changed it to name & email, but you can use any property of the contacts that you're getting.
First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks
I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>
Hi guys so i made a code that parses a CSV file into a JSON ARRAY with PHP. So when you go to this URL you get the PHP output:
http://www.jonar.com/portal/mynewpage.php
Now i used this code to append my JSON ARRAY to HTML but now things have changed since i am using PHP i am not sure how to use it and what to do differently.
Also my ajax call is always empty which is weird..
$.ajax({
type: 'GET',
url: 'http://www.jonar.com/portal/mynewpage.php',
dataType: 'jsonp',
success: function(response) {
alert(response);
}
});
I used this to append my JSON ARRAY but now if i can get the response do i use the same code or will it have to be altered?
$.each(results.data.slice(1), // skip first row of CSV headings
function(find, data) {
var title = data.title;
var link = data.link;
var date = data.date;
var type = data.type;
var where = data.where;
var priority = data.priority;
if (priority == '1') {
$('ul.nflist').prepend($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
} else if (where == 'pp', 'both') {
$('ul.nflist').append($('<li>', {
html: '' + title + ' ' + ' ' + '<span class="category">' + type + '</span>'
}));
}
});
the reason i used PHP is to avoid cross domain issue
Thanks for the help guys!
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);
}