Undefined parameter in AJAX - javascript

I'm trying to rewrite an AJAX request of mine so I can debug it's responses, so I have moved code from the responses into individual functions. In my original code I was able to get the result returning from the AJAX call, and output it in the success response.
Since moving that code into a separate function and then trying to call that function in the success response, I get the error 'result is undefined'. I'm not familiar enough with JavaScript to know why this is happening, please help.
$.ajax({
type: 'GET',
url: '/api/auth/api/Homepage/GetLinks',
success:displayLinks(result, jqStatus, error),
error: showPolicyLinkError(result, jqStatus, error)
});
function displayLinks(result, jqStatus, error){
$('#numbercontrol').html(result);
console.log("Success Log - Satus:" + jqStatus + " Error:" + error);
}
function showLinkError(result, jqStatus, error){
$('#numbercontrol').html("<p>Unable to return any links.</p>");
console.log("Failure Log - Result: " + result + "Satus:" + jqStatus + " Error:" + error);
}

You should only pass function names without arguments:
$.ajax({
type: 'GET',
url: '/api/auth/api/Homepage/GetLinks',
success: displayLinks,
error: showLinkError
});

Related

Unexpected Identifier with api url

My code takes input from the users, and saves them by functions in local storage to global variables first_name, last_name and domain. I try to pass these variables to the hunterIO api in my code through the function ajaxing using jquery. For some reason the code throws up an unexpected identifier in the url part of the code.
document.querySelector('#url_But').addEventListener("click", ajaxing, false);
function ajaxing() {
$.ajax({
f_url = "https://api.hunter.io/v2/email-finder?
domain="+domain+"first_name="+first_name+"&last_name="+last_name+
"&api_key=[REDACTED]"
// Error gets thrown here ^^ 'Unexpected identifier'
url: f_url,
type: 'GET',
}).done(function(dataObj) {
console.log(dataObj.data.first_name);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error: " + xhr.status + " " + textStatus);
})
};
I am also worried that after fixing this issue another will be thrown up. Because learning api querying through jquery has been a journey from hell.
You have two issues. Firstly, you cannot define a variable inside an object. Move the f_url declaration outside of $.ajax(). Secondly, you cannot have line breaks in a string. You can either place it all on one line, concatenate the separate lines, or use a template literal. Try this:
document.querySelector('#url_But').addEventListener("click", ajaxing, false);
function ajaxing() {
let f_url = "https://api.hunter.io/v2/email-finder?domain=" + domain + "&first_name=" + first_name + "&last_name=" + last_name + "&api_key=[REDACTED]"
$.ajax({
url: f_url,
type: 'GET'
}).done(function(dataObj) {
console.log(dataObj.data.first_name);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error: " + xhr.status + " " + textStatus);
})
};
Finally note the missing & before the first_name property in the URL.
You must pass the url as first param in $.ajax() not declare it inside it as it is a function.
Just declare f_url before the $.ajax() and pass it to the url parameter.

Error in JSON when I am doing a AJAX call in jQuery

I'm getting the following error in the console when I am trying to return a string of JSON from a AJAX call.
Uncaught SyntaxError: Unexpected token
I have added a codepen with the code I am using.
If you click the convert button and look in the console you will see the error.
I cannot for the life of me figure it out.
Thanks.
JB
http://codepen.io/anon/pen/XJvyWq
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + data);
}, 'json')
});
First remove the "=" .
for a string display in the console you can use the methode stringify of the JSON object
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log("Data: " +JSON.stringify(data) );
}, 'json');
});
or for display an object in the console you can juste write :
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log(data );
}, 'json');
});
the result :
Object {To: "CAD", From: "EUR", Rate: "1.3138"}
Remove json at the second parameter as #SnehalShah said and it'll work
$('.convert').click(function(){
$.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + JSON.stringify(data));
});
});
http://jsfiddle.net/1z20m3pL/
Try this way::
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("To: " + data.To);
console.log("From: " + data.From);
console.log("Rate: " + data.Rate);
});
});
Remove the callback=? from the end of the URL you are providing OR remove the 'json' from the .get() method call.
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD", function(data){
console.log(data);
});});
This is because jQuery assumes that when you pass a "callback" parameter in URL and type 'json' that the response will be JSONP. But in this case the server sends a JSON string. Instead of passing "?" if you pass the name of an existing function the error will not be thrown.
The current response by the server is:
{"To":"CAD","From":"EUR","Rate":"1.3138"}
If the Server was responding with JSONP and if the callback you passed was "test" then the response would have been:
test({"To":"CAD","From":"EUR","Rate":"1.3138"})
http://codepen.io/tejzpr/pen/yymQNz?editors=101 explains both cases.

