Parsing associative array via AJAX - javascript

I have the following associative array and i try to send it to the server via AJAX.
Checking my console, in the network tab, it's posted but nothing is parsed.
Array creation:
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
Assoc array (console.log):
[category: "6", Type1: "998", Type2: "20100100"]
Request:
$.ajax({
type: POST,
url: 'something.php',
data: {
data: FiltersArray
}
}).done(function(data) {
console.log('Server Response: ' + data);
})
Complete code:
$(document).ready(function() {
var filters = {
category: $("#categoryInp"),
type1: $("#type1Inp"),
type2: $("#type2Inp"),
button: $("#FilterBtn"),
returnArray: function() {
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
return FiltersArray;
},
sendRequest: function(type, URL) {
$.ajax({
type: type,
url: URL,
data: JSON.stringify(this.returnArray()),
beforeSend: function() {}
}).done(function(data) {
console.log('Server Response: ' + data);
}).fail(function() {
alert("An error occurred!");
});
}
};
filters.button.on('click', e => {
console.log(filters.returnArray());
filters.sendRequest('POST', 'Modules/Products.order.module.php');
});
});

There is no such thing as an associative array in JavaScript.
There are objects, which hold key:value pairs of data.
There are arrays, which are a type of object that provides special behaviour when the key name is an integer.
jQuery distinguishes between arrays and other kinds of objects when you pass one in data.
If you pass an array it will not do anything with key:value pairs where the key is not an integer.
Use a plain object and not an array for this.
Aside: Variable names beginning with a capital letter are traditionally reserved for storing constructor functions in JavaScript. Don't use that naming convention for other kinds of data.
var filters = {};
filters['category'] = this.category.val();
filters['Type1'] = this.type1.val();
filters['Type2'] = this.type2.val();
It would be easier to just collect all the data as you create the object though:
var filters = {
category: this.category.val(),
Type1: this.type1.val(),
Type2: this.type2.val()
};
Aside
data: {
data: FiltersArray
}
This will create a (seemingly pointlessly) complex data structure that you'll need to access in PHP as $_POST['data']['category'].
You probably want just:
data: filters
Aside
data: JSON.stringify(this.returnArray()),
This will send JSON instead of form encoded data.
If you do that then you'll also need to:
Set the contentType of the request to indicate that you are sending JSON
Explicitly parse the JSON in PHP
So you probably don't want to do that.

Related

Serializing Array, reducing it, and serving just the name and value of the inputs in the array to ajax post

I have a form pushing to Zapier. I serialize the inputs into an array and then reduce it. Here's the code I use:
$(function() {
$("#lead-gen-form").submit(function() {
const formInputSerializedArray = $(this).serializeArray();
const ajaxData = formInputSerializedArray.reduce((acc, { name, value }) => ({ ...acc, [name]: value }), {});
$.ajax({
url: "",
type: "POST",
data: { ajaxData },
dataType: "jsonp",
cache: false,
success: function(data) {
window.location = "../sent";
},
});
return false;
});
});
This results in this, which is including the name of the const and adding brackets around the name of the input, when all I really want to pull is the name of the input:
ajaxData[utm_campaign]: test
ajaxData[utm_term]: 12
ajaxData[utm_content]: comm
ajaxData[utm_medium]: email
ajaxData[utm_source]: sig
What I am looking to make it result in is:
utm_campaign: test
utm_term: 12
utm_content: comm
utm_medium: email
utm_source: sig
When data is serialized by Ajax as JSON, it will include the name of the object being passed in so that it will create correctly formed JSON. The anonymous object created by this data: { ajaxData } gets turned into '{ "ajaxData": { "utm_campaign": ... } }'
Simply remove the surrounding {} (use just data: ajaxData) and you will get the expected '{ "utm_campaign": ... }'

Passing an array to parse through AJAX

I'm trying to pass an array through an AJAX call to the backend, the array gets pushed to the backend, but I'm getting the error "Trying to get property 'id' of non-object"
This is the
var items = [];
$("input:checkbox[name='refundcheck']:checked").each(function(){
let id = $(this).val();
let item = {
"id": id,
"quantity": $('#quantity'+id).val()
};
items.push(item);
});
$.ajax({
type: "GET",
url: '{{url("/")}}/products',
data: {items:items},
dataType: 'JSON',
beforeSend:function (){
//$("#loadingDiv").show();
} ,
success: function( msg ) {
}
});
This is the console log for that array
I've tried both of these possibilities
$productarraylist = $request->items;
foreach($productarraylist as $item){
$product= dbtable::find($item->id);
}
AND
foreach($productarraylist as $i=> $item){
$product= dbtable::find($item->id);
}
This is the var_dump result of the array in the backend.
I tried to JSON.decode the array on the backend, and it says I need to pass a string, not an object.
You are dealing with arrays and not objects, try this:
foreach($productarraylist as $item){
$product= dbtable::find($item['id']);
}

Javascript error parsing http response

