Why do I have to enclose a function in another function? - javascript

When I write a function in JSON, why do I have to enclose it inside an anonymous function?
This works:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
This doesn't work:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: alert(data)
});
Thanks

You can do that. You just using the wrong syntax.
The success property needs a function expression not a function() call (which then returns a value into success);
So
success: myfunction
instead of
success: myfunction()

In short, because you're executing alert() and trying to assign the result to the success callback, so this won't work (the result of alert() is undefined). However you can do this:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: customFunc //*not* customFunc() which would call it
});
In this case customFunc will receive the same parameters as success passes, so it's signature should be: customFunc(data, textStatus, XMLHttpRequest), though it can be a subset, for example customFunc(data).

Related

Jquery, how I can call the same function without rewrite [duplicate]

This question already has answers here:
How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)
(4 answers)
Closed 5 years ago.
usually when I need to use the same function with some edits I must copy/paste the function and then add some variables (sometimes the code is very long)
for example:
1st f unction
$.ajax({
type: 'GET',
url: url,
data: {s: size},
dataType: 'json',
success: function (data) {
//data
In the second function i have to add a variable in data (success data will be the same as the first function):
$.ajax({
type: 'GET',
url: url,
data: {s: size, f:from},
dataType: 'json',
success: function (data) {
//data
How I can call the first function without rewrite all?
You can have an function and pass the data into it and call your $ajax inside the function with the given data. Also you can pass your callbacks into it to make more flexible.
function makeAjax(data, success, error){
$.ajax({
type: 'GET',
url: url,
data: data,
dataType: 'json',
success: success,
error: error
});
}
Enclose your AJAX request in a single function and pass your data as a parameter.
function ajax_request(request_data) {
$.ajax({
type: 'GET',
url: url,
data: request_data,
dataType: 'json',
success: function (data) {
//do something here
}
});
}

value missing on AJAX response

I can't find what the error is in an AJAX call.
I have a PHP file output:
[{"value":"123","name":"My Name"}]
and this output is correct. And my AJAX call returns undefined after success:
$.ajax({
type: "POST",
url: "correct_file_location.php",
data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
alert(pk.value);
$("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
});
Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object.
pk[0].value
should work.
*It is showing undefined because you are getting an array of objects and not only object *
try what #freedomn-m suggested in the comments
Try below code it will be work.
$.ajax({
type: "POST",
url: "correct_file_location.php",
//data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
var data1 = JSON.parse(pk[0].value);
console.log(data1);
// $("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
}) ;
Your code will also work but your php response code must be in javascript object.
Please add below code in 'correct_file_location.php' and check with your ajax code.
'{"value":"123","name":"My Name"}';

Must I use an anonymous function with jquery's $.ajax?

I have this:
$ajax = $.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {//I want to define this function externally
var dataLength = data.length; ...
I would like to do something like this:
function myFunction(data) {
// do something
}
$ajax = $.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: myFunction(data),
...
When I try the above code it tells me data is not defined. How can I achieve this?
Must I use an anonymous function with jquery's $.ajax?
No
When I try the above code it tells me data is not defined. How can I achieve this?
You are passing the return value of calling myFunction. Since it doesn't have a return statement, that value is undefined.
You need to pass a function instead.
success: myFunction,

Call another method onSuccess event of an Ajax call

I have an AJAX call on MVC3 it looks like this
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type:"post",
data: ko.toJSON(this),
contentType:"application/json",
success: function(result){alert(result.message)}
});
}
The trouble is the line
success: function(result){alert(result.message)}
I want to pass all the messing things in a HtmlHelper, however, the success line prevents me from doing so, is there a way I can specify a function for that line
success: doSomeStuff(result)
and
function doSomeStuff(result){alert(result.message)}
Thanks in advance
Simply pass the function name to the success: method and it will pass the data onwards, as such:
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type:"post",
data: ko.toJSON(this),
contentType:"application/json",
success: doSomeStuff
});
}

javascript jquery and using eval

i am currenty using jquery plugin to read a data file (data.html)
data.html has below format
[10,20,30,40,50]
my jquery data request and the javascript to return values is below
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[".
If i use eval function
my=eval(test());
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
Thanks
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
You don't need eval. Just indicate the proper dataType: 'json':
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...

Categories