what URL call this function? - javascript

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.

Related

jQuery ajax var line - Uncaught SyntaxError: Unexpected identifier

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

Nested ajax call with an value from the first into the seconds Ajax call's url

I want to do live search and I need to use an id value from the first ajax call inside the second one.
I get the info when I type fast into the search, but if I search again or continue, I get this and the outer ajax wont be called again.
GET
http://api.themoviedb.org/3/movie/366924/videos?api_key=KEYHERE…9a6ebe&callback=jQuery1102017797202615180896_1472038138300&_=1472038138301
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val(),
movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
}
})
.then(function() {
$.each(resultArray,
function (index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function () {
$("#myList").append("stuffs");
}
});
});
});
}
$(this).change();
});
Try This -
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val();
var movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
$.each(resultArray,
function(index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function() {
$("#myList").append("stuffs");
}
});
});
}
});
}
$(this).change();
});

JSON object length is returning a big value instead of expected 750 records

I'm trying to append records to my table which are being loaded from an AJAX request which returns JSON, but if I try to use output.length it returns a big number instead of 750 records. This causes the for loop to be run for 10000 times instead of 750. Why is this?
$(document).ready(function() {
getData();
});
function getData() {
$.ajax({
data: {
action: 'getData'
},
url: "api/ajaxcall.php",
type: 'post',
async: false,
dataType: 'html',
success: function(output) {
console.log(output.length);
// buildTable(result);
}
});
}
function buildTable(output) {
for (var i = 0; i < output.length; i++) {
$('<tr>').append(
$('<td>').text(output[i].naam),
$('<td>').text(output[i].perc),
$($('<input id="' + output[i].id + '" onclick="editData(this)" type = "button" value = "Edit" />')),
$($('<input id="' + output[i].id + '" onclick="readData(this)" type = "button" value = "Read" />')),
$($('<input id="' + output[i].id + '" onclick="deleteRow(' + output[i].id + ')" type = "button" value = "Delete" />'))
).appendTo('#tableA');
}
}
Check with this probably
function getData() {
$.ajax({
data: {
action: 'getData'
},
url: "api/ajaxcall.php",
type: 'post',
async: false,
dataType: 'html',
success: function(output) {
output = JSON.parse(output.d); //May it need to parse the string
console.log(output.length);
// buildTable(result);
}
});
}

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

what is [object Object]?

why instead giving data(value) of database give me the [object Object]?
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
$(".list_name").append('<p>' + data + '</p>');
$('.list_name p a').click( function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
});
results url is:(json_encode()) :
[{"name":"333333"},{"name":"\u0633\u0644"},{"name":"\u0633\u0644\u0627\u0633\u06cc"},{"name":"\u0633\u0644\u0627\u0633\u0633"},{"name":"\u0633\u0644\u0627\u0645"}]
update: full code:
$('.auto_complete').keyup(function () {
var id = '#' + this.id;
var alt = $(id).attr('alt'); var id = $(this).attr('id'); var name = $(this).attr('name');
var url = alt + id + '/' + name;
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
data is not a string, but a JSON object, which is basically a Javascript Object. You access it as you would any JS object/array (looks like your result string is an array)
So you can do something like this: data[1].name
data is a list (It is javascript object).
toString( list ) in javascript gives "object Object"
data[0].name will return "333333"
To make a string from a complex object write your own function.
It looks like your Ajax call is returning an array of structures. Each element in the array is a name-value pair. Given that data is an array, the first element is data[0] so you might do something like:
var firstElem = data[0];
var firstName = firstElem.name;
alert("The first name is: " + firstName);
If you want to add all of the names into your html, you would need to loop through the array, each time appending the current element.
If you wanted to show all names, you could do
var names = "";
for (var i=0; i<data.length; i++) {
var elem = data[i];
names = names + elem.name + ", ";
}
I would rewrite it in the following way
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
}
});

Categories