I've been trying to make an ajax call to retrieve some data from a database but i don't know why is returning an error.
there's the code
$('#afegir_pagament').submit(function() {
var import_pagament = $('#import_pagament').val();
var id_reserva = $('#id_reserva_hidden').val();
url = "afegir_pagament.php";
data = {import: import_pagament, id_reserva: id_reserva};
$.ajax({
url: url,
dataType: 'application/json',
type: 'post',
data: data,
complete: function(xhr, statusText) {
console.log(xhr.responseText);
},
success: function(responseText) {
$('#pag_import_pagat_propietari').val(responseText.total);
},
error: function(req, status, err) {
alert('Error');
}
});
return false;
});
console.log(xhr.responseText) returns {"total":"230.00"}
ERROR: no conversion from text to application/json
Could somebody help me?
"application/json" is not a valid value for the dataType property. Change it to "json".
See here (comment #7):
Thanks for the report, but this is not a jQuery bug. application/json is not a valid value for the dataType property.
Just change application/json to datatype :"json" and exactly what you trying to do inside the
success function ..if you trying to display this value in your text field just try this..
$("#pag_import_pagat_propietari").attr("#yourid",responseText.total);
Related
I want to use ajax to get a json file in github, I wrote this code:
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType:'json',
success: function(data){
console.log(data);
},
error:function() {
console.log("err");
}
});
but I always get "err" and I check the network , it gets the data
How can I solve this problem, thank you!
Since you have included dataType:'json', in your request, jQuery will validate the returned JSON. In this case, the returned JSON has a semi-colon at the end of the body which is not valid JSON.
{
"name":"Bill Gates",
"street":"Fifth Avenue New York 666",
"age":56,
"phone":"555 1234567"
};
Remove the semi-colon to prevent the error handler from being called.
I think you are getting a parse error which is causing the issue, you can fix the json response or you can remove data type json from you request.
You will get parse error, if your json response is not valid and you are using dataType: 'json'. you can change it dataType: 'text'
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType: 'text',
error: function(data){
//debugger;
alert('err');
},
success:function(data) {
alert(data);
}
});
Reference: jQuery returning "parsererror" for ajax request
1.json file is incorrect. At the end there is a semi colon. Remove that semi colon and it will work fine.
if you dont have access to that file then you can use the following code.
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType:'text',
success: function(data){
console.log(JSON.parse(data.substring(0, data.length - 1)));
},
error:function() {
console.log("err");
}
});
Here I basically get the string and trim its last character and then parse the string back to JSON object.
You are receiving the data in error because you are expecting a JSON response where as the actual response is not a valid JSON.
It has semicolon at the end, it makes a invalid JSON.
Try dataType as text. Here you go with the example https://jsfiddle.net/sfjxsdsx/1/
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type:"get",
dataType:'text',
success: function(data){
console.log(data);
},
error:function() {
console.log("err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Based on the error, parsererror, the url doesn't seem to return valid JSON, while the call expects it to be JSON (dataType: 'json')
You can tell jQuery to parse it as text (using dataType: 'text') and then convert it to JSON manually using JSON.parse.
You'll have to trim out the last ; before you parse.
On a side note, you can use the parameter passed into the error callback to print out the error.
Fixed code:
$.ajax({
url: "https://rawgit.com/nianyuyu/play_javascript/master/1.json",
type: "get",
dataType: 'text',
success: function(response) {
if (!response)
return;
response = response.slice(0, -1); // trim ";" at the end
var data = JSON.parse(response); // convert to object
console.log(data);
},
error: function(err) {
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am making an ajax call below and getting an error I do not understand. The variable response in the success function looks like
{"status": "complete", "username": "test", "error": "0", "message": ""}
however when I call my three alert functions inside the success function, the first one prints out the value above, but the next two print out undefined. I know the error key exists, however the javascript does not recognize it. As a result my window crashes.
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
alert(response); //prints correct response
alert(response.error); //prints undefined
alert(response["error"]); //prints undefined
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
Can somone explain what is happening and how to fix this?
This is due to a combination of two factors:
The server is sending the JSON with the wrong content type
You've used the wrong capitalization for overriding it
Consequently, jQuery is interpreting the JSON as (probably) plain text (which is why alerting the value gives you the raw JSON and not [Object object]).
You should fix this by making sure the server sends the JSON with:
Content-Type: application/json
Since it looks like you are using PHP, you can do that with:
header("Content-Type: application/json");
You should also either remove datatype: 'json' or change it to dataType: 'json'.
that because response is not parse as JSON object to do that you can do it like this:
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
var data = jQuery.parseJSON(response); // <---- Here parse it as JSON
alert(data.error);
// Todo with data
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
I make an ajax POST request to post JSON data to server, and I get a simple text response. I can see that everything works fine because it is shown in the browser's debugger. However, I cannot use it.
callajax1(Callback);
function callajax1(callbackfn) {
$.ajax({
type: "POST",
url: myUrl,
data: JSON.stringify({ Data: data }),
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function (data2) {
callbackfn(data2);
},
failure: function (errMsg) {
}
});
return false;
}
function Callback(data) {
alert(data);
}
No alert is showing.
You say that you are getting a "simple text response" back, but your JavaScript (dataType: "json") says to ignore the content type of the response and parse it as JSON.
Perhaps (since you are sending JSON and claiming it is plain text) you are confusing dataType (override the content type the server returns) and contentType (describe the data you are sending).
If the response is "simple text" and not JSON then you can't parse it as JSON. Either return JSON or use dataType: 'text'.
if result of ajax is text, datatype should be text
if result of ajax is html, datatype should be html
if result of ajax is json, datatype should be json
if result of ajax is xml, datatype should be xml
dataType tell jQuery to parse result in given dataType, default is 'text', though jQuery is intelligent enough to detect which conversion is required.
you can see the answer here:
http://jsfiddle.net/justtal/x9re9/
function callajax1(callbackfn) {
$.ajax({
type: "GET",
url: 'https://gdata.youtube.com/feeds/api/videos',
/*data: JSON.stringify({ Data: data }),*/
/*contentType: "text/plain; charset=utf-8",*/
/*dataType: "json",*/
success: function (data2) {
callbackfn(data2);
},
failure: function (errMsg) {
callbackfn(errMsg);
}
});
return false;
}
var Callback = function (data) {
alert(data);
}
callajax1(Callback);
I'm using the following code to get the dataa from the server:
$.getJSON('http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod?callback=?', dd, function (data) {
alert(data);
});
From the server, I'm sending the byte array as response.
In firebug, in Net > Response tab, I get:
jQuery19101878696953793153_1365677709012([67,37,94,38,42,44,69,67,71,32,97,116,116,97,99,104,101,100,32,102,111,114,32,112,97,116]);
Also in Net > JSON tab, I get data with several keys.
But how to get the data at alert(data);; so that I process on that data.
I don't know, how this thing works.
Edit:
I tried this different approach:
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/javascript",
data: dd,
crossDomain: true,
url: "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function (data) {
alert(JSON.parse(data));
},
complete: function (request, textStatus) { //for additional info
alert(request.responseText);
alert(textStatus);
},
error: function(request, textStatus, errorThrown) {
alert(textStatus);
}
});
But I got: parseerror as alert.
From looking at the docs (I haven't tried this) you need to explicitly tell jQuery that you're making a JSONP call that will invoke the function that's returned. Something like this:-
$.ajax({
type : "GET",
dataType : "jsonp",
url : "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function(data){
alert(data);
}
});
Function you are looking for is JSON.parse. Please try this code :
$.post("YouURL", { 'ParameterName': paramvalue }, function (Data) {
var data = JSON.parse(data);
});
Your response is a function call. If u define function name with name jQuery19101878696953793153_1365677709012 you can process the 'data' else from your server just send the json as a response to $.getJSON's callback to work
The problem was the data was very huge. I was sending array of around 10,00,000+ bytes.
So instead I divided it into list of bytes (each having 1000 bytes) & then sent as response.
I don't know if this is the best solution, but it solved my problem.
BTW, thanks to all for helping me.
Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});