Convert JavaScript Object or Array to JSON for Ajax Data

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

Arrays in AJAX request JSON object data

You weren't passing a JSON string through ajax which is why you couldn't handle the data on the back end.

var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}

var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: JSON.stringify(data),
contentType: 'application/json', // for request
dataType: 'json' // for response
});

Getting JSON data with AJAX and converting to array of strings

It will depend on what your putting the objects into. The objects you've been given are just fine, but in order to access the values inside them you will need to access them via the DisplayName property.

$.each(results, function(i,e) {
console.log(e.DisplayName);
})

This would log XXX Street Middle School, XXXX Schools, etc.

To circumvent this behavior, do not shove the values into a named part of the array.
I assume you want the result to look similar to:

["XXX Street", "xxxxx school", "xxxx", ... ]

So in your php code, you want to do something like this:

$json = array();
foreach($school in $schools) {
array_push($json, $school->displayName); //obviously this is unique to your application and not this verbatim
}
echo json_encode($json);

Basically, you want a list, not an associative array. Now, if you had more information you needed to display about a single school you would want an associative array. But given your usage desires, I believe this is closer to what you need.

As an aside, if you use the $.getJSON() function in jQuery (as opposed to $.get), you can avoid using the call to jQuery.parseJSON() and will just get a json object in your success function.

How to convert ajax array of objects into array of arrays

Maybe you need this solution:

var aData = [];
$http({
method: 'POST',
url: 'server/search/searchQuery.php',
data: {data: 'getData', searchText: id.SearchText , typeOfStudy: qTypeOfStudy , typeOfSpecies: qTypeOfSpecies , typeOfSpeciality: qTypeOfSpeciality },
headers: {'Content-Type': 'application/json'},
dataType:"json"
}).success(function(data) {
var aData = [];
for(var k in data){
aData.push(data[k].id, data[k].primary_authors, data[k].primary_titles, data[k].pub_year);
}
}

Convert ajax response array object to javascript array?

Encode it to JSON.

In your php:

echo json_encode($model->getErrors());

In your js (in the else):

var errors = $.parseJSON(response);

Edit:

In your case it would be better to always return JSON.

Your JS could be changed to:

var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {
...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});

Your PHP:

$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

Here is a working demo like below:

1.Model:

public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}

2.View(remove Content-type):

<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>

3.Console.log(group):

Sample Image

4.Result:
Sample Image

Update:

Another way by using json:

1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):

<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",

data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>

2.Controller(add FromBody):

[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}


Related Topics



Leave a reply



Submit