• 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

    • I have not even heard of that game. will take a look
    • Chasys Photo 5.41.01 by Razvan Serea Chasys Photo is a suite of image editing applications including a layer-based image editor with adjustment layers, linked layers, timeline and frame-based animation, icon editing, image stacking and comprehensive plug-in support (Chasys Photo Editor), a fast image viewer (Chasys Photo Viewer) and a fast multi-threaded image file converter (Chasys Photo Converter) , with RAW image support in all components. It supports the native file formats of several competitors including Adobe Photoshop, Affinity Photo, ArtWeaver, Corel PhotoPaint, FireAlpaca, GIMP, Krita, Paint.NET, PaintShop Pro and Pixlr, and the whole suite is designed to make effective use of multi-core processors, touch-screens and pen-input devices. Designed under the mantra of “unique, flexible and powerful”, Chasys Photo takes a radically different approach to image editing with the aim of opening up new possibilities for those who dare to be different. Chasys Photo key features: Free-style layering with blending modes Adjustment layers with multiple adjustments per layer Linked layers (a.k.a Linked Smart Objects) Composite, Image List, Frame Animation and Object Animation image modes Animation, both frame-based and object-based (timeline animation) Animation Composer engine Image Stacking for noise reduction, super-resolution, etc. Tablet/Pen-input/Stylus support with pressure control Touch-screen support with gestures including pitch-to-zoom and multi-finger panning Support for the native formats of Adobe Photoshop, Affinity Photo, ArtWeaver, Corel PhotoPaint, FireAlpaca, GIMP, Krita, Paint.NET, PaintShop Pro and Pixlr Support for common formats such as JPEG, animated PNG, animated GIF, TIFF, PICT, WebP, HEIF, DDS, JPEG-2000, JPEG-XR, JPEG-XL, AVI video, etc. Support for the OpenRaster interchange file format and rare formats such as QOI, MNG/JNG and DPX Support for older formats such as PPM/PGM/PBM, PCX/DCX, PCD, TGA, COKE, etc. Comprehensive Camera RAW file support with live adjustment Extensive plug-in support with streamlined SDKs Support for Photoshop Filter Plug-ins (.8BF) Advanced printing and scanning engines PDF document generation Icon and cursor editing, import and export, including Vista-style and Mac-OS icons Screen Capture, including Video Screen Capture with multiple triggering modes Video capture from devices (e.g. TV/Video) Supports multi-core processors, High-DPI displays and Multiple Display setups Integrated File Browser, Bluetooth OBEX and in-built utilities (Calculator, Notepad) Shell integration with thumbnails and conflict detection Unlimited Undo/Redo and Asynchronous Auto-Save, with Just-in-time memory compression to save space Fully re-editable text with advanced styling and effects (TextArt) Full alpha channel through out the workflow with Alpha protection (a.k.a. transparency protection) Multiple language support with user-editable language files and translation assistant (Chasys Photo Language Studio) Anti-aliasing and super-sampling support in tools and paths* Smart-resizing (similar to seam-carving) Best-in-class post-edit heuristics anti-aliasing engine Physical measurement specification with display size detection via EDID Uses the latest CD5 specification with animation and multi-resolution Super-fast internal graphics engine (JpDRAW2) Full UNICODE support in all components Metadata save, restore and scale to imitate vector art Configurable Guides and Grids with Snap-to-Grid Smart-dither to custom palette Asynchronous preview rendering engine Pantone equivalent palettes for PMS 100 to 814-2x Automatic color naming ... and many more! Chasys Photo 5.41.01 changelog: New Features Layered images with multiple pages (Composite/Multi-page) Additional templates to support template-centric workflow New Layer Blend Mode: Inverse Luma Mask Horizon detection in Rotate Transform Cropping option when importing video Orientation options in QR Code Generator plug-in Solved angle ambiguities (CCW versus CW) Internal Improvements Improved graphics engine (JpDRAW2™ v26.05) Improved CD5 codec (v4.10, improved ACSC compression) Improved interpolation when downsizing images Improved motion detection in Video Capture Slightly lower memory usage (RAM is getting expensive!) File Support and Bug Fixes Improved PXZ file support (placeholders, blanks) [bug-fix] Memory leak in flt_JPEG.dll Download: Chasys Photo 5.41.01 | 46.1 MB (Freeware) View: Chasys Photo Home Page | Wikipedia Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • We don't need stars for the word, just use the word "CSAM"
    • If they want to do business in the UK then they can't ignore it. thats why Imgur pulled out of the UK
  • 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
      508
    2. 2
      PsYcHoKiLLa
      220
    3. 3
      ATLien_0
      92
    4. 4
      +Edouard
      90
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!