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,
Related
I am trying to learn javascript best practices and I am a bit confused. I have red that best ajax practice is:
function doSomething(arg1, arg2) {
jQuery.ajax({
var urlink = resourceURL
url: urlink,
cache: false,
data : "testData"+arg1,
type: "POST"
}).done(function(data) {
var obj = jQuery.parseJSON(data);
updateHtml1(obj);
updateHtml2(obj);
});
}
and not this way:
function getSomething(arg1, arg2) {
jQuery.ajax({
var urlink = resourceURL
url: urlink,
cache: false,
data : "testData"+arg1,
type: "POST",
success: function(data) {
var obj = jQuery.parseJSON(data);
updateHtml1(obj);
updateHtml2(obj);
}
});
}
I am asking which practice is best and why?
Either way is fine, it's just a difference in using the success callback or a promise, and in this case there is no difference. If you would want to return the result from the function doSomething then you would use the first method so that you can return the promise, as the done method then can be bound outside the function.
Both examples are overly complicated, and the var urlink = resourceURL is placed inside an object literal, so neither would actually work. You should also specify the dataType in the call, then the data will be parsed automatically.
In the first example you don't need an extra function wrapper.
function doSomething(arg1, arg2) {
jQuery.ajax({
url: resourceURL,
cache: false,
data : "testData"+arg1,
type: "POST",
dataType: "json"
}).done(function(data) {
updateHtml1(data);
updateHtml2(data);
});
}
And the second should be:
function getSomething(arg1, arg2) {
jQuery.ajax({
url: resourceURL,
cache: false,
data : "testData"+arg1,
type: "POST",
dataType: "json",
success: function(data) {
updateHtml1(data);
updateHtml2(data);
}
});
}
I have a jQuery function that is called when the "submit" button is clicked:
function SubmitForm() {
var idList = [];
var list = $('#TableAdminPortfolio .CheckBoxProjects');
list.each(function () {
var id = $(this).closest('td').children('.hiddenId').val(); // parseInt()
idList.push(id);
});
$.ajax({
url: $(this).href,
type: 'POST',
data: idList,
success: function (result) {alert('Successful');},
error: function (result) {alert('Error');}
});
}
My controller looks like:
[Transaction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(IEnumerable<int> projects)
{
...
}
The paramater (projects) is always null. I've stepped through my jQuery code inspecting it each step of the way and the idList is definitely populated. I've also tried my $ajax like this:
$.ajax({
url: $(this).href,
type: 'POST',
data: { projects : idList },
success: function (result) {alert('Successful');},
error: function (result) {alert('Error');}
});
And still the same results. Any ideas what is going on? And yes, I have a reason for doing an Ajax Post rather then a Form Post.
TIA
NOTE:
I am using jQuery v1.6.4 and ASP.NET MVC 2.0.
try converting your array to json using JSON.stringify
$.ajax({
url: $(this).href,
type: 'POST',
dataType: "json",
data: JSON.stringify(idList),
traditional: true,
success: function (result) {alert('Successful');},
error: function (result) {alert('Error');}
});
try:
var mylist='{"projects":'+ JSON.stringify(idList)+'}';
then
data:mylist,
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
});
}
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...
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).