PHP to JSON on client side - php

I'm using Rob Monies 'Jquery Week Calendar' to build a calendar application.
I have a MSSQL DB a with table named 'dates' and the following fields:
id
start
end
title
I would like to query this DB in PHP and then pass the results to Javascript, Javascript will then render the events in the browser.
The Javascript needs to receive the event details in JSON format as per the following example:
{"id":1,"start": 2010-10-09T13:00:00,"end":2010-10-09T14:00:00,"title":"Lunch with Mike"},
{"id":2,"start": 2010-10-10T13:00:00,"end": 2010-10-10T14:00:00, "title":"Dev Meeting"}
So far, to keep things simple I've just returned one row from the DB at a time, however - I will need the application to be able to render multiple events, as stored in the database.
I've tried using json_encode() to put the values into a var and pass them to a Javascript var called DB_events - if I return the DB_events in an alert box on the client side I see the following;
{"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"}
which looks ok, but when I do this in my code:
events : [DB_events]
It doesn't work :(
If I take PHP out of the equation, and just do the following on the client side:
var DB_events = {"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"};
and return DB_events in an alert box, I get:
[object] [Object]
But when I do this:
events : [DB_events]
it works!
Back to PHP …
If I put the SQL result into PHP vars as follows:
$id = id;
$start = start;
$end = end;
$title = title;
and pass those vars to the following JS vars:
JS_id
JS_start
JS_end
JS_title
and do this on the client side:
var DB_events = {"id":JS_id, "start":JS_start, "end":JS_end,"title":JS_title};
events : [DB_events]
that also works.
As you can probably tell - I'm new to this and probably missing something very basic.
Any help, advice or information would be very much appreciated :)
Many Thanks
Tim

when you get a string representation of your object it means that you've exported it as a string not as an object.
when you get [object] [Object] it means that it is now an object, which is right!
You can do this with JSONP if you get JSON from an URL:
// send the request via <script> tag
var src = "..."; // url of the JSON output
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
Or parse it as a string with JSON parser:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var DB_events = JSON.parse( ...JSON output as a string... );
Or by directly passing it from PHP with an inline <script> block in your page:
echo "<script>";
echo "var DB_events = " . json_encode( ... ) . ";";
echo "</script>";
​

Did you use jsocn decode
http://php.net/manual/en/function.json-decode.php
You can split the result and make it differenct variables like start ,end , events etc
http://php.net/manual/en/function.explode.php

Related

Pass array into GET URL using jQuery

I am trying to pass an array into a GET URL BUT it is coming as add_cart?ids=1,2,3,4,5 as opposed to sending it properly.
This is my jquery code where it adds the array to the URL and directs the user to the next page:
$(document).on("click", 'button.btn_checkout', function(){
var cart = <?php echo json_encode($carts); ?>;
window.location.href = "addcart.php?cart=" + cart;
});
And then on the addcart.php page I am unable to get these values.
Ideally on this page, I want the values in the form 1,2,3,4,5
This is the code for that page:
<?php
session_start();
$cart = isset($_GET['cart']) ? $_GET['cart'] : "";
$cart = explode(",", $_GET['cart']);
for($i = 0; $i<$cart.size; $i++){
echo $cart[$i];
}
?>
Where am I going wrong?
You are using the jQuery GET request a little wrongly. You will use
window.location.href
when you are trying to change the location of your current webpage.
Try this instead:
$(document).on("click", 'button.btn_checkout', function(){
var result = <?php echo json_encode($carts); ?>;
$.get( "addcart.php", { cart: result } );
});
I'm assuming by ARRAY you mean to include the braces {}?
If so, your problem is actually the php part. json_encode is creating a proper json object. Which then is being added onto the url AS the object itself, and NOT a string. You actually want it to be a string.
this line: var cart = <?php echo json_encode($carts); ?>; is the main issue.
convert it to something like: var cart = "<?php echo json_encode($carts); ?>";
Use $.param() function to convert params to get query string.
You are directly initialising Json to param but not converting to query string.
Above function will convert Json to query string
Try to use the javascript function JSON.stringify() to convert to json.
Note: Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.

How to use outputs of php that is called by ajax in our file

I have an app that sends latitude, longitude values to my postgresql database. And i want to plot the updated points accordingly on my OpenLayers map using jquery,ajax. But here is where i am stuck at: When I click the button, the php file with database connection and saving the last entry of the table in an array is happening.
But when i try using the outputs in markers, nothing is happening.
How to use the output values of the php in my function?
Here is the code that i am trying to use.
php file:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
My page code is :
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
and the alert i am getting when clicking update button is
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
Is the way i am trying to access the values of query output correct? Please help.
Sorry if this is a dumb question. I am new to jquery.
When your php script sends a string like:
'var javascript_lat1 = ["output of the query"];'
back to your code, that does not mean that your code has a variable called javascript_lat1 in it.
Your php script is sending strings back to your javascript code from which you must extract the information that you want to use in your code. It is up to your javascript code to know what format the strings are in. But since you wrote the php script you can send the strings back in any format you want. Then your javascript code can dissect the strings with regexes, split(), etc. to extract the parts of the strings that you want to use in your code. A very simple format that your php code could use is:
"output of query 1, output of query 2"
Then you can split() on the comma to separate the two pieces of data e.g.:
var pieces = data.split(', ');
Then you can use pieces[0] and pieces[1] in your javascript code.
Another option is to send a request to your php script using the $.getJSON() function. If you do that, your php script should send back a json formatted string, e.g.:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
Then the $.getJSON() function will automatically convert the string into a javascript object and pass the js object to your callback function. Inside the callback function you can access the data using:
some_func(data.lat1, data.long1);

calling php and javascript functions with one button

This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

Getting JSON data from Javascript

I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.

Categories