Get data from a JSON API into JS or jquery variable - php

I am trying to get some data from this api:
https://www.bitstamp.net/api/ticker/
into a jquery variable (to eventually display on a web page). It returns a JSON dictionary (more information here https://www.bitstamp.net/api/).
I tried for hours on end doing it all client side but realised that I cant because the api doesn't support cross-origin requests nor JSONP. So I then moved onto serverside code:
I have a php file 'test.php' with the following code:
<?php
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>
Then inside my html page I have the following code:
<script>
var last = JSON.parse(test.php)["last"]
document.getElementById('apidata').innerHTML=last;
</script>
<span id="apidata"></span>
But I don't know why it's not working! Can anyone please shed some light on this?
I thought jquery may be simpler but if anyone knows how to get this done with JS I'd like to hear that too. I also suspect that my php file is wrong.
EDIT: Here's a link to my php file http://www.buyabitcoin.co.uk/beta/test/test.php
and my html file http://www.buyabitcoin.co.uk/beta/test/test.html
username: 'test' password: 'test123'
EDIT: I have also tried
$.getJSON('test.php', function(response) {$("#apidata").html(response.value); });
in the html but to no avail. Can anyoneplease confirm if my php is outputting a JSON rather than a string?
Many thanks in advance

Modify your php file like so:
<?php
header('Content-type: application/json');
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>
The header() tells the requesting entity what sort of data it provides.
The url you request (https://www.bitstamp.net/api/ticker/) provides this json string:
{
"high": "161.00",
"last": "154.00",
"bid": "153.51",
"volume": "20295.34112055",
"low": "135.10",
"ask": "154.00"
}
Your html page has this JQuery:
$.getJSON('test.php', function(response) {
// access the response here
// e.g. get the volume
var volume = parseInt(response.volume);
// the numbers are returned as strings (numbers in quotes), thats why parseInt should be used
});

You can use jQuery ajax function to get JSON from the php page
like,
$.ajax({
dataType: "json",
url: 'test.php',
data: data,
success: function(data){
var last = data.last
$('#apidata').innerHTML=last;
}
});
Read more about jQuery.ajax http://api.jquery.com/jQuery.ajax/

You do not need to have jQuery just to download a JSON string and replace a div's content!
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
r = JSON.parse(xmlhttp.responseText);
document.getElementById("apidata").innerHTML=r;
}
}
xmlhttp.open("GET","/beta/test/test.php",true);
xmlhttp.send();
}
loadXMLDoc();

I managed to do what I want with the following code. This allows me to 'extract' a value from the JSON (in this example, the value for 'last') to use as a JS variable in a separate html file:
In my php file:
<?php
$ticker = file_get_contents('https://www.bitstamp.net/api/ticker/');
$obj = json_decode($ticker,true); // Split the JSON into arrays.
echo json_encode(array("myVariable" => $obj['last']));
?>
In my html file:
$.getJSON('test.php', function(data) {
var myVar = data.myVariable });
I hope this helps someone.

Related

XML Request not working properly

