I have a json array created by javascript and need to post it to a php file in order to save the data into the database.
var myArray = [{
"picture":"picture1.jpg",
"picture_comment":"some comment about picture1",
"pictureid":16,
"u0id":80,
"u1id":82,
"u2id":78,
"u3id":79,
"u4id":81,
"param0": "60f3f",
"param1":"48dd2",
"param2":"4f2f7",
"param3":"8d101",
"param4":"5efcc",
"active":false,
"dutyid":1256,
"t":0
},
{
"picture":"picture2.jpg",
"picture_comment":"some comment about picture2",
"pictureid":160,
"u0id":18,
"u1id":48,
"u2id":70,
"u3id":95,
"u4id":74,
"param0": "1123f",
"param1":"48d13",
"param2":"595f7",
"param3":"78ad8",
"param4":"4efdc",
"active":false,
"dutyid":125,
"t":4
}
//goes like this about more than 20 times.
;
I have tried to post it using jQuery.ajax but I was not successful.
$.ajax({
type: "POST",
url: "goDoMyWork.php",
data: myArray,
dataType: "json",
success: function(){
alert("Done! You'll be redirecting now.");
window.location.href = "/index.php";
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert("Fail!");
}
});
I have to insert some of the data into one table and some of them into another table.
I have got the following error using:
alert(jqXHR + '-' + textStatus + '-' + errorThrown);
[object Object]-parsererror-SyntaxError: JSON.parse: unexpected character
Try changing data: myArray to data: {mydata : myArray}. Passing your array directly causes jQuery to pass it in an odd format. http://api.jquery.com/jQuery.param/
JSON.parse is the function that transforms text in json-format into a JavaScript object. What you seem to be wanting to do is throw some data at the server, where the server will handle it further.
What you are actually doing is setting the dataType to json. In the documentation you can read that this is the data-type you are expecting to get back from the server. jQuery will therefor throw the data it gets back from the server through JSON.parse, but apparently the data is not a well-formed json-string. Removing the dataType from your request will fix this, as the data will most likely not be parsed. Therefor, whatever gets returned will be in the form of a string.
Related
I've almost viewed similar kind of questions but my problem has not solved yet.
I've following codes.
Controller
def create
#task_list = TaskList.new(task_list_params)
if #task_list.save
respond_to do |format|
format.json { render json: #task_list}
end
else
return
end
end
Ajax Script
$(document).on('click','.add', function(){
count = 0;
user_id = $('#user_id').val();
var name = $('.new-list').val();
var current = $(this);
if(name){
$.ajax({
method: 'POST',
url: action,
dataType: 'JSON',
data: {
task_list: {
name: name,
user_id: user_id
}
}
}).success(function(response){
var data = JSON.stringify(response);
alert(data.id);
$(current).parent().parent().parent().before(
'<div class="col-md-12">'+
''+name+''+
'</div>'
);
$(current).parent().parent().parent().remove();
$('.add-list').show();
});
}else{
alert('please add title');
}
});
I just want to take id of the record just saved to the database through ajax post request. Here, in success function it just alerts undefined and I don't know what's going wrong.
This is sample response.
.success(function(response){
alert(response.id);
Remove JSON.stringify from your success function. Response is already in JSON format you can directly get the value from it.
JSON.stringfy converts javascript object into string.
Explanation
Your response is already in JSON format and you have used dataType: "JSON" in your AJAX call. Which will make it possible to transfer JSON data between server and client.
When your response is already in JSON format you can use its property without parsing it. I.e response.id
If you have not used dataType: "JSON" and you are passing json encoded response from your controller to view file you have to first decode the response to get its values.
var d = $.parseJSON(response);
alert(d.id);
var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/
I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array
Hi I am doing a ajax post via a JSP. I am posting JSON data in string format (parsed using parseJSON, then I use the JSON stringify to return to a string.
This post works fine. But what I am not sure how to do, is basiclally I sending this to a a client gateway, which translates this jsonString into XML to do some internal processing. This internal work will generate an XML response, that needs to be sent back to my JSP. I plan on receiving and this XML in the ajax post 'success' function facility.
So far I have been able to make this work with the success function "data" item being HTML. But I am not sure how this can be done when I want to XML. How do I do this? How do I receive XML, and how do you host/find/display the XML for it to be returned in the sucess 'data' function?
My other option, is that if it is not XML that I want to recieve, I could possibliy receive JSON data. How can I host/find/display JSON data for it to be returned in the sucess 'data' function?
This is my post code:
$.ajax({
type: "POST",
url: suppliedURL,
data: "jsonData=" + jsonString, // I have already done a json stringify on this.
success: function(data, textStatus, jqXHR) {
alert('Success : ' + data); .. I want this to be XML
alert('textStatus : ' + textStatus);
alert('jqXHR : ' + jqXHR);
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
//complete: alert('complete'),
dataType: "text" // xml, json, script, text, html
});
Change dataType to xml; after that data in the success method will be an XML document.
Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I'm using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)
#{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
#Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying "parsererror".
I recently encountered this problem and stumbled upon this question.
I resolved it with a much easier way.
Method One
You can either remove the dataType: 'json' property from the object literal...
Method Two
Or you can do what #Sagiv was saying by returning your data as Json.
The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.
So if you remove the dataType: json property, it will not try to parse it as Json.
With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.
See the answer by #david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
the problem is that your controller returning string or other object that can't be parsed.
the ajax call expected to get Json in return. try to return JsonResult in the controller like that:
public JsonResult YourAction()
{
...return Json(YourReturnObject);
}
hope it helps :)
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
Your JSON data might be wrong. http://jsonformatter.curiousconcept.com/ to validate it.
Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.
I don't know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.
If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false.
As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.
$.ajax({
url: '/Test/Something/',
type: 'GET',
dataType: 'json',
cache: false,
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
you should remove the dataType: "json". Then see the magic... the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
incase of Get operation from web .net mvc/api, make sure you are allow get
return Json(data,JsonRequestBehavior.AllowGet);
If you don't want to remove/change dataType: json, you can override jQuery's strict parsing by defining a custom converter:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
I was also getting "Request return with error:parsererror." in the javascript console.
In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
I have encountered such error but after modifying my response before sending it to the client it worked fine.
//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response); // Sending to client
//Client side
success: function(res, status) {
response = JSON.parse(res); // Getting as expected
//Do something
}
I had the same problem, turned out my web.config was not the same with my teammates.
So please check your web.config.
Hope this helps someone.
I ran into the same issue. What I found to solve my issue was to make sure to use double quotes instead of single quotes.
echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';
The problem
window.JSON.parse raises an error in $.parseJSON function.
<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>
My solution
Overloading JQuery using requirejs tool.
<pre>
define(['jquery', 'jquery.overload'], function() {
//Loading jquery.overload
});
</pre>
jquery.overload.js file content
<pre>
define(['jquery'],function ($) {
$.parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
/** THIS RAISES Parsing ERROR
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
**/
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "#" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
$.error( "Invalid JSON: " + data );
}
return $;
});
</pre>