jQuery ajax var line - Uncaught SyntaxError: Unexpected identifier - javascript

I am using jQuery to call get ajax "Uncaught SyntaxError: Unexpected identifier" at line 3.
In here, i removed the original URL due to confidential purpose. but even i remove the csrHost line, the following line also will hit the same error.
Please help. Thanks in advance.
function getCSR(){
$.ajax ({
var csrHost = "https://example.com/jsp/csr.jsp?";
var commonname = '&'+'commonname'+'='+$('#csrName').val().toUpperCase();
var company = '&'+'org'+'='+$('#csrCom').val().toUpperCase();
var city = '&'+'locality'+'='+$('#csrCity').val().toUpperCase();
var state = '&'+'state'+'='+$('#csrState').val().toUpperCase();
var country = '&'+'country'+'='+$('#csrCountry').val().toUpperCase();
var OrgUnit = '&'+'commonname'+'='+$('#csrOU').val().toUpperCase();
var keysize = '&'+'keysize'+'='+2048;
url: csrHost+commonname+company+city+state+country+OrgUnit+keysize,
type: "GET",
//data: {latlng:40.714224,-73.961452}
//contentType: "application/json; charset=utf-8",
success: function(csr){
var textareaResult = $('#textarea1')
textareaResult.html(csr)
}
})
}

Instead of jQuery-slim you need to use standard jQuery. ajax is removed from the jQuery-slim version.
You need to create the url outside of the ajax function. It takes an object as parameter, but you use var inside it.
function getCSR() {
var csrHost = "https://example.com/jsp/csr.jsp?";
var commonname = '&' + 'commonname' + '=' + $('#csrName').val().toUpperCase();
var company = '&' + 'org' + '=' + $('#csrCom').val().toUpperCase();
var city = '&' + 'locality' + '=' + $('#csrCity').val().toUpperCase();
var state = '&' + 'state' + '=' + $('#csrState').val().toUpperCase();
var country = '&' + 'country' + '=' + $('#csrCountry').val().toUpperCase();
var OrgUnit = '&' + 'commonname' + '=' + $('#csrOU').val().toUpperCase();
var keysize = '&' + 'keysize' + '=' + 2048;
$.ajax ({
url: csrHost + commonname + company + city + state + country + OrgUnit + keysize,
type: "GET",
//data: { latlng: 40.714224, -73.961452 },
//contentType: "application/json; charset=utf-8",
success: function(csr) {
var textareaResult = $('#textarea1');
textareaResult.html(csr)
}
})
}
You can also try with this approach, which I think is more beautiful.
function getCSR() {
var csrHost = "https://example.com/jsp/csr.jsp?";
var keyValues = [
{ name: 'commonname', value: $('#csrName').val() },
{ name: 'org', value: $('#csrCom').val() },
{ name: 'locality', value: $('#csrCity').val() },
{ name: 'state', value: $('#csrState').val() },
{ name: 'country', value: $('#csrCountry').val() },
{ name: 'commonname', value: $('#csrOU').val() },
{ name: 'keysize', value: '2048' },
];
var queryString = keyValues.map(item => `${item.name}=${item.value.toUpperCase()}`)
.join('&');
$.ajax ({
url: csrHost + queryString,
type: "GET",
//data: { latlng: 40.714224, -73.961452 },
//contentType: "application/json; charset=utf-8",
success: function(csr) {
var textareaResult = $('#textarea1');
textareaResult.html(csr)
}
})
}

The Definition of Jquery Ajax function defines as
jQuery.ajax( url [, settings ] )
which means you can supply a url and settings (optional).
you are trying to define a bunch of statements, which are invalid in this context and hence the error. You need to pass in an URL or a settings object as specified by the Spec.
Jquery Ajax Specification
For example in your case following would be the right way :
function getCSR() {
var csrHost = "https://example.com/jsp/csr.jsp?";
var commonname = '&' + 'commonname' + '=' + $('#csrName').val().toUpperCase();
var company = '&' + 'org' + '=' + $('#csrCom').val().toUpperCase();
var city = '&' + 'locality' + '=' + $('#csrCity').val().toUpperCase();
var state = '&' + 'state' + '=' + $('#csrState').val().toUpperCase();
var country = '&' + 'country' + '=' + $('#csrCountry').val().toUpperCase();
var OrgUnit = '&' + 'commonname' + '=' + $('#csrOU').val().toUpperCase();
var keysize = '&' + 'keysize' + '=' + 2048;
$.ajax ({
url: csrHost + commonname + company + city + state + country + OrgUnit + keysize,
type: "GET",
//data: { latlng: 40.714224, -73.961452 },
//contentType: "application/json; charset=utf-8",
success: function(csr) {
var textareaResult = $('#textarea1');
textareaResult.html(csr)
}
})
}

