Good Day,
I try to assign to a variable the result of an Ajax request. I tried both of the requests below, with no result (got an "Undefined" answer).
I don't understand the difference between:
var temp = obj.method(me, you);
and
var temp = (function () {
obj.method(me, you);
})();
Here is the AJAX request:
ObjID.prototype.getAjx = function(one, you){
$.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
}
Is this the same, or not ?
Thanks for your help! :)
The first two bits of code you showed effectively do the same thing.
However, neither of them do what you think they do. Neither of them are assigning the return value from your AJAX call anywhere:
The first line of your code:
ObjID.prototype.getAjx = function(one, you){
is simply assigning the function that contains the actual AJAX call to the .getAjx property of the ObjID.prototype. That function doesn't contain any return statements and upon execution, will not return anything. That is why you are getting undefined.
The code that actually performs the AJAX call is:
$.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
and, you aren't assigning that return value to anything. If you wanted to, you'd need to write something like this:
var result = $.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
JQuery AJAX calls return a reference to a Promise object and that's what you would be storing in that case.
Related
Using the following jQuery, how can I read through the values of the JSON that's returned? With it how it is, the jQuery doesn't even run as there is an error in: alert("A" + obj.sender[0]);
var session_id = $(this).find(".session_id").val();
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: {sesh_id: session_id},
success: function (response) {
var obj = jQuery.parseJSON(response);
alert("A" + obj.sender[0]);
},
error: function (response) {
alert("Err: " + response.status);
}
});
The value of response is:
[{
"sender":"email#example.com",
"details":"details1",
"date":"2017-01-04 16:11:04"
},
{
"sender":"someone#example.com",
"details":"details2",
"date":"2017-01-04 16:11:05"
},
{
"sender":"blah#example.com",
"details":"details3",
"date":"2017-01-04 16:11:06"
}]
The issue you have is that your index accessor is in the wrong place as obj is an array, not the sender property, so it should be obj[0].sender.
You also don't need to call JSON.parse() on the response, as jQuery does that for you automatically as you specified dataType: 'json'. Try this:
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: { sesh_id: session_id },
success: function (response) {
console.log("A" + obj[0].sender);
},
error: function (response) {
console.log("Err: " + response.status);
}
});
Finally, note that console.log() is much more preferable when debugging over alert() as it doesn't coerce data types.
I have recently taken over a project, and there is one thing i don't get about it.
Somehow there is a .js file that can change the names and values of the variables and such by using the # symbol. this is somehow called via the window object, for example i have one of the .js files with some ajax call in it:
var values#TEMPLATE_CONTROL_ID;
var regtemp#TEMPLATE_CONTROL_ID = #REGISTRATION_TEMPLATE_ID;
function save#TEMPLATE_CONTROL_ID(){
if (isRegistration#TEMPLATE_CONTROL_ID){
SaveInput#TEMPLATE_CONTROL_ID();
var toGoValues = ConvertRegistrationToGoValues#TEMPLATE_CONTROL_ID();
$.ajax({
url: 'scripts/SaveStandard.php',
type: 'post',
data: {'arrvalues': toGoValues, 'regID': registrationID#TEMPLATE_CONTROL_ID},
cache: false,
success: function(json) {
ImSaved();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
else{
values#TEMPLATE_CONTROL_ID = new Array();
SaveInput#TEMPLATE_CONTROL_ID();
AddToGoArray#TEMPLATE_CONTROL_ID();
$.ajax({
url: 'scripts/SaveStandard.php',
type: 'post',
data: {'arrvalues': values#TEMPLATE_CONTROL_ID, 'regID': 1},
cache: false,
success: function(json) {
ImSaved();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
}
This is somehow called with window[value](); where value could hold something like 1084. 1084 is entered where it says #TEMPLATE_CONTROL_ID.
My Question is does anyone recognise this, i figure that there should be some kind of map or something but i need to call something else, and would love to know how this works.
I have a script that makes two ajax calls - the second being contained within the success handler of the first.
However I need to use the data captured within the first success handler as a further variable to pass in the second ajax call and then use that variable within the php file that is undertaking the server side processing.
This is all very new to me, so I hope this makes some sort of sense. If anyone could assist that would be great.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id'+lead_id,
data: $('form').serialize(),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I think you lose a "=" sign in the code:
url: 'processtwo.php?lead_id='+lead_id,
You're going to want to split these into two separate functions and allow for a parameter to be passed to the second. Not really part of your question, but should make it much easier to read. The second process seems to be missing an equals sign in the url parameter which will cause it to not work
function processOne() {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function(data) {
//alert("success data from processone is " + data);
//console logs are better to use when debugging data
console.log('SUCCESS DATA', data);
var lead_id = data;
processTwo(lead_id);
}
});
}
function processTwo(lead_id) {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id=' + lead_id,
data: $('form').serialize(),
success: function(data2) {
alert("success data from processtwo is " + data2);
}
});
}
If you're still not getting anything make sure the data is directly returning the lead_id. AJAX calls commonly return JSON data, so it very well might be something like data.lead_id or something like that. Alerts aren't useful for showing this so you could use the console log, console.log('SUCCESS DATA', data) to dig into the return data.
Given the reply to my comment, and making the assumption that the data returned from the first AJAX call is a simple string value (if it's not, you can still use the code here to see how you need to do what you need to do). jQuery's serialize() returns a string (see https://api.jquery.com/serialize/) so you can just append to that.
Also, you are missing your = sign when making your URL, so if you are trying to get the lead_id as a GET var, that's why it's not working.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
// you are missing the equals sign here, which is why this doesn't work as a GET
url: 'processtwo.php?lead_id'+lead_id,
// here we tack on a lead_id variable to the serialized form and give
// it the value you got back from query 1
data: ($('form').serialize() + "&lead_id=" + lead_id),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I wrote this function as revealing module pattern, but when I call the get method in console by metadataModule.get(); it echoes undefined in console.
var metadataModule = function () {
var metadataurl = 'http://farskids326.com/data.json';
function getMetadata() {
console.log("Metadata Function Called")
$.ajax({
url: metadataurl,
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
return {
get: getMetadata,
};
}();
Where did I made a mistake in this code?
When you are working in the console, the return value of the last expresion is echoed after any command. The method you are using doesn't have an explicit return value. So, that may be why you see undefined.
This probably means that your ajax call is encountering an error. Try changing it to log when either success or error happens, like so:
$.ajax({
url: metadataurl ,
dataType: "json",
success: function(data){
console.log('called success!');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('called error!');
}
});
Then, when you run your code, you should see exactly which callback is being executed. Hopefully, that will give you a good starting point for debugging the issue.
The getMetadata function returns nothing so yes, it will output undefined. for it to respond with the content of the JSON you need to make the ajax call synchronous and return the value you get.
var metadataModule = function () {
var metadataurl = 'http://farskids326.com/data.json';
function getMetadata() {
console.log("Metadata Function Called")
var content = {}
$.ajax({
url: metadataurl,
async : false,
dataType: "json",
success: function (data) {
content = data;
}
});
return content
}
return {
get: getMetadata,
};
}();
function getMore(from){
var initData = "&start-index=";
initData += from;
$.ajax({
type:"POST",
url: '', //removed the URL
data: initData,
dataType: 'json',
success: function(result) {
return result;
},
error: function(errorThrown) {
}
});
return result;
}
Its a google base query; I have another function that makes the initial server call and gets the first 250 items. I then have a running counter and as long as the results = 250 it calls the server again, but starting at "start-index=" of the current amount of items pulled off. This part all works correctly and with firebug I can also see that the server response is proper JSON.
The trouble I'm having is trying to return the JSON from this function to the function that called it. I do not want to call the original function again because it will clear the arrays of data already pulled from the server. Each time it returns to the parent function it's null.
Does anyone know how i can go about returning the data using "return"?
function FuncionCallGetMore(){
//...
getMore('x-value', FuncionGetReturn);
//...
}
function FuncionGetReturn(error, value){
if (!error) {
// work value
}
}
function getMore(from, fn){
var initData = "&start-index=" + from;
$.ajax({
type:"POST",
url: '', //removed the URL
data: initData,
dataType: 'json',
success: function(result) {
fn(false, result);
},
error: function(errorThrown) {
fn(true);
}
});
return;
}
The only way that you can do what you're describing is to make the AJAX call synchronous, which you don't want to do since it will lock the UI thread while the request is being made, and the browser may will to freeze. No one likes freezing.
What you want to do is use callbacks. Post the code of the other functions involved so I can get a better idea of what is going on. But basically, what you want to do is to create an asynchronous loop.
function listBuilder() {
var onError = function(response) {
// ...
};
var onSuccess = function(response) {
// Handle the items returned here
// There are more items to be had, get them and repeat
if ( response.length == 250 ) {
getMore(onSuccess, onError, 250);
}
};
getInitialSet(onSuccess, onError);
}
function getMore(onSuccess, onError, from) {
$.ajax({
type:"POST",
url: '', //removed the URL
data: "&start-index=" + from,
dataType: 'json',
success: onSuccess,
error: onError
});
}