I am trying to map traceroutes to google maps.
I have an array in php with traceroute data as
$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng
I used json_encode($c, JSON_FORCE_OBJECT) and saved the file
Now, how do I access this using javascript, by directly equating it to new JS object?
earlier I used to have a data format like this on harddrive
var data12 = {
"route":[
{
"ip": "some ip",
"longitude": "some lng",
"latitude": "some lat",
.....
and in my javascript it was used as
data=data12.route;
and then simply acces the members as data[1].latitude
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
For parsing JSON, simply do
var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
You can now access everything easily:
alert ( obj.name );
Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.
Edit: To get data from the server side to the client side, there are two possibilities:
1.) Use an AJAX request (quite simple with jQuery):
$.ajax ( {
url: "yourscript.php",
dataType: "json",
success: function ( data, textStatus, jqXHR ) {
// process the data, you only need the "data" argument
// jQuery will automatically parse the JSON for you!
}
} );
2.) Write the JSON object into the Javascript source code at page generation:
<?php
$json = json_encode ( $your_array, JSON_FORCE_OBJECT );
?>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
//]]>
</script>
I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.
< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);
I could get the JSON array by using PHP's json_encode() from backend like this example:
<!doctype html>
<html>
<script type="text/javascript">
var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
console.log(json[1]);
console.log(json.abc);
</script>
</html>
No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.
no need for jquery, just:
var array= <?php echo json_encode($array); ?>;
console.log(array->foo);
we have to display the json encode format in javascript , by using below one:
var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);
This function works for you I guess:
function json_encode4js($data) {
$result = '{';
$separator = '';
$count = 0;
foreach ($data as $key => $val) {
$result .= $separator . $key . ':';
if (is_array($val)){
$result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
continue;
}
if (is_int($val)) {
$result .= $val;
} elseif (is_string($val)) {
$result .= '"' . str_replace('"', '\"', $val) . '"';
} elseif (is_bool($val)) {
$result .= $val ? 'true' : 'false';
} elseif (is_null($val)) {
$result .= 'null';
} else {
$result .= $val;
}
$separator = ', ';
$count++;
}
$result .= '}';
return $result;
}
$a = array(
"string"=>'text',
'jsobj'=>[
"string"=>'text',
'jsobj'=>'text2',
"bool"=>false
],
"bool"=>false);
var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}"
var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
HTML
<select name="sub" id="subcat" class="form-control" required="required">
</select>
PHP
$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()
JS
$("#maincat").change(function(){
var status = this.value;
$.ajax({
type: 'POST',
url: 'home/subcat/'+status,
success: function(data){
var option = '';
var obj = JSON.parse(data);
if(obj.length > 0){
for (var i=0;i<obj.length;i++){
option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';
}
//Now populate the second dropdown i.e "Sub Category"
$('#subcat').children("option").remove();
$('#subcat').append(option);
}else{
option = '<option value="">No Sub Category Found</option>';
$('#subcat').children("option").remove();
$('#subcat').append(option);
}
},
error: function(){
alert('failure');
}
});
Related
I'm screen scraping a site with a php script which creates an array in the end that I want to send back to the javascript caller function. In the code below I've tried to print it out with 'print_r', which doesn't give me any results at all (?). If I echo out on of the elements (e.g $addresses[1]) the element is shown.
So, why ain't I getting anything out from the php function, and what is really the best way to send back the array to the calling js function?
Thanks a lot in advance!
js:
$.post(
"./php/foo.php",
{
zipcode: zipcode
},
function(data) {
$('#showData').html(data);
}
);
php:
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
array_push($addresses, $address);
}
print_r($addresses);
You can use JSON to return an array back to the client-side, it can be send by AJAX same what you are doing on your existing code.
Use json_encode() of PHP, this function will make your PHP array into a JSON string and you can use it to send back to your client by using AJAX
In your PHP code(Just for demonstration how it works)
json.php
<?php
$addresses['hello'] = NULL;
$addresses['hello2'] = NULL;
if($_POST['zipcode'] == '123'){ //your POST data is recieved in a common way
//sample array
$addresses['hello'] = 'hi';
$addresses['hello2'] = 'konnichiwa';
}
else{
$addresses['hello'] = 'who are you?';
$addresses['hello2'] = 'dare desu ka';
}
echo json_encode($addresses);
?>
then in your client script(much better you use the Jquery's long AJAX way)
$.ajax({
url:'http://localhost/json.php',
type:'post',
dataType:'json',
data:{
zipcode: '123' //sample data to send to the server
},
//the variable 'data' contains the response that can be manipulated in JS
success:function(data) {
console.log(data); //it would show the JSON array in your console
alert(data.hello); //will alert "hi"
}
});
references
http://api.jquery.com/jQuery.ajax/
http://php.net/manual/en/function.json-encode.php
http://json.org/
js should be
$.ajax({
url:'your url',
type:'post',
dataType:'json',
success:function(data) {
console.log(JSON.stringify(data));
}
});
server
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
$arr_res[] =$address;
}
header('content-type:application/json');
echo json_encode($arr_res);
I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!
So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);
I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )
Hi searched through the questions here, but couldn't find anything. I'm new at writing PHP and jQuery, so bear with me.
What I'm trying to do is send an ajax request using jQuery to my script which runs a mysql query on data from my database and serializes it into the JSON format using php's json_encode. The response is then parsed with the available json2.js script. All of this works fine, but I'd also like to return more data other than just JSON from this script.
mainly, i'd like to also echo the following line before the json_encode:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
however, my jQuery is evaluating the entire response during the ajax success, making the json.parse function fail due to the script's return being in an invalid format.
success: function(data) {
//retrieve comments to display on page by parsing them to a JSON object
var obj = JSON.parse(data);
//loop through all items in the JSON array
for (var x = 0; x < obj.length; x++) {
//Create a container for the new element
var div = $("<div>").addClass("bubble").appendTo("#comments");
//Add author name and comment to container
var blockquote = $("<blockquote>").appendTo(div);
$("<p>").text(obj[x].comment).appendTo(blockquote);
var cite = $("<cite>").appendTo(div);
$("<strong>").text(obj[x].name).appendTo(cite);
$("<i>").text(obj[x].datetime).appendTo(cite);
}
$("#db").attr("value", '' + initialComments + '');
}
does anyone know how i can return the html line as well as the json_encode to use this script for more than just json population?
thankyou, this website has been wonderful in answering my noob questions.
my php:`
for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));
}
//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
$response = json_encode($comments);
echo $response;`
Don't echo the line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
); and send that back ( via json_encode ) instead.
Also, you don't need json2.js, jQuery has an excellent JSON parser.
you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );
Changed to match your newly introduced iteration.
for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array(
"name" => stripslashes($row["name"]),
"comment" => stripslashes($row["comment"]),
"datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
);
}
$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
echo json_encode(array( 'comments' => $comments, 'html' => $html ));
then, in your javascript, you have
function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}
As said above just put all the data you want to get back in an array and encode that.
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as json.
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($data) {
var html = $data.html;
var foo = $data.foo;
var bar = $data.bar;
// Do whatever.
}
});
EDIT Pretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.
For example:
PHP:
<?php
// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);
echo json_encode($comments);
?>
jQuery:
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($comments) {
// Here's your html string.
var html = $comments[0];
// Make sure to start at 1 or you're going to get your HTML string twice.
// You could also skip storing it above, start at 0, and add a bit to the for loop:
// if x == 0 then print the HTML string else print comments.
for (var x = 1; x < $comments.length; x++) {
// Do what you want with your comments.
// Accessed like so:
var name = $comments[x].name;
var comment = $comments[x].comment;
var datetime = $comments[x].datetime;
}
}
});
You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq supports querying nested objects and performing joins. For example:
var results = jLinq.from(data.users)
.join(data.locations, //the source array
"location", //the alias to use (when joined)
"locationId", // the location id for the user
"id" // the id for the location
)
.select(function(r) {
return {
fullname:r.first + " " + r.last,
city:r.location.city,
state:r.location.state
};
});
I create a huge JSON-Object and save it in my database. But when I load the "string" and echo it in PHP, I can't access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with "echo json_encode($arr);" it works fine, but I need to save the Object for caching).
{"247":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]},{"248":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]}}
just an excerpt
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn't work.
Update 1: forget to tell that I'm using a TEXT-Field with UTF8_general_ci collation
Update 2: Maybe a little bit more code:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
this loads the script and should alert "This is a question"
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
I'd suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data);
}, "text");
return false;
});
}
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you've done that, if you still can't spot the problem, try this code:
var data1, data2;
function start() {
$(".start").click(function () {
$.post("load_script.php", {src: "db" }, function(data){
data1 = data;
}, "text");
$.post("load_script.php", {src: "echo" }, function(data){
data2 = data;
}, "text");
if (data1 == data2) {
alert("data1 == data2");
}
else {
var len = data1.length < data2.length ? data1.length : data2.length;
for(i=0; i<len; ++i) {
if (data1.charAt(i) != data2.charAt(i)) {
alert("data1 first differs from data2 at character index " + i);
break;
}
}
}
return false;
});
}
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
<?php
if ($_POST['src'] == 'db')) {
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
}
else {
$output = '{"247":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]},{"248":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]}}';
}
echo $output;
?>
Hope that helps!
I got this to work in a slightly different manner. I've tried to illustrate how this was done.
In Plain English:
use urldecode()
In Commented Code Fragments
$json = $this->getContent($url); // CURL function to get JSON from service
$result = json_decode($json, true); // $result is now an associative array
...
$insert = "INSERT INTO mytable (url, data) ";
$insert .= "VALUES('" . $url . "', '" . urlencode(json_encode($result)) . "') ";
$insert .= "ON DUPLICATE KEY UPDATE url=url";
...
/*
** Figure out when you want to check cache, and then it goes something like this
*/
$sqlSelect = "SELECT * FROM mytable WHERE url='" . $url . "' LIMIT 0,1";
$result = mysql_query($sqlSelect) or die(mysql_error());
$num = mysql_numrows($result);
if ($num>0) {
$row = mysql_fetch_assoc($result);
$cache = json_decode(urldecode($row['data']), true);
}
Hope this is helpful
Maybe you use varchar field and your string just doesn't fit in 255 chars?