You need to extracts the creation of variables from within the ajax function. Like this:
function getCSR(){
var csrHost = "https://example.com/jsp/csr.jsp?",
commonname = '&'+'commonname'+'='+$('#csrName').val().toUpperCase(),
company = '&'+'org'+'='+$('#csrCom').val().toUpperCase(),
city = '&'+'locality'+'='+$('#csrCity').val().toUpperCase(),
state = '&'+'state'+'='+$('#csrState').val().toUpperCase(),
country = '&'+'country'+'='+$('#csrCountry').val().toUpperCase(),
OrgUnit = '&'+'commonname'+'='+$('#csrOU').val().toUpperCase(),
keysize = '&'+'keysize'+'='+2048,
url = csrHost+commonname+company+city+state+country+OrgUnit+keysize
$.ajax ({
url: url,
type: "GET",
success: function(csr){
var textareaResult = $('#textarea1')
textareaResult.html(csr)
}
})
}
More info about JQuery Ajax function's here.

Hiii Actually the problem is , you can not use var inside ajax request ,You can define those variables outside the $.ajax and then use those inside it , it will work.
and just to let you know , you can not use var inside json object :)
{
"key":"value"
}
This is the correct way of json
$.ajax( { } )
this holds a json object so this can not contain the var.
hope it will clear your doubts :) :)

function getCSR(){
var csrHost = "https://example.com/jsp/csr.jsp";
var param = {
commonname: $('#csrName').val().toUpperCase(),
org: $('#csrCom').val().toUpperCase(),
locality: $('#csrCity').val().toUpperCase(),
state: $('#csrState').val().toUpperCase(),
country: $('#csrCountry').val().toUpperCase(),
commonname: $('#csrOU').val().toUpperCase(),
keysize:2048
};
$.ajax ({
url: csrHost,
type: "GET",
data: param,
//contentType: "application/json; charset=utf-8",
success: function(csr){
var textareaResult = $('#textarea1')
textareaResult.html(csr)
}
})
}

Related

what URL call this function?

have function like this:
this.rmSaveParam = function(index, value, responseMethod, errorMethod) {
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: this.destination_ + (updater.currentDevice_ ? "rmNewParam?uid=" + encodeURIComponent(updater.currentDevice_) + "&" : "rmNewParam?") + "newParamIndex=" + encodeURIComponent(index) + "&newParamValue=" + encodeURIComponent(value),
success: responseMethod,
error: errorMethod
});
return false;
}
this.destination_ = https://www.econet24.com/
updater.currentDevice_ = C6ZPLELPP36R45624503480
index = 56
value = 67
I try to guess how the URL will look like.
I try something like this but it's probably wrong (too much question marks?): "https://www.econet24.com/C6ZPLELPP36R45624503480rmNewParam?uid=C6ZPLELPP36R45624503480&rmNewParam?newParamIndex=56&newParamValue=67"
It's easy enough to figure out. No need to guess!
const destination = 'https://www.econet24.com/';
const currentDevice = 'C6ZPLELPP36R45624503480';
const index = 56;
const value = 67;
const url = destination
+ (currentDevice
? "rmNewParam?uid=" + encodeURIComponent(currentDevice) + "&"
: "rmNewParam?")
+ "newParamIndex=" + encodeURIComponent(index)
+ "&newParamValue=" + encodeURIComponent(value);
console.log(url);
There is a better, and much cleaner, way to do this.
this.rmSaveParam = function(index, value, responseMethod, errorMethod) {
const queryParams = {
newParamIndex: index,
newParamValue: value
};
if (updater.currentDevice_) {
queryParams.uid = updater.currentDevice_;
}
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: this.destination_ + rmNewParam,
data: queryParams,
success: responseMethod,
error: errorMethod
});
return false;
}
Notice the lack of encodeURIComponent, this is done for you automatically.

