Jump to content



Photo

Jquery Json example


  • Please log in to reply
9 replies to this topic

#1 Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 22 November 2012 - 18:08

hi guys i'm trying to understand JSON i have this please tell me if i'm wrong

test.php
<?php
$arr = array('foo','bar','baz','blong');

echo json_encode($arr);
?>

test.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$.ajax({
url: [i]url[/i],
dataType: 'json',
data: [i]data[/i],
success: [i]callback[/i]

});


echo $arr;  //I KNOW THIS IS WRONG
</script>

so my question is how do i get the array in the test.html

tghanks


#2 +Seahorsepip

Seahorsepip

    http://seapip.com

  • Tech Issues Solved: 28
  • Joined: 23-January 11
  • Location: Netherlands
  • OS: Windows 8.1 Pro
  • Phone: Nexus 5

Posted 22 November 2012 - 20:09

I guess the following thing is where you're looking for: http://mrarrowhead.c...g_variables.php

I suggest the following code:
php:
<?php
$arr = array('foo','bar','baz','blong');
session_start(); // start up your PHP session!
$_SESSION['arr'] = $arr

echo json_encode($arr);
?>
html:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$.ajax({
url: [i]url[/i],
dataType: 'json',
data: [i]data[/i],
success: [i]callback[/i]

});

//Yes this is php inside js LOLZ
$_SESSION['arr'] = $arr
echo $arr;
session_destroy(); //If you want to remove the global variable again

</script>


#3 OP Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 22 November 2012 - 20:26

thanks but i cant echo PHP in a html script

#4 +Seahorsepip

Seahorsepip

    http://seapip.com

  • Tech Issues Solved: 28
  • Joined: 23-January 11
  • Location: Netherlands
  • OS: Windows 8.1 Pro
  • Phone: Nexus 5

Posted 22 November 2012 - 20:34

thanks but i cant echo PHP in a html script

you need to make the html into a php like this:
php html:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$.ajax({
url: [i]url[/i],
dataType: 'json',
data: [i]data[/i],
success: [i]callback[/i]

});
<?php
$_SESSION['arr'] = $arr
echo $arr;
session_destroy(); //If you want to remove the global variable again
?>

</script>

php is a server side code and js is a client side code so you can just put php inside js or wherever you want since the php has already been parsed into text when the js code starts ;) so if you test this php file you shouldn't see the php but the php results when you check the page source from within the browser.

You can also open and close php tags wherever you want so you can use php all over the page to add support for IE.

As example, I use the following code to change "placeholder" into "value" for my textboxes when IE is used:
<input class="input" type="text" name="name" <?php if(preg_match('/(?i)msie [6-9]/',$_SERVER['HTTP_USER_AGENT'])) { echo 'value'; } else { echo 'placeholder'; }?>="Name" />

Keep in mind that client side js code can never ever acces php code since the php code has already been parsed so js is never able to use a php variable without using php in the page to put the variable value into the js,

#5 ZakO

ZakO

    Neowinian

  • Tech Issues Solved: 2
  • Joined: 21-September 07
  • Location: Finland

Posted 22 November 2012 - 20:37

Are you trying to access the array/json returned by test.php inside test.html?

If so, the PHP part is correct, but you need to access the json returned inside the callback:


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$.ajax({
  url: "test.php",
  dataType: 'json',
  success: function(json) {
    // json now holds the array ["foo", "bar", "baz", "blong"]
    console.log(json);
  }
});

</script>


#6 OP Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 22 November 2012 - 20:41

