• 0

Jquery Json example


Question

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);
?>
[/CODE]

test.html

[CODE]
<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>
[/CODE]

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

tghanks

Link to comment
https://www.neowin.net/forum/topic/1121580-jquery-json-example/
Share on other sites

9 answers to this question

Recommended Posts

  • 0

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);
?>[/CODE]

html:

[CODE]<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>[/CODE]

  • 0

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>[/CODE]

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:

[CODE]
<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" />
[/CODE]

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,

  • 0

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>[/CODE]

  • Like 1
  • 0

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="https://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>
[/CODE]

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:

[CODE]
<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>[/CODE]

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

  • 0

by global i mean this

works



$.getJSON("test.php",
function(data){
userCoor = data;
document.write(data);
});
[/CODE]

[b]Dont work[/b]

[CODE]
$.getJSON("test.php",
function(data){
userCoor = data;

});

document.write(data);
[/CODE]

  • 0

by global i mean this

works



$.getJSON("test.php",
function(data){
userCoor = data;
document.write(data);
});
[/CODE]

[b]Dont work[/b]

[CODE]
$.getJSON("test.php",
function(data){
userCoor = data;

});

document.write(data);
[/CODE]

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

[CODE]document.write(data);[/CODE]

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

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

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • So is Russia, China, Iran, North Korea, just to mention a few. What's your point? Everyone is a threat from their enemies' perspective. I'd say that Israel is only a threat to their immediate enemies like Hamas, Hezbollah and the Iranian regime, not to anyone else.
    • The government is not the good guy either. You propose 99% of people require that the government overreach and govern their freedom of information and privacy, while ignoring the government is made up 100% of people, of which 99% are (as you described) brain dead. You can't have both. The reality is Signal is absolutely right and the government is doing what it has always done. Ignoring that we are their boss and grabbing all the power they possibly can to make sure we aren't. Your (societies) ###### parenting is not reason enough as to why I can't have a safe platform for my data/information. Thinking the government is helping is precisely what they are targeting psychologically to take suckers like you for a ride. "Think of the children" was, has, is, and will always be a mechanism of control. In the rare occasion it's actually essential the mass consensus has always been there and it doesn't become a debate.
    • Google Chrome 149.0.7827.103 (offline installer) by Razvan Serea The web browser is arguably the most important piece of software on your computer. You spend much of your time online inside a browser: when you search, chat, email, shop, bank, read the news, and watch videos online, you often do all this using a browser. Google Chrome is a browser that combines a minimal design with sophisticated technology to make the web faster, safer, and easier. Use one box for everything--type in the address bar and get suggestions for both search and Web pages. Thumbnails of your top sites let you access your favorite pages instantly with lightning speed from any new tab. Desktop shortcuts allow you to launch your favorite Web apps straight from your desktop. Chrome has many useful features built in, including automatic full-page translation and access to thousands of apps, extensions, and themes from the Chrome Web Store. Google Chrome is one of the best solutions for Internet browsing giving you high level of security, speed and great features. Important to know! The offline installer links do not include the automatic update feature. Download web installer: Google Chrome Web 32-bit | Google Chrome 64-bit | Freeware Download: Google Chrome Offline Installer 64-bit | Direct Link | 131.0 MB Download: Google Chrome Offline Installer 32-bit | Direct Link | 119.0 MB Download page: Google Chrome Portable Download: Chrome ARM64 | Direct Link View: Chrome Website | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Apple would rather delay Siri AI than open iOS to rival assistants in the EU by Pradeep Viswanathan At WWDC 2026, Apple today announced a revamped Siri AI experience for iOS and iPadOS users. However, this new Siri AI experience will not be available on iPhones and iPads in the European Union when iOS 27 and iPadOS 27 launch later this year. In a detailed press release, Apple blamed the Siri delay on the EU’s Digital Markets Act, highlighting that EU regulators did not accept its proposed solutions for bringing Siri AI to the region. Consequently, there is currently no timeline for Siri AI’s availability on iOS and iPadOS in the EU. Here is what EU users will be missing due to this delay: Siri AI, Apple’s next-generation assistant powered by Apple Intelligence A new dedicated Siri app for revisiting conversations Expanded Visual Intelligence features Integrated AI-assisted writing tools Siri mode in Camera on iOS Other system-level AI features Since the new Siri experience on watchOS 27 is dependent on an iOS 27 device, EU users will also miss out on Siri AI on watchOS 27. The most frustrating part is that even developers based in the EU will not be able to test or use the new Siri AI features for their apps on iOS 27, iPadOS 27, and watchOS 27. In its press release, Apple mentioned that making Siri AI available in the EU would require the company to give other AI assistants (like ChatGPT, Claude, and Gemini) broad access to private user data and the ability to control installed apps. Essentially, the EU wants competing AI systems to be able to read and send messages, make purchases, access files, and perform actions across apps. To address these concerns, Apple proposed an intermediary system called Trusted System Agent. This system would have allowed other virtual assistants to access the same features as Siri AI in a safer way. However, the European Commission rejected Apple's proposals, and it is currently unclear why. The good news is that Apple stated it will continue working with EU regulators to bring Siri AI to the region. For now, however, iPhone and iPad users in the EU will have to wait. If platform gatekeepers such as Apple and Google reserve deep operating system capabilities only for their own AI assistants, rival services such as ChatGPT, Claude, Perplexity, and others will be at a major disadvantage. Modern AI assistants are no longer simple chatbots. They require access to core OS-level capabilities such as reading on-screen context, interacting with installed apps, sending messages, creating calendar events, managing files, and completing user-approved actions across the device. If only Siri on iOS or Gemini on Android can access these capabilities, competing AI services will struggle to offer the same level of convenience, even if their underlying models are better. This is exactly what the European Union's DMA is trying to address. Apple and Google should be allowed to protect user privacy and security, but they should not be permitted to use those concerns as a blanket excuse to block rival AI assistants from getting fair access to core platform features. A secure permission-based framework could allow users to choose their preferred AI assistant without giving any company unrestricted access to personal data.
  • Recent Achievements

    • Very Popular
      Captain_Eric earned a badge
      Very Popular
    • One Month Later
      amusc earned a badge
      One Month Later
    • One Month Later
      DJC50PLUS earned a badge
      One Month Later
    • Week One Done
      DJC50PLUS earned a badge
      Week One Done
    • Proficient
      Eric Biran went up a rank
      Proficient
  • Popular Contributors

    1. 1
      +primortal
      509
    2. 2
      PsYcHoKiLLa
      222
    3. 3
      ATLien_0
      92
    4. 4
      +Edouard
      86
    5. 5
      Steven P.
      81
  • Tell a friend

    Love Neowin? Tell a friend!