how to use ajax to get a json file in github - javascript

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>

Related

Calling a PHP returning a JSON returns an error though I can see the response

This is the javascript I'm using to make an AJAX call to a PHP:
$(document).ready(function(e) {
$(function(){
$.ajax({
type:'GET',
dataType: 'jsonp',
data: {
country: "uk"
},
url: 'http://api.mysite.uk/advertorial/index.php',
success: function (response){
var result = $.parseJSON(response);
console.log(result);
},
error : function () {
console.log('Error');
}
});
});
});
which returns a JSON structured like this:
{"id":"1","name":"test","country":"uk","header":"Header","pre_cta_text":"Pre CTA","cta_text":"CTA text","cta":"CTA","img":null,"active":"1"}
Even if the call gives an error, I can see that it's returning the JSON above. I particular the error I get in browser console is:
Uncaught SyntaxError: Unexpected token :
index.php?callback=jQuery32103297264247416809_1516181997373&country=uk&_=1516181997374:1
You instruct jQuery to ask for JSONP and decode it automatically:
dataType: 'jsonp',
Then you take jQuery's decoded data and handle it as JSON, which is not and has never been:
success: function (response){
var result = $.parseJSON(response);
console.log(result);
}

value missing on AJAX response

I can't find what the error is in an AJAX call.
I have a PHP file output:
[{"value":"123","name":"My Name"}]
and this output is correct. And my AJAX call returns undefined after success:
$.ajax({
type: "POST",
url: "correct_file_location.php",
data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
alert(pk.value);
$("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
});
Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object.
pk[0].value
should work.
*It is showing undefined because you are getting an array of objects and not only object *
try what #freedomn-m suggested in the comments
Try below code it will be work.
$.ajax({
type: "POST",
url: "correct_file_location.php",
//data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
var data1 = JSON.parse(pk[0].value);
console.log(data1);
// $("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
}) ;
Your code will also work but your php response code must be in javascript object.
Please add below code in 'correct_file_location.php' and check with your ajax code.
'{"value":"123","name":"My Name"}';

Jquery request always fails

I am currently using the dark sky forecast api https://developer.forecast.io/ to retrieve json object via jquery get request.the required url parameters format is (api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE") while the valid format with the parameters is:
https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115
inputting this url in your browser will show you a json object.
First thing i tried was a jquery get request :
$.ajax({
type: 'GET'
, data: ''
, url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115"
, success: function (data) {
alert("works");
}
, datatype: 'json'
, error: function (err) {
alert("Could not get forecast");
}
});
this is not succesful- it triggers the error function. i try again using a post request it doesnt work either.please help
This is a simple CORS issue which can be easily resolved by using jsonp datatype:
$.ajax({
url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115",
dataType: "jsonp",
success: function(data) {
console.log(data.latitude, data.longitude);
console.log(data.timezone);
console.log(data.daily.summary);
},
error: function(err) {
console.log("Could not get forecast");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<em>Loading . . .<em>

Getting data through jQuery ajax request

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.

jquery not properly serializing json in ajax call

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) {
});

Categories