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>
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 need to fetch data from url returned data was JSON.but while trying to fetch i am getting
Uncaught SyntaxError: Unexpected token :
here is the code please check it.
can you please tell me why i am getting this error and how to solve it.
$(document).ready(function () {
var Url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol=LIBERTSHOE";
$.ajax({
contentType: 'application/json',
dataType: 'json',
url: Url + '&callback=?',
success: function (data) {
alert(data);
},
error: function (jqXHR, text, errorThrown) { }
});});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
find fiddle link https://jsfiddle.net/vbpradeep/kf9ad1t3/
it seems that you cant build the URL string inside the JSON
instead of creating it in the JSON like this:
url: Url + '&callback=?',
you can just add it to the end of the original URL string:
var Url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol=LIBERTSHOE&callback=?'";
http://codepen.io/nilestanner/pen/pEOgZj
This removes the syntax error although codepen still shows a cross origin error.
I hope this solves the issue.
$(document).ready(function() {
var Url = "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxGetQuoteJSON.jsp?symbol=LIBERTSHOE&callback=?";
$.ajax({
contentType: 'application/json',
dataType: 'json',
url: Url
}).then(function(data){
//What should happen in success scenarios
console.log('Success');
alert(data)
},function(data){
//what should happen in failure scenarios
console.log('Failure Block');
alert(data)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How can I send data through ajax to a specific method in a another PHP class? In the url value I have pointed to the class file, but where can I assign the method name to use?
$.ajax({
type:'POST',
url:'ResortController.php',
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Pass the data in data:vidData and specify your function name after call of controller.
url = BASE_PATH + 'ResortController/FUNCTION_NAME';
vidData = {id: 123, vidName: "testVideo"};
$.ajax({
type:'POST',
url:url,
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Using $_POST in your function you will get your ajax data in $_POST['vidData'].
Also you need to call data instead of vidData variable in success of ajax console.log(data).
You need to have a server-side mechanism in place to handle how to direct your requests. Presumably the url you are sending a request to just has the class declaration...you need some sort of dispatcher or else php doesn't know what to do:
jQuery:
$.ajax({
type:'POST',
url:'/dispatcher.php',
data: {
"data":vidData,
"class":"ResortController",
"method":"rMethod"
},
cache:false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
/dispatcher.php
<?php
// This is dangerous if you have no controls in place to allow/restrict
// a program to run a command
// Anyone could send a cURL request and run an automated class/method through
// this mechanism unless you have some way to restrict that
if(!empty($_POST['class']) && !empty($_POST['method'])) {
// Here you want to have some way to check that a request is valid and not
// made from some outside source to run arbitrary commands
// I will pretend you have an admin identifier function....
if(is_admin()) {
call_user_func_array(array($_POST['class'],$_POST['method']),array('data'=>$_POST['data']));
}
}
I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.
I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});