After awhile of not using JSON, I'm a little rusty on the possibility of requesting the data from another domain/web-server.
I'm just trying to get the JSON resource to load onto my web server when the JSON file is hosted from GitHub. Using AnyOrigin, I used this script
$( document ).ready(function() {
$.ajax({
dataType: "json",
url: 'http://anyorigin.com/get?url=,https%3A//raw.githubusercontent.com/testuser/testbin/master/data/&callback=?',
success: function(result){
run(result);
}
});
});
In my index.php, I have a file that references the json.. but it doesn't parse it.
<a href="https://raw.githubusercontent.com/testuser/testbin/master/data/<?php echo $post['filename']; ?>">
I am a bit lost at this point. What am I doing wrong? Am I not specifying something correctly? All help is appreciated. Thank you for your time.
You need to use JSONP as a dataType in your ajax request as you are sending a request to the external link. Also, need to need to receive the response in the callback function with JSON.
For more detail, check https://www.w3schools.com/js/js_json_jsonp.asp
This example might be helpful for you as well https://www.sitepoint.com/jsonp-examples/
Related
I have a HTML table with sport results on a third party server that I would like to parse as a JSON or XML so I can grab me the values out of it...
I would prefer to do this with jQuery and already played around with $.ajax but I don't get it running :/
I also thought about a PHP script running on my server and doing something with file_get_contents() and parsing the result as JSON - without success...
Dose anyone have an idea - what is the best solution to do what I want? I need a thought-provoking impulse ;)
My jQuery attempt:
$.ajax({
dataType: "jsonp",
url: "....",
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
});
Running in to an error:
As per comments:
For cross-site content, make a proxy script using PHP. All this will need to do is grab the remote content and echo it out.
Your ajax request will then point to this script instead, and you will be able to parse the response using standard jQuery functions as if it were a normal page e.g. $(data).filter('table');
Your 'dataType' is wrong? Shouldn't that be either 'html' or 'json' since i see you are receiving HTML content.
I tried following some basic examples, and it is not working. I am not sure I completely understand jsonp, but I followed the basic tutorials and on an intuitive level, I can't see anything wrong. (Of course, I am missing something, hence the question).
JavaScript code:
postData = $(this).serialize();
console.log(postData);
$.ajax({
data: postData,
url: 'externaldomain.php',
dataType: 'jsonp',
success: function(data){
console.log(data);
alert('Your comment was successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding your comment');
}
});
PHP code:
$tag = mysql_real_escape_string($_GET["callback"]);
The annoying part is that it is not even showing me an error to Google for.
Can anyone help out figuring the problem please?
Since you haven't posted your full or relevant PHP code I'm going to assume it looks like this
$tag = mysql_real_escape_string($_GET["callback"]);
echo $tag."(";
// print json here
echo ")"
I'm not really sure how jquery handles jsonp requests but what I used to do is add a new script tag to the DOM that looks like this
<script> function cb(json) { alert(json); } </script> // (I)
<script src="{url}?callback=cb"></script> // (II)
When (II) is loaded, and because we have a callback then the script that we are including in the DOM looks like this
cb({
// json goes here
})
which pretty much is like a function call to some function called cb that we are using. It is therefore natural to have an implementation of cb (which is in (I)). That implementation is similar to the success(data) function in jQuery's ajax. It is used to use and manipulate the json requested
However I noticed that you are doing a POST request along the ajax call with jsonp. Unfortuantely (according to this question How to make a jsonp POST request that specifies contentType with jQuery?) doing POST with JSONP is not feasable due to implementation pursposes.
You can't POST using JSONP... it simply doesn't work that way...
So you can usually only perform GET requests. You can NOT perform POST requests.
For details about how jsonp work look at this nice article. jsonp-how-does-it-work
For more clearification :
See Other SO question Link1 Link 2
But there is work around for that with some limitations look at this Using PUT/POST/DELETE with JSONP and jQuery. (for me nothing works at all)
The client website needs to do a cross-domain JQuery Ajax call to a php file on my server, the php file will query the database for a bunch of stored javascripts which then need to be sent back to the client and be executed on the client's website. This is what i have so far, haven't done the grabbing javascript from database yet and it works. Is this the best way to do this (assuming i can grab the javascripts directly from the database without adding the escape sequence when echo'ing back to the client)? Thanks.
This is what i have so far:
client side:
$.ajax({ url: "http://localhost:8888/test.php",
dataType: "script",
});
server side (test.php):
<?php
echo "alert(\"WORKS!\");";
?>
Review the ajax documentation and handle the success callback option on the ajax method:
$.ajax({
url: "http://localhost:8888/test.php",
dataType: "html",
success : function(data) { alert(data); }
});
As noted by Ricardo, your PHP script should echo HTML or some other content appropriate for your scenario.
See http://api.jquery.com/jQuery.get/
And http://api.jquery.com/jQuery.getJSON/
I am building an application in which i am trying to fetch the list of places near to a given lat and long.
i got a api key and entering this on my browser url works and gives me a json file with the places data.
https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I
but when i try to fetch and parse it though j query its not giving me anything.
$(document).ready(function(){
$.getJSON('https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I',
function(data) {
alert(data);
});
i found the following questions on stack overflow but they dint reach me to an answer.
parse google place json with javascript
How do I use Google Places to get an array of Place names?
EDIT:
i tried to get contents of the file using php by
echo file_get_contents("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I");
and got the file contents using php.
But is there a way to parse this with jquery or javascript ?
Thank you for your help.
It's not possible using ajax (directly) cross domain request are not allowed. I've tried:
echo file_get_contents("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I");
it works for me (wamp 2.0 openssl enabled).
if you succeed in this, you can get the content using your ajax script on the page in the same domain.
EDIT:
The idea is to do an ajax call to your php page, the php page gets data from de google api and returns it. jquery automatically parses json :)
in code:
$.ajax({
url: 'url_to_your_php',
data: {
location:'-33.8670522,151.1957362',
radius:500,
sensor:false,
key:'AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I'},
dataType: "json"
type: "GET", //or POST if you want => update your php in that case
success: function( data ) {
for(var i in data.results){
doSomthingWithYourLocation(data.results[i]);
}
},
error: function (request, status, error) {
//handle errors
}
});
Your php shoud do somthing like this:
<?php
header('Content-type: application/json');
echo file_get_contents("https://maps.googleapis.com/maps/api/place/search/json?" .
"location=-" . $_GET['location'] .
"&radius=" . $_GET['radius'] .
"&sensor=" . $_GET['sensor'] .
"&key=" .$_GET['key']);
?>
It is probably best to check the input in the php files but this should work.
A script loaded from one domain can't make an ajax request to another domain. Use the Google Maps JavaScript api to load your data.
The places javascript API can be accessed here: http://code.google.com/apis/maps/documentation/javascript/places.html
You can parse your object data this way:
$(document).ready(function(){
$.getJSON('https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyAImBQiqvaXOQtqeK8VC-9I96kMmB6Mz7I', function(data) {
$.each(data, function(index,place) {
alert(place.name);
});
});
});
Hope it helps.
i took some interest in this script http://www.9lessons.info/2009/06/comment-system-with-jquery-ajax-and-php.html
and i see that the ajax calls commentajax.php.
what i want to do is to ignore that php, because i want to post to a json file and then get the response from the same file.
my server will use POST or PUT to put the data in the database, so there is no need for me to use php, just the syntax is killing me :)
i want to use :
$.ajax({
type: "POST",
url: "http://www.xxx.com/json",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
but then how would the commentajax.php look like?
maybe replace the php with :
$.getJSON('http://www.xxx.com/json' , function(data) { ... });
any idea helps
Thanks.
edit1: i have the server-side script in place
If you have the server side scripting set up already, then what is the question again?
If you're asking how to handle the ajax call, then it's mostly a matter of looping through the JSON that you get back, and applying those values to the site in some manner. Pseudo code:
$.getJSON('http://www.xxx.com/json' , function(data) {
for(i=0; i<data.comment.length; i++) {
$(".commentTitle").html(data.comment[i].title);
$(".commentBody").html(data.comment[i].text);
}
});
If I am reading this correctly:
because i want to post to a json file and then get the response from the same file.
You are going to need some server side scripting in order to 'post' to the json file. How are you getting the data into the file.
You can 'read' the data file from the server, that's not a problem, it is a matter of getting the data into the file that you need the server side scripting for.