GSON Not an Object Error - javascript

I have the following json object:
cNGJSON = {
"one": graph1.graphNode, "two": graph2.graphNode, "three": graph3.graphNode, "four": graph4.graphNode, "five": graph5.graphNode,"six": graph6.graphNode,
"seven": graph7.graphNode,"eight": graph8.graphNode, "nine": graph9.graphNode,"ten": graph10.graphNode, "eleven": graph11.graphNode, "twelve": graph12.graphNode,
"thirteen": graph13.graphNode,"fourteen": graph14.graphNode,"fifteen": graph15.graphNode,"sixteen": graph16.graphNode, "seventeen": graph17.graphNode, "eighteen": graph18.graphNode,
"nineteen": graph19.graphNode
};
where graph1.graphNode is an integer array.
[1,2,3,4]
I send this to the server with jQuery:
$.ajax({
url: 'validate',
type: 'post',
dataType: 'json',
success: function (data) {
console.log("Success!!");
},
data: cNGJSON
});
However I get a
Expected BEGIN_OBJECT but was STRING at line 1 column 1
Error every time I try.
I tried with setting the cNGJSON to:
cNGJSON = {
"one": "Number one", "two": "Number two"
};
Still I get the same error.

As you want to send JSON object in your XHR request you need to stringify the JSON object first
$.ajax({
url: 'validate',
type: 'post',
dataType: 'json',
success: function (data) {
console.log("Success!!");
},
data: JSON.stringify(cNGJSON)
});

Related

Unable to get array in controller from ajax