I have an XML request in my javascript file that is not transferring my variable correctly to PHP and I cannot figure out why. Could I possibly be missing a reference library of some sort?
Here is the function in question. I do know that the str variable has what I want inside. I am leaving old trial code in comments just in case you want to see what I have tried.
function PHP_Con(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
if(!xmlhttp)
{
alert("Fehler");
}
else
{
/*$.ajax({
type:"POST",
url:"dbConnection.php",
data:{"test" : "str"},
success:function()
{
alert("success");
}
});*/
alert(str);
xmlhttp.open("GET","dbConnection.php?test="+str,true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send();
/*var json_string= JSON.stringify(str); // convert it into a json string.
$.post('dbConnection.php' , {test : json_string },function(){
alert("success");
}); */
}
}
And here is my corresponding PHP code:
$test = intval($_POST['test']);
echo $test;
Also, I know about isset but I am trying to get the variable to show up. I'd rather get an error when it is not there, if that makes since...
Thank you very much. :) If there are easier ways to do this, I would be interested in that as well.
But as of now I feel like I do need to have a Form that calls a JS function, then my JS has variables retrieved from user input, and then those variables go to PHP so that they can be checked against my database... it all seems like the right order to me, but I admit to not having a very clear view of how JS variables show up in PHP and also of how PHP can respond in a way that is reflected through HTML code... for example I would like to "echo" back to a span in a p with the results of the comparison (user input against the database contents) and I have no idea of how that is done...
You are sending a GET request so you have to use $_GET instead of $_POST
$test = intval($_GET['test']);
echo $test;
a POST request would look like
xmlhttp.open("POST","dbConnection.php",true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send("test="+encodeURIComponent(str));

Data from javascript code insert to mysql database

Here I have a script which help me to get places from google places API. So now I want to store all this into mysql but how? I'm new to mysql and php, and how to store data that I get from google places to database?
What I need to do here? Can someone show me on my example...
How to combine php and javascript;
CODE: http://jsbin.com/AlEVaCa/1
So I need to store data which I got from google:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
I want to store all place.name,website ... etc. data to mydatabase. How to do that?
Is there any way to store this data?
Use AJAX to send data to PHP file.
Use jQuery $.post()-AJAX method to send data to php file
data = "name="+name+"&place="+website;
$.post('file_to_store.php', data, function(data) {
//Here you can get the output from PHP file which is (data) here
});
Pure javascript way
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
data = "name="+name+"&place="+website;
xmlhttp.open("POST","file_to_store.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In file_to_store.php receive all data from $_POST[] global array
if(isset($_POST)){
$name = $_POST['name'];
$website = $_POST['website'];
//Do same for all other variables
//Steps to insert Data into Database
//1. Connect to database
//2. Select Database
//3. Generate Database Insert Query
//4. Run mysql Query to insert
// Return appropriate return back to Javascript code - Success or Failure
}
Use serialize($data) then put it into database, use unserialize() after getting data from db.
Addition: this will store raw data, you'll probably need a parser also.
Addition 2: sorry I assumed that you got an array.
Alternative solution if you got non-array data:
you can use base64_encode($raw_data) to store and base64_decode($encoded_data) to use the encoded data coming from SQL.
Fundamentally, your JavaScript program, executing on the client side, does not have direct access to the SQL database on the host. You must use AJAX to issue requests to the host, and the host-side software must be programmed to handle them. Lots(!) of existing tutorials on this subject are already out there ... everywhere.

Pass JSON AJAX reply to PHP

I have a script which uses AJAX to connect to a PHP script which queries a database and returns some values. The code of which is below:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxphp.php?ID="+str,true);
xmlhttp.send();
}
</script>
<select id="users" name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<!-- PHP populates this dropdown box -->
</select>
<div id="txtHint"><b>Selected user info will be listed here.</b></div>
Right now the txtHint div will return anything the ajaxphp.php script prints. This isn't very flexible, however. What I want to do is create an array in ajaxphp.php and use json_encode() to pass the results back.
The problem I'm having is I don't know how to get the original script to grab the results so I can do useful things with them. Right now I can make it return a JSON array which will appear in the txtHint div but I've no idea how to get PHP to actually read that information so I can do something with it.
Try using jQuery Ajax...
$.ajax({
url : 'ajaxphp.php?ID='+str,
type: 'get',
dataType:'json',
success : function(data) {
console.log(data);
}
});
Data in success function parameter is your encoded result that you return from php.
echo json_encode($result);
Then you can access it with something like this from javascript.
data.result1
data.result2
data.result3....
Use $_GET method to See what ever the user send you in php see here:
http://php.net/manual/en/reserved.variables.request.php
Maybe the json_decode() php method is the solution of what you want.
http://www.php.net/manual/en/function.json-decode.php
This method takes a JSON encoded string (from the json_encode method for example) and converts it into a PHP variable... so you can use this variable like an object and simply access to its attributes.
Maybe this other post will help you : How to decode a JSON String with several objects in PHP?
Hope this helps ! Bye !

javascript not executed with ajax

How to make javascript code execute on php page which was previously loaded from an ajax call?
code samples:
ajax+function parseScript to force javascript to run on the ajax requested page
Senario: I am selecting a question from selectQuest.php and using ajax it request a page called showRecord.php.
The page showRecord.php will display a table which contain the information corresponding to the quetsion selected.It contains the javascript that do not run.The javascript return will allow me to update info in db when i click submit.
The code sample below is found in the showRecord.php.Finally, if the latter run the showRecord will make another ajax request for updateQuestion.php.
But the javascript is not running in showRecord.php
function show(fileTex,aTex,bTex,cTex,dTex,eTex,newQuestNumTex,textAreaTex,textQuesAnsTex)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var resp=xmlhttp.responseText;
document.getElementById("txtHint2").innerHTML=resp;
parseScript(resp);
// document.getElementById("txtHint").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("POST","updateQuestionAdmin.php?param="+fileTex+"&text_A="+aTex+"&text_B="+bTex+"&text_C="+cTex+"&text_D="+dTex+"&text_E="+eTex+"&text_ID="+newQuestNumTex+"&text_Ques="+textAreaTex+"&text_Ans="+textQuesAnsTex,true);
xmlhttp.send();
}
// this function create an Array that contains the JS code of every <script> tag in parameter
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {
var scripts = new Array(); // Array which will store the script's code
// Strip out tags
while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
var s = strcode.indexOf("<script");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</script", s);
var e_e = strcode.indexOf(">", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
}
</script>
As iyrag said, a Javascript framework would help. jQuery has a callback function that you can run when a script is successfully loaded and finished with ajax.
You'll want to execute some other stuff within that callback function, for instance :
$.ajax({
url: 'test.php',
success: function(data) {
$('#result').html(data); // Display script return on some div
someFunction(); // blabla
// Execute some other javascript here, you'll be abble to access the DOM of the test.html
// page because here you'lle be sure that test.html is loaded.showRecord.php should not contain javascript, which would rather be here
}
});
I also posted this because the tag features jQuery...

Sending Javascript Object to PHP via Ajax

I'm learning Ajax by failure and have hit a wall:
I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.
I have a function that is called when the user clicks the 'save' button. The function is as follows:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var url = "create_amenities.php";
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
My question is:
What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?
furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?
Thanks in advance.
If your array has more then 1 dimension or is an associative array you should use JSON.
Json turns a complete array structure into a string.
This string can easily send to your php application and turned back into a php array.
More information on json: http://www.json.org/js.html
var my_array = { ... };
var json = JSON.stringify( my_array );
In php you can decode the string with json_decode:
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json));
Loop over the array and append encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&' to the query string each time.
furthermore, should I try using JSON?
You could, but it would mean decoding JSON at the other end instead of letting normal form handling take care of it.
And if so, how could I send a JSON object via ajax?
There is no such thing as a JSON object. JSON takes the form of a string, and you can include strings in query strings (just remember to encodeURIComponent).
I found this question useful for Javascript enthusiasts.
Sending a javascript Object, be it js array or js object, you must stringify the setup before putting it to the server for decode & processing.
Stringifying a js object:
Based on your function:
case of Javascript Array object
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
case of Javascript Object object
let my_obj = {
name: "Daniel",
age: 23,
location: "Nigeria"
}
my_obj = JSON.stringify(my_obj);
Ones on point you can push this to the server, as per use case, u're working with AJAX GET method in sending your stringified object to the server.
Here is the full code:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById('message').innerHTML = this.responseText;
// if your returned response is in json, please, do ensure to parse the response before displaying
// like this JSON.parse(this.responseText)
}
}
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
var url = "create_amenities.php?my_json=" + my_array;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here are what i noticed out of your codes:
You don't need to call xmlhttp inside of xmlhttp object again, all you need is the this
I included the my_json parameter that holds the array object you are sending to the server.
Now, here in the server, you will need to catch the object and convert it to php readable object.
$my_json = $_GET['my_json'];
$my_json = json_decode($my_json);
Now, you can do whatever you wish it, because it has now become a full php array.
Example to pick the first array option:
$first = $my_json[0];
echo json_encode($first) // hahaha, you echoed it for AJAX to display
// i used to json_encode() to convert from php object to a js readable object
First off, yes, do not write ajax by hand. You are unlikely to produce something that truly works on all browsers.
The best approach to your actual problem would be to submit your array as cgi parameters.
If the checkboxes are in a form, you need to do very little - simply submit the form,
<form><input type=checkbox ...><input type=checkbox ...>
$.post("test.php", $("#testform").serialize());
See http://api.jquery.com/jQuery.post/ for more details on how to do that.
Your list will turn up as an array in PHP.
Or to augment your own example with something very simple, do this:
url = url + '?checkboxes=' + checkboxes.join(',');
Now just split it inside PHP and you've got it back!

Categories