Index of an array becomes undefined while looping [duplicate]

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I am creating a small domain availability checker. For that I will parse the desired domain into a form, and submit that to a PHP file with jQuery AJAX.
However while I am looping through the different TLD's it suddenly gets undefined and I am not able to use the "TLD" for further processing within the loop. As far as I can read, it as something to do with the loop happening first and the requests made after, so I somehow have to freeze the index of my array. But I don't know how to do that.
This is my code:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
};
return false;
});
The printed console.log's looks like this:
This is a classic JavaScript issue. In the success function (a closure), the i is being used. That callback runs in the future, once the AJAX call is done. By that point, the loop has finished, and i has been incremented to 4.
tlds[4] doesn't exist, and that's why you're getting undefined. The callbacks are all using the same i value.
To fix it, you need to create a new function to capture the value of i for each callback.
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
var createCallback = function(i){
return function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
};
}
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: createCallback(i)
});
};
return false;
});
By the time the ajax calls return, the loop has long since ended, and i has run past the end of tlds. Trying to print tlds[i] is bound to fail.
Break the lookup into a separate function, with local variables that will be valid on the ajax callback:
var checkup = function(datastring, domain, tld) {
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tld + " is " + data);
}
});
};
for (var i = 0; i < tlds.length; i++ ) {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
checkup(datastring, domain, tlds[i]);
};
You need to enclose the code in your loop in a closure as follows:
$("input[name=submit]").click(function(){
var getDomain = $("#domainsearch").val();
var stripDomain = getDomain.split(".");
var domain = stripDomain[0];
var tlds = ["dk", "se", "com", "net"];
for (var i = 0; i < tlds.length; i++ ) {
(function() {
var dataString = "domain=" + domain + "." + tlds[i];
console.log(dataString);
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
success: function(data) {
console.log(domain + "." + tlds[i] + " is " + data);
}
});
})( i );
}
return false;
});

How to pass values to asp pages from javascript?

I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}

populated jquery objects show as undefined when passed

In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};

showing error that mouse_id is undefined while implementation in javascript

Hi I am getting an error while implementing the following.
When I click on the "save" button in following code:
<td width="20%"> <input id="save" onClick="updateMouseInfo();" type="button" value="Save" /></td>
I want to call the mouse_id parameter from getMouseInfo() function to updateMouseInfo() and I am getting the error that mouse_id is undefined, so please help me with the solution.
function getMouseInfo(mouse_id)
{
var dataString = {auth_token: sessionStorage.auth_token, id: mouse_id};
var mh_url = MH_HOST + '/mice/get_mouse_info.json';
alert("Inside Mouse Get Info");
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
//for (var info_count = 0, info_len = data.length; info_count < info_len; info_count++ );
//{
alert("Inside for loop");
//var mouse_info = data.cage.mice[info_count];
var ear_tag = document.getElementById("ear_tag");
var age = document.getElementById("age");
var genotype = document.getElementById("genotype");
var owner = document.getElementById("owner");
//var born = document.getElementById("born");
//var euthanize = document.getElementById("euthanize");
//var note = document.getElementById("note");
ear_tag.innerHTML = data[0].ear_tag;
age.innerHTML = data[0].age;
genotype.innerHTML = data[0].genotype_id;
owner.innerHTML = data[0].owner_id;
//born.innerHTML = data[0].dob;
//euthanize.innerHTML = data[0].dob;
//note.innerHTML = data[0].dob;
//}
},
error: function (data)
{
alert("fail");
}
});
}
//update mouse info
function updateMouseInfo(mouseid)
{
var ear_tag = $('#input_ear_tag').val();
var age = $('#input_age').val();
var genotype = $('#input_genotype').val();
var owner = $('#input_owner').val();
var dataString = {auth_token: sessionStorage.auth_token, id: mouseid, mouse:
{ear_tag: ear_tag, age: age,}};
var mh_url = MH_HOST + '/mice/update.json';
alert("Inside Mouse update Info");
console.log('Data String='+ dataString.auth_token + 'Mouse id=' + dataString.id);
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
document.getElementById('ear_tag').innerHTML = "<div" + ear_tag + "'>" + ear_tag + "</div>";
document.getElementById('age').innerHTML = "<div" + age + "'>" + age + "</div>";
document.getElementById('genotype').innerHTML = "<div" + genotype + "'>" + genotype + "</div>";
document.getElementById('owner').innerHTML = "<div" + owner + "'>" + owner + "</div>";
},
error: function (data)
{
alert("fail");
}
});
}
I am getting the following error in the browser console.
m_id=99
Data String=pvHxzkr3cys1gEVJRpCDMouse id=undefined
Whereas the id should be 99 in the above case it is showing undefined.
You are calling the updateMouseInfo function in the following manner:
onClick="updateMouseInfo();"
if you want to have same mouseid value which is taken by getMouseInfo() function when you call updateMouseInfo(),you will have to globalize getMouseInfo()
Hope it works.

Categories