I am not really sure how to phrase this question, so I will just ask the best I can.
I would like to know how to grab the contents of a webpage and place it in a string or array so I can parse the data.
This is the webpage: https://campusdata.uark.edu/api/buses?callback=?&routeIds=8
The webpage returns something like this:
?([{"id":25,"fleet":15,"name":"Fleet 15","description":"","zonarId":9,"gpsId":"8061088","latitude":"36.0680039","longitude":"-94.1758039","speed":0.000,"heading":89.700,"power":true,"date":"\/Date(1456339080000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":9999999999,"nextStop":"Garland Center","nextArrival":"8 mins"},{"id":33,"fleet":6,"name":"Fleet 6 ","description":"","zonarId":13,"gpsId":"8061090","latitude":"36.0818423","longitude":"-94.1707598","speed":0.000,"heading":181.700,"power":true,"date":"\/Date(1456339200000)\/","color":"#0090ff","routeName":"Blue","routeId":8,"distance":2.31887983012931,"nextStop":"South Creekside","nextArrival":"1 mins"}]);
I am not sure the best way to go about this... AJAX through JQuery? Maybe a php call? I don't know.
I have searched for this, but like I said, I don't know exactly how to phrase the question, so my search results have been sporadic at best.
Can someone help me please?
Seems like a JSONP call. You can use jQuery to easily fetch the data from the API end point. Please see the example below:
$.ajax({
url: "https://campusdata.uark.edu/api/buses?callback=?&routeIds=8",
// The name of the callback parameter
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
data: {},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
Here is a jsfiddle with working example.
Please make sure to include jquery in the page before trying this.
Your can use this in PHP
$site = file_get_contents("http://campusdata.uark.edu/api/buses?callback=&routeIds=8");
print_r(json_decode($site));
Reference
json_encode
file_get_contents
Get the page content with file_get_contents function. Remove illegal character. Convert the json format to PHP array:
<?php
$page = file_get_contents('https://campusdata.uark.edu/api/buses?callback=?&routeIds=8');
$page = substr($page, 0, -2);
$page = substr($page, 2);
var_dump (json_decode($page));
Related
I am trying to send a row and column number of the clicked cell via GET method.
to php file, where I can check if this cell contains something or not.
For example that the URL will loke like this:
.php?c=3&r=5
I am using:
https://www.w3schools.com/jquery/ajax_get.asp and I have been trying to send data like it is listed on W3schools:
Request "test.php" and send some additional data along with the request (ignore return results):
$.get("test.php", { name:"Donald", town:"Ducktown" });
I am doing it like this:
$(document).ready(function() {
$("td").click(function(event) {
var clickedBtnID = $(this).attr('id');
values=clickedBtnID.split('.');
var row=values[0];
var col=values[1];
$.get("info.php", {"row":row, "col":col});
I was looking at some other examples on StackOverFlow, like:
How to send data to PHP file using JQuery Ajax?
I would like to say it that info.php is the diferent .php file, as the one we are working from. And another thing is that the best way to do this, would be to do it without refreshing the page. So is Ajax call the best way for this? I have tried many different things, but it seems like I can't send the data via GET method.
I'm not 100% sure I understand what you're looking to do, but I'll try to help!
Have you tried something like this? In your js file:
$.get("info.php?c=3&r=5");
Then in your PHP file:
//Retrieve the variables
$c = ($_GET["c"]);
$r = ($_GET["r"]);
//Then do what you need to do with $c and $r
Let me know if that helps.
I have tried this:
$.ajax({ url: 'info.php',
data: {'row':row, 'col':col},
type: 'GET',
success: {}
});
And it works perfectly. I don't know why the jquery $.get didn't work.
I want to send data from php to a browser using JSON. I think I understand the process - see my example code below. But someone told me this is not the right way to do it. I have been researching for three days but because my English is poor I am not confident that I have found an answer.
What I am hoping for is a sample of code that will receive the JSON and pour it into html elements such as a div, and give it style via CSS, etc.
I really just want an example of how to do this so that I can learn from it and expand it myself for my own needs, but I am unconfident that this approach is correct and do not want to write more bad code.
Thanks
Javascript
$(document).ready(function() {
$.ajax({
type : 'POST',
url : 'server.php',
dataType:"json",
success : function (data) {
$("#orders").html(JSON.stringify(data));
}
});
});
PHP
<?php
$db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
$statement=$db->prepare("SELECT * FROM myfeilds");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
You don't need to call JSON.stringify on the data that gets returned in your response. This method is for converting a javascript object to a JSON string, but your PHP code should be sending a JSON string back already by the looks of it.
So it depends on what your returned JSON looks like, but usually it'll be something like this:
{"name":"Mike", "phone":"5551234", ...} etc
So in your success callback, you would do something like this:
$("#name").text(data.name);
$("#phone").text(data.phone);
And so on.
Note that I'm using the .text() method. You could use .html() as you've done but you probably don't need to unless your JSON strings contain HTML or you want to write out HTML like so:
$("#name").html("<p>" + data.name + "</p>");
As for styling, I would setup your styles in advance so that you don't have to do it in javascript as this will be more performant.
However, if for some reason you needed to then you could do something like:
$("#name").css({"display":block","color": "#000"});
Hope that helps.
I'm trying to load a JSON file by link and then align data (like title, date etc) to variables so I can use them. Right now, I don't care about variables. I just want to alert() them but something seems like I'm doing it wrong, alert returns nothing!
I use JSfidle to run the code. The code is this:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json') ;
var JSON = JSON.parse(JSON_unparsed) ;
alert(JSON.feed.entry[0].title.$t) ;
The URL I want to parse is: http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json
and here you can see the JSON how is structured if that can help you:
You can use JSONP for this:
Update, for better understanding how to work with returned JSON.
var id, title;
$.ajax({
url: 'http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json',
jsonp: "callback",
dataType: "jsonp"
}).done(function(r){
// r is returned JSON
for(var i in r)
// for ex ID is this
id = r[i].id.$t;
// and title
title = r[i].title.$t;
// and so on, check the json, I mean check the browser console by hitting F12, below code will print the whole JSON
console.log(r[i]);
});
Codepen link: http://codepen.io/m-dehghani/pen/grXrrp?editors=0010
In addition to adeneo's reply, in your code, JSON_unparsed variable is holding something called (differed or promise object), this object might be holding the data inside it,but you are using the wrong way to pull it out. in order for you to get it out, you need to call (.done()) function, see the below:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json').done(function(json){
console.log(json);
console.log(json.feed.entry[0].title.$t);
});
aside from that, if you got an error with something like this:
XMLHttpRequest cannot load http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json&_=1459788714707. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.
it means that you are not allowed to call this API/URL from your current domain.
One more thing, if you are using getJSON method, there is no need to parse the returned data, jquery will parse it for you
I have searched here and on Google, but as an inexperienced Javascript hack I'm struggling to find a good example of what I believe is a rather straight forward action.
I have a server-side script that I have coded to provide JSON formatted output (content.php?action=json).
The JSON output is multi-dimensional, ie it is formatted as ...
[Content]
[Class 1]
[Entry 1]
[Entry 2]
[Entry 3]
...
[Class 2]
[Entry 1]
[Entry 2]
...
Both the number of classes and entries are variable.
I am now trying to write a simple Javascript to do the following ...
1) Call my PHP script
2) Copy the returned JSON output into a suitable Javascript array
3) Display parts of this array within my HTML pages
There are a number of "bits" of this puzzle, but I am struggling to put this together. Would anyone put a simple example together for me?
A couple of side questions ...
(i) Does the output file containing the JSON data need to have it's HTML headers altered to indicate it's content type?
(ii) Is jQuery the best approach for this sort of thing?
Thanks in advance.
Pete
jQuery does provide a very easy approach to ajax calls:
$.ajax({
url: '/path-to-php-script',
type: 'get',
dataType: 'json',
success: function(json) {
// gets run after ajax call is successful
// do stuff with json object
// format: json.content.class[0].entry[2]
}
});
Providing dataType: 'json' will automatically eval the response from your php script into a json object.
Here's the jQuery documentation on ajax calls: http://api.jquery.com/jQuery.ajax/
You can control the format of your json data when you create it so you don't need to copy it into an array once you have retrieved it.
$.get("your_php_script.php",
function(data){
// update html with json ( in data )
}, "json");
http://api.jquery.com/jQuery.get/
To answer your side questions
i) the content type for json is application/json
ii) jQuery is the a good ( and popular ) way to retrieve your json as it abstracts away the different methods that browsers will make an ajax request.
(i) the content type can just be plain text. However to be correct, see What is the correct JSON content type?
(ii) jQuery will make fetching and parsing the JSON very easy, although there are other libraries that do this as well. Many people advocate jQuery due to its usability, though.
Now to answer your main question, using jQuery:
$.getJSON('content.php?action=json', function(data) {
// data returns the result of the request, and will be the array
});
See http://api.jquery.com/jQuery.getJSON/
Here's some simple Javascript:
(function($){
var ajax_callback = function(data) { window.location.hash = data.h1; };
$('.clickable').live('click', function() {
$.post('server.fcgi', {}, ajax_callback, 'json');
}
);
})(jQuery);
The server is a c++ binary (yes, i know) that spits out (through fast_cgi) the string:
{"h1":"newhash"}.
The expected behavior is that the URL should change.
Instead, nothing happens and Firebug complains that 'data' is "null"!.
Any help would be greatly appreciated!
Will.
When the following code enters "ajax_callback", it says that "data" is "null"!.
But the server is a c++ binary that is confirmed to return the JSON string {"h1":"newhash"}.
Anyone have an idea why JQuery seems unable to accept the JSON data when calling the ajax_callback?
I did have similar problem as you have mentioned when using $.POST().
There are two things if you are using jquery $.post method. You need to add an extra bracket before defined data type ("JSON") as shown below. I don't know why but it works, it will return data.
$.post('server.fcgi', {}, ajax_callback,{}, 'json');
The second thing is that you will need to parse JSON data using $.parseJSON(data) in side the callback function.
One more thing to make sure that the url to fetch JSON, the page document type should be defined as JSON in the header.
I have given an example below.
$.post("url/path/here/to/json", {}, function(data){
if(data){ // just in case the called program had a problem
var obj = $.parseJSON(data);
.... do everything else using the Obj->
}
},{},"json");
This will work.
However I recommend to you to use another Jquery function specially implemented for JSON, that is called
$.getJSON();
Here is the url for more information
And I am suggesting you to use the following method instead of the one described by you.
$(document).ready(function(){
$('.clickable').live('click', function() {
$.getJSON('server.fcgi', function(data){
window.location.hash = data.h1;
});
}
);
});
Make sure the server also returns the correct HTTP headers before the payload. E.g.:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: ...
...
{"h1":"bla"}
From your description, I could not quite make out if all it did was printf("{\"h1\":\"bla\"}"); or not.
To check the actual result, use a command line tool like HEAD, GET, wget, curl, or even nc. If you are not able to use one of those, you might get some clues from the Net panel in Firebug and the like.
Probably not the answer you want to hear, but I assume you're using jQuery 1.4.2? I noticed that this does work as expected in 1.3.2 so you might want to consider using that instead. :(