Unexpected Identifier with api url - javascript

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.

Related

Jquery post and missing data

I'm retrieving an a list of sites, groups, and users. I'm concatenating and placing them in their respective variable, sending them in a query string to an aspx file.
var url = (Page._BASE_URL + 'Mo/Un/Unis/Unifie.aspx?' + getUserSecurityParameter() +
'&action=sending&userIds=' + encodeURI(userIds) +
'&siteName=' + encodeURI(site) +
'&groupName=' + encodeURI(groupName) +
'&siteList=' + encodeURI(siteList) +
'&team=' + encodeURI(team) +
'&users=' + encodeURI(users)+
'&site=' + encodeURI(site));
Ii'm using this code to retrieve those values on from the ajax post. I notice when I notice check the aspx source, There's so much data between the groups and sites that the users variable and data is never present.
var siteName = $.getUrlVar('siteName');
var groupName = $.getUrlVar('groupName');
var users= $.getUrlVar('users');
Is there a better way to do this so I won't have this issue? Because of missing users data it throws of a query that is written on the back end. Thanks in advance.
This is what I have now. When I try to send the data over I get an error. I can't see the what the error is unfortunately.
var requestParameters =
{
siteList: siteList,
team: team,
users: users,
siteName: site,
site: site,
group: group,
userId: userId,
securityCode: getUserSecurityParameter()
};
$.ajax({
url: Im._B + 'Mo/Uni/Unif/Ui.aspx/getValues',
type: "POST",
data: JSON.stringify(requestParameters),
contentType: "application/json; charset=UTF-8",
done: function (requestParameters, textStatus, jqXHR) {
var left = Math.floor((screen.width - 545) / 2);
windowManager.openFixed(url, 'DocumentListWindow', left, /* top: */ 10, /* width: */ 1480, /* height: */ 840);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error occurred trying to send the data.');
}
});
Ui.aspx.cs
[System.Web.Services.WebMethod]
public static string getValues(string requestParameters)
{
string mystuff = requestParameters;
return mystuff;
}
ERROR
"{\"Message\":\"Operation is not valid due to the current state of the object.\",\"StackTrace\":\"
Although there is technically no limit to the length of a query string, individual browsers do have limits. Follow Alex's advice and convert this to a post.

Undefined parameter in AJAX

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
});

Passing a Knockout Observable as a parameter to a JavaScript Function?

My Knockoutjs code goes as following:
function chainModel(){
var self = this;
this.total_count = ko.observable();
function get_total_count(number){
$.ajax({
type : "get",
url : "./XYZ/abc.php",
cache : false,
data : {number: number},
success : function(result){
self.total_count($.parseJSON(result));
},
error : function(jqXHR, textStatus, errorThrown){
console.log("Error ! Unable to get step " + $number + " count." + "Error: " + errorThrown + ", Status: " + textStatus);
}
});
}
}
ko.applyBindings(new chainModel());
Inside the get_total_count() function, I am assigning the ajax result to self.total_count observable. Instead, I would like to pass the observable too as an parameter to the get_total_count() function so that I can reuse the same function for more than one observable.
Here's a different approach which is using the the promise semantics of jQuery Ajax calls. Take a few minutes to familiarize yourself with jQuery Deferreds if the concept is new to you, it's worth it.
Quick note: By widely adopted convention, constructor names are PascalCase and all other names are camelCase in JavaScript. Don't use underscore_separated identifiers (nobody else does).
function ChainModel() {
var self = this;
self.totalCount = ko.observable();
self.otherCount = ko.observable();
function getCount(number) {
return $.get("./XYZ/abc.php", {number: number})
.fail(function (jqXHR, textStatus, errorThrown) {
console.error(
"Error ! Unable to get step " + number + " count." +
"Error: " + errorThrown + ", Status: " + textStatus
);
});
}
getCount(1).done(self.totalCount);
getCount(2).done(self.otherCount);
}
ko.applyBindings(new ChainModel());
Since knockout observables are in fact functions and calling them sets their value, you can directly use them as success callbacks in Ajax calls.
By returning the jqXHR object from getCount(), you get access to the promise functions it exposes. So instead of passing in the target observable into getCount() you could pass it to the .done() callback, thus assigning the result of the Ajax call to it. Effectively this is separation of concerns and makes your code more flexible.
Other notes:
You should not have to force cache: false in an Ajax call. Set the appropriate Cache-Control header on the server side and the browser won't cache the call.
jQuery automatically parses the response for you, manually calling $.parseJSON() is not necessary.
Isn't it as simple as passing the observable as an argument?
function chainModel(){
var self = this;
this.total_count = ko.observable();
get_total_count(this.total_count, this.number);
function get_total_count(observable, number){
$.ajax({
type : "get",
url : "./XYZ/abc.php",
cache : false,
data : {number: number},
success : function(result){
observable($.parseJSON(result));
},
error : function(jqXHR, textStatus, errorThrown){
console.log("Error ! Unable to get step " + number + " count." + "Error: " + errorThrown + ", Status: " + textStatus);
}
});
}
}
ko.applyBindings(new chainModel());
Are you calling this method "get_total_count()" via any event binding. If so, then you can pass entire data view model to this method.
<input data-bind="event:{ click: function(data,event){ get_total_count(data,event,total_count()); } }" />

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.

Categories

Resources