jQuery $.ajax(), pass success data into separate function - javascript

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
I am wanting this to be the same as:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}

Works fine for me:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>

You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}

this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

In the first code block, you're never using the str parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}

I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)

Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};

Related

how to use json data sent from backend

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part
You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!
In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},
var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

jsCall return value to outside of jquery ajax post request

I want to get jquery ajax post request value to outside from the ajax function. my code is this and it return undefined as console output. How should fix it
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.post(urlForPhp + '/' + url, formData, function (outputData) {
output = outputData;
});
return output;
}
Edited
I changed my code to sync type ajax post request and check output. But it is not changed. here my code
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
output = e;
}
});
return output;
}
You can use Deferred jQuery
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole').then(function (outputFromAjax) {
console.log(outputFromAjax);
});
}
function submitViaPost(url) {
var dfd = jQuery.Deferred();
var formData = $('form').serializeArray();
$.post(urlForPhp + '/' + url, formData, function (outputData) {
dfd.resolve(outputData);;
});
return dfd;
}
Don't return , make it a callback as $.post is async
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole', function(out){ //Result comes here
var outputFromAjax = out;
console.log(outputFromAjax);
});
}
function submitViaPost(url , callback) { //Added callback
var formData = $('form').serializeArray();
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
callback(e);
}
});
}

How to pass a list of id's in a AJAX request to the Server in MVC

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});

Calling ajax inside of ajax

I'm trying to make an ajax call that gets a type of a property. Using that type I then pass it into another ajax call. I'm having some difficulty doing this asynchronously because I'm trying to defer til the first property is loaded.
function getEnt_PodType() {
var ent_PodType;
var oDataUrl = //URL to my data;
return $.ajax({
url: oDataUrl,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
var res = xhr;
if (res.d.results != undefined) {
ent_PodType = res.d.results[0].Ent_PodType;
}
console.log("The ent pod type value is "+ ent_PodType);
return ent_PodType;
}
});
}
function getProjects() {
var QUERY_FILTER = getEnt_PodType().done(function (result) {
"$filter=Ent_PodType eq '" + result + "'";
});
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
}
When I call the getProjects(), I thought building the url would wait for getEnt_PodType() to return its value but it doesn't seem to work that way.
Instead it goes ahead and executes the rest of getProjects(). Is there any way to do this asynchronously?
Your second ajax call need to be placed inside done promise. You can wrap rest of your code in local function and call it inside done, like so:
function getProjects() {
function getProjectsViaAjax(){
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
}; // end of getProjectsViaAjax
var QUERY_FILTER = getEnt_PodType().done(function (result) {
"$filter=Ent_PodType eq '" + result + "'";
getProjectsViaAjax();
});
}
AJAX is asynchronous. Anything that depends on the result must be done in the callback function.
I also recommend always passing the parameters as an object, to allow jQuery to encode it properly.
function getProjects() {
getEnt_PodType().done(function (result) {
var QUERY_FILTER = { "$filter": "Ent_PodType eq '" + result + "'"};
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: restUrl,
data: QUERY_FILTER,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
});
}
The ajax call needs to be in the done promise. Something like the following should be ok.
function getProjects() {
return getEnt_PodType().done(function (result) {
var QUERY_FILTER = "$filter=Ent_PodType eq '" + result + "'";
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
});
}
For this to work you need to call the second code from the success function of first code.Or you put the code in a function and call that function from the success callback of first ajax call.Using .done calllback is more appropriate.So call second function from done callback of first ajax call.
function getProjects() {
return getEnt_PodType().done(function (result) {
var QUERY_FILTER = "$filter=Ent_PodType eq '" + result + "'";
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
});
}
You need to call one function synchronously, because second task is depends on first task.
You can call function getEnt_PodType synchronously, you need to make
async: false in this function.
And then it will work as you expected.

Assigning ajax call return value to an var with jquery

How can I assign a variable(var) to a json object which is returned from ajax call to the server? I need to access that object in the rest of the body.
For example, I've try this, I don't know it's correct.
var selectValues=$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: onSuccess
});
})
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
Note that, variable selectValues is used in the rest of the body.
I think you should do the whole code inside the $(document).ready(function() function and then make the ajax call synchronous. Because now the ajax call will be made when the document is ready, but the other code will be run directly without waiting for the document to be ready. Also the ajax call is asynchronous by default, so you should make it synchronous and assign the selectValues variable inside the success function of the ajax call. It will become something like this:
$(document).ready(function() {
var selectValues;
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(data) {
selectValues = data
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
})
you have to define the var outside the document ready scope like this:
var selectValues;
$(document).ready(function() {
// ajax
});
in the onSuccess function you can define the selectValues = data or something like that
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: function (result){
var selectValues=result;
}
});
try this.
Here is how we extract the returned information from our (xml) ajax calls:
$.ajax ({
type: "POST",
url: "something.cgi?someparam=whatever",
data: "key=val&key2=val2",
dataType: "xml", // you use json, but I don't think it matters
success: function (data) {
if ($("error", data).text() === "") {
// I could assign $("error", data).text() to a var just here
// This gets the "error" parameter out of the returned xml or
// json, here contained in "data"
}
[snip the rest]
Another way to do this is to add the rest of your code in the success callback lik this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(selectValues) {
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
}
});
})

Categories

Resources