add json objects to ajaxsubmit call - ajax

I have a piece of code which goes as following:
var o_titular = {id:'01',fecha:'2014-01-01'};
var o_dependientes = [
{id:'02',fecha:'2014-02-02'},
{id:'03',fecha:'2014-03-03'}
];
var o_fecha = '2014-05-05';
$("#documento-antiguedad").ajaxSubmit({
dataType: 'json',
data: {
titular: o_titular,
dependientes: o_dependientes,
fecha: o_fecha
},
success: function(r) {
alert("yay success");
}
});
I'm forced to make this ajaxSubmit (this is a simplified code, but the complete case involves file uploading and such) but when I see the data I send in the POST request i got the following:
titular [object Object]
dependientes [object Object],[object Object]
fecha 2014-05-05
of course I want to fiddle with the content of the objects, not the object itself. How can I send this parameters as JSON objects with ajaxSubmit?
Thank you in advance
EDIT:
When I make a regular ajax call:
var o_titular = {id:'01',fecha:'2014-01-01'};
var o_dependientes = [
{id:'02',fecha:'2014-02-02'},
{id:'03',fecha:'2014-03-03'}
];
var o_fecha = '2014-05-05';
$.ajax({
url:'/pendientes/index/creatependienteantiguedad/',
dataType: 'json',
data: {
titular: o_titular,
dependientes: o_dependientes,
fecha: o_fecha
},
success: function(r) {
alert("yay success");
}
});
I get the following:
dependientes[0][fecha] 2014-02-02
dependientes[0][id] 02
dependientes[1][fecha] 2014-03-03
dependientes[1][id] 03
fecha 2014-05-05
titular[fecha] 2014-01-01
titular[id] 01
That's exactly what I want to get, but with ajaxSubmit instead of Ajax.

You could use:
JSON.stringify(o_dependientes);
That will turn the JSON object into a string

Related

Vuejs post returns json data but wont assign to vues data object

Hey guys I am using vuejs and ajax to send formData and return a json response. There's a json response comes though however I cant assign it to the vue data object. Any ideas as to why? Heres my method. I know the function is firing as it hits the other page and returns json data in the console. Message, nameExists, and error wont assign even though all our in the vue data property and is spelled correctly.
addTemplate: function() {
this.sub = true;
this.itemName = this.itemName.trim();
var addTemplateForm = document.getElementById("addTemplateForm");
var fd = new FormData(addTemplateForm);
if (this.validItemName == true /* etc...*/) {
$.ajax({
url:'addTemplateBackend.php',
type:'POST',
dataType: 'json',
data: fd,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
error: function(data){
this.message = data.message;
alert('error');
},
success: function(data){
alert('success');
this.error = data.error;
this.message = data.message;
console.log(data);
this.nameExists = data.nameExists;
if(data.success == true){
$('#successModal').modal('show');
}
}
});
}
}
You need to either bind this:
success: function (data) {
this.message = data.message;
}.bind(this)
or use ES6 "fat arrow" syntax:
success: data => {
this.message = data.message;
}
See How does the "this" keyword work?.

Charset encoding of $.ajax json data

I make simple ajax request.
code is like this.
var paramObject = new Object();
paramObject.cd_nm01 = 'farm';
paramObject.cd_nm02 = 'server';
paramObject.cd_nm03 = 'cpu_num';
paramObject.cd_nm04 = 'mem_size';
paramObject.cd_nm05 = 'user_hdd';
paramObject.cd_nm06 = 'net_sprt';
paramObject.cd_nm07 = 'net_type';
var codes = JSON.stringify(paramObject);
$.ajax({
type: 'POST',
async: false,
cache: true,
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded; charset=UTF-8');
},
url: '/common/getCodes',
data: {
'jParam' : codes
},
success: function(data, status ,xhr) {
console.log(data);
},
error: function(xhr){
}
});
I want send data of this: "'cd_nm':'farm','cd_nm':'server','cd_nm':'cpu_num','cd_nm':'mem_size','cd_nm':'user_hdd','cd_nm':'net_sprt','cd_nm':'net_type'}"
but in controller(Spring 3.1),
if I get those values from request,
they looks like below.
%7B%22cd_nm01%22%3A%22farm%22%2C%22cd_nm02%22%3A%22server%22%2C%22cd_nm03%22%3A%22cpu_num%22%2C%22cd_nm04%22%3A%22mem_size%22%2C%22cd_nm05%22%3A%22user_hdd%22%2C%22cd_nm06%22%3A%22net_sprt%22%2C%22cd_nm07%22%3A%22net_type%22%7D
How can I solve this problem?
Your request is just url encoded, like it should be. If you decode it it looks like this:
{"cd_nm01":"farm","cd_nm02":"server","cd_nm03":"cpu_num","cd_nm04":"mem_size","cd_nm05":"user_hdd","cd_nm06":"net_sprt","cd_nm07":"net_type"}
That looks like valid json to me. The form that you want to send the data in doesn't look right. You want to use single quotes and you don't have a leading bracket. If you don't want the 01, 02, 03 suffixes you probably need to change the JSON.stringify method to accept an array of strings instead of an object.

Ajax success: function(data) is undefined

Edit: could've researched better... reading this post now: How do I return the response from an asynchronous call?
I have an ajax request which returns JSON data. When I watch it in fiddler, it does go out to the service and get the JSON data, but when I try to set a variable to it's response, that variable is "undefined". If I alert in the success method, it alerts, but the variable is still undefined.
I tried changing the function(data) to function(something) incase that had anything to do with it... same story.
var returndata
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
returndata = data; //undefined
alert('haaalp');
}
});
The JSON is like below
[
{
"DelegateSid":null,
"DisplayName":"Tom",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Tim",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Jake",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Ryan",
"HasDelegation":true,
"HasEtaManagement":false
}
]
Try:
var returndata;
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
console.log(data);
returndata = data;
console.log(returndata);
}
});
If the 2 outputs are the same it might be the case that you're trying to access returndata from outside its scope, hence the undefined, or that you're accessing returndata before the Ajax call completes.

Extjs how to memorize a response from an Ajax request?

I want to memorize the response of an ajax request, how I can do it?
In the code above, I found "" in the console...
How can I do it? any suggests?
var jsoncolumnset = '';
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
success: function(response){
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
},
failure: function(){
//TODO: gestione fallimento chiamata
}
});
console.log(jsoncolumnset);
Ajax is asynchronous so while you have started the request in your Ext.Ajax.request call, the response has not come back by the time console.log(jsoncolumnset) is being executed.
The 'success' method will execute when the server response comes back to the browser which could be milliseconds or seconds later - either way the code mapped to the 'success' event is executed after the console.log executes.
So it appears the snippet is from code nested in some object since you have the "this" scope in place. .
You can add some event based logic that works nicely with ajax. Here is an idea:
// add this custom event in line with other bindings or in the objects constructor or a controllers init method
this.on('columnsready', this.logColumns);
// add this method to the main object
handleColumnResponse: function () {
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
this.jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
// fire the custom event
this.fireEvent('columnsready');
},
// add this as an example of where you would put more logic to do stuff after columns are setup
logColumns: function () {
console.log(this.jsoncolumnset);
},
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
// map to the handler method in the main object
success: this.handleColumnResponse,
failure: function(){
//TODO: gestione fallimento chiamata
}
});

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

Resources