ok maybe i did not explane correctly here is my full script
<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
   <title>Google Maps - Moving point along a path</title>
   <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body onunload="GUnload()">
   <div id="map_canvas" style="width: 1000px; height: 800px;"></div>
   <script type="text/javascript">
	  var map;
	  var mapOptions = { center:
		 <?php
	  $result = mysql_query("SELECT * FROM location ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result)){
echo 'new google.maps.LatLng('.$row['latitude'].', '.$row['longitude'].'),';
}
?>
		 zoom: 14,
		  mapTypeId: google.maps.MapTypeId.ROADMAP };
	  function initialize() {
	    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var userCoor = [
  <?php
	  $result = mysql_query("SELECT * FROM location ORDER BY id DESC");
while($row = mysql_fetch_array($result)){
echo '["TIME:-'.$row['TRUEtime'].'<br>SPEED:-'.$row['speed'].'mph<br />DISTANCE:-'.$row['distance'].'km",'.$row['latitude'].', '.$row['longitude'].'],';
}
	  ?>
			    ];
var userCoorPath = [
	  <?php
	  $result = mysql_query("SELECT * FROM location ORDER BY id ");
while($row = mysql_fetch_array($result)){
echo 'new google.maps.LatLng('.$row['latitude'].', '.$row['longitude'].'),';
}
	  ?>
						 
				    ]
var userCoordinate = new google.maps.Polyline({
path: userCoorPath,
strokeColor: "blue",
strokeOpacity: 1,
strokeWeight: 4
});
userCoordinate.setMap(map);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var image = new google.maps.MarkerImage('green.png',
	  // This marker is 20 pixels wide by 32 pixels tall.
	  new google.maps.Size(20, 20),
	  // The origin for this image is 0,0.
	  new google.maps.Point(0,0),
	  // The anchor for this image is the base of the flagpole at 0,32.
	  new google.maps.Point(10, 10));

	
for (i = 0; i < userCoor.length; i++) { 
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(userCoor[i][1], userCoor[i][2]),
    map: map,
    icon   : image
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
	  infowindow.setContent(userCoor[i][0]);
	  infowindow.open(map, marker);
    }
  })(marker, i));
}
	 }
	  google.maps.event.addDomListener(window, 'load', initialize);

   </script>
</body>
</html>

i would like the map to refresh every 20 seconds but not the whole page so i need to remove the PHP and put them in a PHP file then just call it every 20 seconds

Are you trying to access the array/json returned by test.php inside test.html?

If so, the PHP part is correct, but you need to access the json returned inside the callback:


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script language="javascript">

$.ajax({
  url: "test.php",
  dataType: 'json',
  success: function(json) {
	// json now holds the array ["foo", "bar", "baz", "blong"]
	console.log(json);
  }
});

</script>

yes that is it now i have the array how do i get it global

#7 OP Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 22 November 2012 - 20:47

by global i mean this
works

$.getJSON("test.php",
		function(data){
		userCoor = data;
	  document.write(data);
		});
Dont work
$.getJSON("test.php",
		function(data){
		userCoor = data;
	
		});

document.write(data);


#8 ZakO

ZakO

    Neowinian

  • Tech Issues Solved: 2
  • Joined: 21-September 07
  • Location: Finland

Posted 22 November 2012 - 21:04

by global i mean this
works


$.getJSON("test.php",
		function(data){
		userCoor = data;
	  document.write(data);
		});
Dont work
$.getJSON("test.php",
		function(data){
		userCoor = data;
	
		});

document.write(data);


You can't. $.ajax/$.getJSON calls are asynchronous (that's why they have a callback), the global scope line:

document.write(data);

will be executed before the callback is completed, you need to do the actual work in the callback.

$.getJSON("test.php",
  function(data){
	userCoor = data;
	// Do something with the data, like pass it off to another function which modifies the DOM.
});


#9 OP Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 22 November 2012 - 21:07

Read post #6 am i even heading in the right direction?


"i would like the map to refresh every 20 seconds but not the whole page so i need to remove the PHP and put them in a PHP file then just call it every 20 seconds"

#10 OP Craig Hopson

Craig Hopson

    Neowinian

  • Joined: 17-November 12
  • Location: London
  • OS: Windows 8 :-(

Posted 24 November 2012 - 12:38

anyone?