I am trying to parse the response from the www.skiddle.com API in Javascript:
$.ajax({
url: 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
type: "GET",
success: function(response) {
var list = [];
$(response).find("results").each(function() {
var el = $(this);
var obj = {
"eventname": el.find("eventname").text(),
"imageurl" : el.find("imageurl").text(),
};
list.push(obj);
});
The response actually has a results property with one element in the array:
{error: 0, totalcount: "1", pagecount: 1, results: Array(1)}
but I can't seem to parse it correctly, $(response).find("results") returns nothing.
If you are sure that there will be a result array property in your response, you may simply use response.results which gives you the array.
success: function(response) {
$.each(response.results,function(indx,item){
console.log(item);
var obj = {
eventname: item.eventname,
imageurl : item.imageurl
};
list.push(obj);
});
}
Assuming list is an array defined earlier.
Also if you are sure there will be only one item in the array, you do not need a loop, you can access it via response.results[0]
success: function(response) {
if (response.results.length>0) {
var obj = { eventName: response.results[0].eventname,
imageurl : response.results[0].imageurl };
list.push(obj);
}
}
I also noticed that the your new object has the same property names as the object you are iterating. In that case, you can simply add the same object
list.push(response.results[0]);
Of course this will add the first item as it is , which means if that has additional properties (other than eventname and imageurl) those will be present in the item you are adding to list now..
The response you are getting is a JSON, you are trying to parse it as XML.
The list you are trying to get can be obtained by simply using
success: function(response) {
var list = (response.results || []).map(function(result) {
return {
eventname: result.eventname,
imageurl : result.imageurl
};
});
}

how to pass array of object in Javascript to C# mvc5 model

is there a way to pass an array of object and then assign it to model?
i searched that making the same variable name in your model and object will do the work but it doesn't work for me.
the model always get null values.
var answers = [];
var answerOthers = [];
var comment = $("#message").val();
$("input:radio:checked").each(function () {
var questno = $(this).attr("data-question");
var ansid = $(this).val();
answers.push({ QUESTIONID: questno, ANSWERID: ansid});
if ($(this).val() == 3)
{
var txtOther = $("#otherTxt-" + $(this).attr("data-question")).val();
answerOthers.push({
QUESTIONID: questno,
ANSWER: txtOther
});
}
});
$.ajax({
url: 'insertQuestions',
data: { answers: answers, answer_others: answerOthers, userid: userid , comment: comment },
method: 'GET',
success: function ()
{
alert("saved");
},
error: function (e)
{
console.log(e);
}
});
c# controller
public void insertQuestions(List<ratingsModel.ANSWERS> answers,
List<ratingsModel.ANSWERS_OTHERS> answer_others, int userid , string comment)
{
insertAnswers(answers,userid);
insertAnswer_others(answer_others, userid);
MySqlConnection myconn2 = new MySqlConnection(cmn.connstring);
myconn2.Open();
string query3 = "INSERT INTO comments (userid,comment) VALUES" +
" (#userid,#comment)";
MySqlCommand cmd2 = new MySqlCommand(query3, myconn2);
cmd2.Parameters.AddWithValue("#userid", userid);
cmd2.Parameters.AddWithValue("#comment", comment);
cmd2.ExecuteNonQuery();
myconn2.Close();
}
You cannot do that with a GET (the data you pass to the method would need to be a query string and to represent your collections you need individual name/value pairs with collection indexers, for example
data { [0].QUESTIONID: xx, [0].ANSWERID: yy [1].QUESTIONID: zz, .... etc }
But it should not be a GET in any case. Your method is changing data so it should be a POST (and in addition, if your collections were large, your would exceed the query string limit and throw an exception)
Change the ajax code to
$.ajax({
url: #Url.Action('insertQuestions'), // dont hard code your url's
data: JSON.stringify({ answers: answers, answer_others: answerOthers, userid: userid, comment: comment }) // modify,
contentType: 'application/json', // add
method: 'POST', // change
success: function() {
....
As a side note, if you had generated your form correctly using the strongly typed HtmlHelper methods, then you code could simply have been
$.ajax({
url: #Url.Action('insertQuestions'),
data: $('form').serialize(),
method: 'POST',
success: function() {
....
and none of the code for generating the arrays would be required.

Issue with JSON.stringify adding a extra \ and "" to my Json object

Hi I am creating using Javascript an array of object with a key and a value using the following code.
ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });
As a result I have am array of object like this:
key:29; value: 'Country'
Key:12; value: '4,3,5'
when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify
var jObject = JSON.stringify(ValuesArray);
My JSON now which is wrong is:
{
"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"
}
I would like to have a JSON object like this
{
"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]
}
without the quotes around the [] and the character \
Any good idea to solve it.
Thank you
More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:
function PostAPIRequest(address) {
var jObject = JSON.stringify(ValuesArray);
var responseJson = null;
$.ajax({
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
ProcessDataResponse(responseJson);
//TODO: REFRESH THE DATA GRID
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.
alert(xhr.status);
alert(thrownError);
}
})
}
and this how I am receiving it in my API controller
...
// POST api/datavalues/5
public string Post(int id, JObject value)
{
var temp = value;
...
It looks like you are placing a string as the value in your map. You should do something like:
var objMap = {"JObject" : ValuesArray};
var json = JSON.stringify(objMap)
What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.
EDIT
It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for - http://jsfiddle.net/4G5nF/
In your post request, try this
var jObject = {"JObject" : ValuesArray};
$.ajax({ url: address,
type: 'POST',
dataType: 'json',
data: jObject,
success: function (data) { .. }});
Note the change in the data attribute. That is a value that is automatically JSONified for you.
const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))
"{\"a\": 1, \"b\": 2}"
May be you have an old prototype library.
As I remove it, bug has disappeared

Categories