Declaring Variable within AJAX function and Calling It Later (jQuery) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I've got an AJAX function that works correctly but I can't seem to access variables that I'm declaring within the function later in the page. If you look at the below code, you'll see I alert the variable number_rows within the function which works but when I try to log it outside of the function, it comes back as 'undefined.'
var newData = "user_id=" + id;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
var number_rows = response;
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows);
I understand my scope may be off. I tried to move all of my code within the success function but that causing a bunch of other issues so the easiest thing would be to get the response variable to be a global variable that I could use throughout the rest of the page's code. I also tried something like this:
success:function(response){
$('body').append('<span class="ajax_response" id="' + response + '"></span>');
}
var number_rows = $('.ajax_response').attr('id');
console.log(number_rows);
But for some reason it isn't able to pick up the ID value immediately that way. I can confirm that the span does get made with the correct ID value but for some reason it doesn't handle it correctly. Any help with this would be greatly appreciated.
Thanks!
Just add to your configuration:
async:false
Your code maybe look like this:
var newData = "user_id=" + id;
var number_rows = ""; //This is a global variable
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType:'text',
data:newData,
async:false, //<------This is the option you must add
success:function(response){
number_rows = response; //<----- receive data from the server
alert(number_rows);
},
error:function (/*stuff here*/){
//stuff here
}
});
//Check data
console.log(number_rows);
Good luck ^^!
Changed the scope of your variable.
Change async: false or wait till you get the response from server, then use the value.
var newData = "user_id=" + id;
var number_rows = ""; //Declare Here
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
async: false,
success:function(response){
number_rows = response; //assign here
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows); //Use here
Yes, your scope is off. If you defining a variable inside a function, as you do, you cannot access it outside. Also your ajax call is async and any code you.
Put your console.log inside the success function otherwise it will probably log undefined even if you declare the variable globally outside of the function.
var newData = "user_id=" + id;
var number_rows;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
number_rows = response;
alert(number_rows);
console.log(number_rows); // here, so we are sure it's set.
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});

$.getJSON parsererror trying to call API

I'm trying to use the Clipped API (http://clipped.me/api.html) that returns JSON but am running into some trouble. I'm using getJSON, and in Chrome's JS console I get these error messages:
Resource interpreted as Script but transferred with MIME type text/html: "http://clipped.me/algorithm/clippedapi.php?url=callback=jQuery1910859611126…emo-day-2013-still-looking-for-the-next-airbnb-or-dropbox/&_=1364420105379".
Uncaught SyntaxError: Unexpected identifier
Request Failed: parsererror, Error: jQuery19108596111265942454_1364420105378 was not called
And here's my JS:
var clippedAPI = "http://clipped.me/algorithm/clippedapi.php?url=[URL]callback=?";
$.getJSON(clippedAPI, "http://pandodaily.com/2013/03/26/y-combinator-demo-day-2013-still-looking-for-the-next-airbnb-or-dropbox/" ).done(function(json) {
console.log("JSON Data: " + json.title );
}).fail(function(jqxhr, textStatus, error){
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
This is my first time trying to make something with an API or JSON at all, so I'm really not sure what to do here. I've tried Googling around but can't find anything. The data that I'm actually sending is getting cut off by this jQuery notice that appears when I add callback=?
Your parameter will not simply "guess" what the [URL] param is. Try this:
var clippedAPI = "http://clipped.me/algorithm/clippedapi.php";
$.ajax({
url: clippedAPI,
type: "GET",
dataType: "JSONP",
data: {
url: "http://pandodaily.com/2013/03/26/y-combinator-demo-day-2013-still-looking-for- the-next-airbnb-or-dropbox/"}
}).done(function(json) {
console.log("JSON Data: " + json.title );
}).fail(function(jqxhr, textStatus, error){
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
Even this fails, however, as your API endpoint does not seem to understand/support JSONP and does not provide a Access-Control-Allow-Origin header. You therefore have two choices:
You can reverse-proxy the API locally to get around the cross-domain issue and go through standard JSON
You can...ehm... get a better API? Lodge a ticket with the devs to get it sorted.

Jquery post success variable scope

I'm trying to return the ajax success array from one function to another. For some reason I don't seem to be able to pass the data stored in a variable in the success part of the ajax function into the parent function to return.
I looked at this post to try and figure things out, but not such luck:
jQuery Ajax call - Set variable value on success
Thanks so much for any assistance.
Here's a simplified version of the code:
// make json_to_return global
var json_to_return;
function loop_through_data(){
// call the load_days function and put its array data into days_array
var days_data = load_days(03,2010);
// I'd like to be able to iterate through days_data here
//
//
}
function load_days(selectedMonth, selectedYear){
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
return json_to_return;
}
This part of your function happens later:
success: function(available_json){
json_to_return = available_json;
}
So the variable you're returning is undefined, because the code to set it doesn't happen until the response comes back from the server. Either call the rest of the code to run from your success function, so it'll run when the data's ready, or set async:false (less desirable because it locks the browser).
The async: false method is like this:
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
json_to_return = available_json;
},
error: function(msg){
alert("error " + msg);
}
});
The better approach:
$.ajax({
type: "POST",
dataType: "json",
url: "../includes/get_availability.php",
data: "month=" + selectedMonth + "&year=" + selectedYear,
success: function(available_json){
loopThroughTheDaysAndDoStuff(available_json);
},
error: function(msg){
alert("error " + msg);
}
});
$.ajax is an asynchronous function.
It means that when called, the function keeps executing.
In your code provided var days_data = load_days(03,2010); this happens:
Start an ajax call (asynchronous, function keeps executing)
return json_to_return (undefined)
days_data == undefined
ajax call finishes, json_to_return gets assigned (this can happen in any timespan)
You should rethink your logic, and start coding around the asynchronousity of the ajax call.
A first approach might be passing a function (callback) to load_days which should be called AFTER the success of the ajax call.

Categories

Resources