Jquery ajax: object in data object - javascript

I need to pass an object within the data object but it's not working
I use the following function I found on this very site, very useful, to convert form data to JSON
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and then I need to pass the object as a sub-object, but it's not working. Filters isn't even showing up in the query string parameters in the inspector
var filters = $('.filtersForm').serializeObject();
$.ajax({
type: 'GET',
data: {script:'search',page:page,filters:filters},
success: function(data){
}
});
See how "filters" is missing in the picture
Can someone please explain why I can't pass an object like that?

Try this instead:
$.ajax({
type: 'POST',
data: JSON.stringify({
script: 'search',
page: page,
filters: filters
}),
contentType: 'application/json'
});
Changed type from GET to POST. This will allow you to send a request body.
Stringify your data parameter using the built-in JSON object to stringify your JS object to a JSON-formatted string. (older browsers may not have this built-in object, in that case, add it using json2.js)
Set contentType to application/json. This basically states that the request-body is of this type... which it is because we just stringified it to JSON.

Try to specifiy your filters
For example in try :
jsonfilter = JSON.stringify(filters);
If youre using MVC and ASP.Net you can try
In your HTTPWebMethode which have a jsonResult as Return you can try to specifiy parameters
public JsonResult myPostMethode(string script,object page,List<object> filters){
//make some usefull
var model = script;
return(model,JsonRequestBehavior.AllowGet);
}

Related

Pass a Javascript ES6 Map() to an MVC Controller

I am using the Map() functionality in ES6 to create a list of keypair values, making an ID number to a boolean value. I want to pass this Javascript object to an MVC 4 Controller.
Here's my Javascript:
var bankHolidays = new Map();
$('.bank-holiday-switch').each(function () {
var id = $(this).attr('id');
var isChecked = $(this).is(':checked');
bankHolidays.set(id, isChecked);
});
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: { bankHolidays: bankHolidays },
success: function (result) {
alert("Success");
}
});
I can console.log() the map object and see that it's being created as intended. However, when I pass it to this MVC Controller:
[HttpPost]
public JsonResult SaveBankHolidays(Dictionary<int, bool> bankHolidays)
{
// DO stuff
}
..no error is thrown, but it just says the bankHolidays dictionary has 0 values in it. I can call other Actions in that Controller without issue. I have tried many different combinations of Dictionary<string, bool> to no avail.
Can somebody tell me what I am doing wrong?
In a http negotiation, xhr in this case, we must send strings, so you need some string representation of Map(), the best option, in my opinion, is to use a JSON stringify in some way, because the parse of JSON have a broad support among server side code:
var bankHolidays = new Map();
bankHolidays.set(1, 2);
bankHolidays.set(3, 4);
var result = JSON.stringify([...bankHolidays]);
console.log(result)
In your code something like :
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: JSON.stringify([...bankHolidays]),
success: function (result) {
alert("Success");
}
});
In backend you have to parse the response, see this.

Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

How can I send an object via Ajax from within a Javascript Class?

My question title may not be phrased well, sorry.
I want to create a Javascript class to simplify sending information to a php page.
I'm using the method described in this answer to create my class
This is what I have so far:
var ParseObject = Class.extend({
init: function(classname, id){
// required properties
this.classname=classname;
this.objects=[];
this.fields=[];
// optional properties
if(id && id != '') this.id='';
//this.command = command;
//this.callback='';
//this.parent=[];
//this.children=[];
//this.relation='';
},
set: function(field, value) {
if(field == 'classname') this.classname=value;
else if(field == 'callback') this.callback=value;
else if(field == 'command') this.command=value;
else this.fields.push(field, value);
},
addChild: function(obj){
this.children ? this.children.push(obj) : this.children= [obj];
},
addParent: function(linkedFieldName, parentClassName, parentId){
this.parent=[linkedFieldName, parentClassName, parentId];
},
addObject: function(obj){
this.objects.push(obj);
},
isRelatedBy: function(relation){
this.relation=relation;
},
send: function(){
var obj = this;
$.ajax({
type: "POST",
dataType: "json",
url: "php/parseFunctions.php",
data: {data:obj},
success: function(response) {
// do stuff
},
error: function(response) {
// do stuff
}
});
}
});
And here's how Im trying to use the class:
var testObject = new ParseObject('TestObject');
testObject.set('callback','testResopnse');
testObject.set('command','save');
testObject.set('title','New Title');
testObject.set('description','New Description');
testObject.set('stuff',['one','two','three']);
testObject.addParent(['parent', 'MeComment', 'kRh5xcpkhz']);
testObject.send();
Everything works as expected until I get to testObject.send();
What I expect is for the below object to get sent to my PHP page:
But instead, what I get is "Uncaught RangeError: Maximum call stack size exceeded"
Why does this happen, and how can I achieve the desired result?
Update:#
Per Quentin's suggestion, this got me sorted
var obj =$.parseJSON(JSON.stringify(this));
When you pass an object to data:, jQuery will call param on it.
That function includes this code:
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
That ends up calling all the functions in the object (including the constructor) in the context of window. I don't have the tuits to figure out all the effects of that, but it clearly isn't desirable and, based on the error message, leads to infinite recursion.
You have several options here:
Write an explicit function that extracts the data you care about from the object and presents as a simple data structure consisting only of the data types you can serialise with .
Serialise the object to JSON and then deserialise it to strip out all the functions before you pass it to param via data:
Serialise the object to JSON, pass that as a string to data:, set the request contentType: "application/json" and change the PHP to expect a JSON formatted request instead of a form formatted request.
(I don't know if this will work) change the way you construct the class to use Object.defineProperty() and mark all the functions so they are not enumerable. I suspect this approach would fail because the object is, itself a function.

Send JavaScript object to web server call via jQuery - what is the correct way?

I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.
var obj = {
'id':45,
'isRead':true
};
$.ajax({
url: "/notification/read",
data: obj,
success: function(data, textStatus){
/* code here */
}
});
$.ajax(url, obj);
You need to send an object as second param
{success: success, data: data}
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones

Categories