Not getting array of data from ajax to controller.
$.ajax({
type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: {
"Query": JSON.stringify(Query) //change this
success: function() {}
});,
And array of Query :
0: {label: "abc:", value: "123", type: "Select"} 1: {label: "xyz",
value: "Hum", type: "text"}
Can anyone help ?
Try something like this
<script type="text/javascript">
var query=[{label: "abc:", value: "123", type: "Select"},{label: "abc:", value: "1232", type: "Select"} ];
$.ajax({ type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: JSON.stringify(query),
success: function (){
} });
</script>
I think something along this may work for you.
function sendarray() {
var arr = [];
var json = {
"label": 'abc',
"value": 1234,
"Name": 'Name'
};
arr.push(json);
json = {
"label": 'abc2',
"value": 1234,
"Name": 'Name2'
};
arr.push(json);
var myarray = JSON.stringify(arr);
$.ajax({
url: '/controller/GetArray',
type: 'POST',
data: { array: myarray },
success: function (data) {
//Do something
},
error: function () {
//Do something
}
});
}
then in the controller
public JsonResult GetArray(string array)
{
var obj = JsonConvert.DeserializeObject<object>(array);
return Json("");
}
This will send an string with all the data in the array to the controller, then you turn string with json format into an object list

How to ignore JSON data when posting through AJAX?

Actually my JSON data as an object i am sending through AJAX is:
{
plotId: "668",
geogPhysZone: "4",
districtCode: "4",
posMethod: "1",
sRS: "45",
crewLeader: "",
date: "",
distanceToOtherLanduse: "",
distanceToSettlement: ""
}
But the value, which are going null from JSON is not available in my table column while posting, so I am getting 500 (Internal Server Error). So while sending from AJAX I want to ignore the value which are null.
My code is called when button is clicked:
$("#generalSubmitButton").click(function(event) {
event.preventDefault();
var form_data = Object.assign($("#generalForm1").toObject(), $("#headForm").toObject());
console.log(form_data);
$.ajax({
url: A_PAGE_CONTEXT_PATH + "/form/api/plot-general/save",
method: "post",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(form_data),
success: function() {
alert("Successful");
},
error: function(response) {
switch (response.status) {
case 409:
alert("error");
}
}
});
});
You can iterate through object and eliminate objects which don't have value.
var myObject= {plotId: "668", geogPhysZone: "4", districtCode: "4", posMethod: "1", sRS: "45",crewLeader:"",date:"",distanceToOtherLanduse:"",distanceToSettlement:""};
Object.keys(myObject).forEach(function(key) {
var val = myObject[key];
if($.trim(val).length == 0){ //delete which are null or blank
delete myObject[key];
}
});
Demo

Pass object to PHP through AJAX

I was wondering if it is possible to pass an array to a php function using the jQuery AJAX function. I have the following as my javascript
arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}
$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'field01': arr_data["field01"],
'field02': arr_data["field02"],
'field03': arr_data["field03"],
'field04': arr_data["field04"]
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});
When I try to do the following though
arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}
$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'data': arr_data
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});
I receive it in the PHP as "Array". How can I correctly send the object so that it is usable by the PHP function?
Please try to pass the array in the format of json. Then use the get the json in your php and access the json array.
<script>
arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}
var myJsonString= JSON.stringify(arr_data);
$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'data': myJsonString
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});
</script>
this is your java script. and below is the php
$dataJson=json_decode($_GET['data']);
here you can get the json array and loop through it and do what ever you want.
Please have try at this. This is working in my case.
from the second ajax you can access the data based on the property names like: $_GET['data']['field01']
$_GET['data'] is the js object converted in php in a associative array
try this :
$.ajax({
url: "scripts/php/phpfunc.php",
method: "POST",
dataType: "json",
data: {
'action': "exec_find",
'data': arr_data.serialize()
},
serialize()
http://api.jquery.com/serialize/
convert your array in string

parse json using ajax success function

I'm trying to display the json that i get and parse it in the success function of ajax.
What I have so far:
Ajax:
data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val();
alert(data);
url= "/portal/getResults.php";
$.ajax({
url: url,
type: "POST",
//pass the data
data: data,
dataType: 'json',
cache: false,
//success
success: function(data) {
alert(data);
}
});
getResults.php (JSON output):
{
"results": [
{
"DocId": 2204,
"Title": "Lorem ipsum dolor sit amet, consectetur",
"Locations": [
{
"State": "New York",
"City": ""
},
{
"State": "New York",
"City": "New York City"
}
],
"Topics": [
3,
7,
11
],
"PublicationYear": "2011",
"Organization": "New Yorks Times",
"WebLocation": "www.google.com",
"Description": "Lorem Ipsum"
}
],
"TotalMatches": 1
}
I expect the result in data to be the the json from getResults.php but instead I get [object Object].
I have also tried the code below but get no response:
success: function(data) {
var json1 = JSON.parse(data);
alert(json1);
}
since you're telling jQuery that you want dataType:'json', the ajax function parses the JSON response into an object for you. the result object you see should be an object with data matching the JSON response from your server. if you need the string version, try JSON.stringify(), otherwise you can just use the object as is: data['results'][0]['DocId'], etc
good luck!
Here is an example for your request : http://jsfiddle.net/5y5ea98n/
var echo = function(dataPass) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: dataPass,
cache: false,
success: function(json) {
alert(JSON.stringify(json));
}
});
};
$('.list').live('click', function() {
$.get("http://www.json-generator.com/api/json/get/bQxORzxQGG?indent=2", function(data) {
var json = {
json: JSON.stringify(data),
delay: 1
};
echo(json);
});
});
I tried some code relate to this and it worked successfully.
function ajaxToParseJson(){
AUI().use('aui-io-request', function(A){
A.io.request('${jsonAjaxURL}', {
dataType:'json',
method: 'post',
data: {
execute: 'JsonLogic',
numberVal:'Pass Json String Here if needed from Screen'
},
on: {
success: function()
{
var empName = this.get('responseData').name;
var id = this.get('responseData').id;
console.log("Name: "+empName);
console.log("Id: "+id);
/** Since return type of this function is bydefault Json it will return Json still if you want to check string below is the way**/
var data = JSON.stringify(this.get('responseData'));
alert(data);
}
}
});
});
}
I have an Employee Class with two fields id,name.

What's wrong with my data, received through JQuery AJAX request?

I'm making an API call with this code:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
})
That returns nothing, except for an error in the console saying:
"Uncaught TypeError: Cannot read property 'item' of undefined"
The JSON data looks like this when I use the url in the browser:
{
"folder": {
"item": 123123,
"item 2": false,
"item 3": "content",
"item 4": [
{
"subitem": "content"
},
{
"subitem": "content2"
}
]
}
}
I was expecting "123123" in the alertbox, but nope. So what am I doing wrong?
If its a JSON string you are getting it will need to be parsed. Try this:
$.ajax({
type: "GET",
url: "https://example/example.json",
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
var parsed = JSON.parse(data);
alert(parsed.folder.item);
}
});
Or to force jquery to parse it for you:
$.ajax({
type: "GET",
url: "https://example/example.json",
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("apikey", "user")
},
success: function(data){
alert(data.folder.item);
}
});

Categories