I need to add some geo-marker to my map.
the markers are in my mysql table on altervista.org
but my JavaScript says [object Object] every time i try...
here my php code:
require('connect.php');
$query = "SELECT latit, longit FROM segnalazioni";
$result = mysql_query($query);
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
echo json_encode($rows);
it returns:
[{"latit":"12.34","longit":"12.34"},{"latit":"56.78","longit":"56.78"},...]
here my JavaScript:
function addMarker(mapobj) {
$.getJSON( "http://####.altervista.org/map.php", function( data ) {
var items = [];
$.each( data, function( key1 , val1 ) {
items.push( "<li id='" + key1 + "'>" + val1 + "</li>" );
//next todo:
//mapobj.marker([latit, longit]).addTo(map).bindPopup("hi");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
and on the end of my [body] i can see only:
[object Object]
[object Object]
[object Object]
...
According to jquery.each the parameters are
indexInArray , value and NOT key, value
So the code is:
$(function () {
var data = [{"latit": "12.34", "longit": "12.34"}, {"latit": "56.78", "longit": "56.78"}];
var items = [];
$.each(data, function(indexInArray , value) {
items.push( "<li id='" + indexInArray + "'>latit: " + value.latit + ' longit:' + value.longit + ' OR '+ JSON.stringify(value) + "</li>" );
//next todo:
//mapobj.marker([latit, longit]).addTo(map).bindPopup("hi");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
Use this
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
I would also encourage to use header before sending JSON stream. It is always good to tell the content type sent in HTTP response. Use
header('Content-Type: application/json');
Before using
echo json_encode($rows);
Related
How to pass my php array to this jquery code ?
i have tried json_encoding but couldnt use it in my jquery function.
my json string looks like this:
{"1":{"id":"1","league":"england","team1":"Arsenal","team2":"Chelsea"},"2":{"id":"2","league":"spain","team1":"Deportivo","team2":"Real Madrid"}}
JS:
<script type="text/javascript">
$(document).ready(function(){
var shownIds = new Array();
setInterval(function(){
$.get('livescore_process.php', function(data){
for(i = 0; i < data.length; i++){
if($.inArray(data[i]["id"], shownIds) == -1){
if(data[i]["league"]=="england"){
$("#eng").append("id: " + data[i]["team1"] + " [ "+data[i]["team1"]+ " - "+data[i]["team1"]+" ]"+ data[i]["team2"] +"<br />");
}
shownIds.push(data[i]["id"]);
}
}
});
}, 3000);
});
</script>
try $.getJSON instead of $.get and use php json_encode:
$.getJSON('livescore_process.php', function(data){...
however the response data is not an array but a json object, so to handle it you can try:
$.each(data, function (index, item) {
if (item.hasOwnProperty('id')) {
if (item.league == "england") {
$("#eng").append("id: " + item.team1 + " [ " + item.team1 + " - " + item.team1 + " ]" + item.team2 + "<br />");
}
shownIds.push(item.id);
}
});
jsfiddle
I have a Jquery Function that basically retrieves a list of users from the data base and inserts the information into divs. The problem is that im getting double reults, this is my first time retrieving from the database, Ive only ever sent to the database.. Any Help will be Greatly appreciated.
Thanks :)
Heres the Jquery Code:
$(function () {
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var mobile = row[2];
var address = row[3];
var email = row[4];
$.each(rows, function() {
$('#contain').append('<div id="name">' + '<span>' + name + '</span>' + '</div>' + '<div id="id">' + id + '</div>' + '<div id="mobile">' + mobile + '</div>' + '<div id="address">' + address + '</div>' + '<div id="email">' + email + '</div>');
});
}
}
});
});
and the PHP:
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
I think the problem is here:
$.each(rows, function (){
$('#contain').append('<div id="name">'+'<span>'+name+'</span>'+'</div>'+'<div id="id">'+id+'</div>'+'<div id="mobile">'+mobile+'</div>'+'<div id="address">'+address+'</div>'+'<div id="email">'+email+'</div>');
});
you should do just
$('#contain').append('<div id="name"><span>'+name+'</span></div><div id="id">'+id+'</div><div id="mobile">'+mobile+'</div><div id="address">'+address+'</div><div id="email">'+email+'</div>');
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 have the following code which pass data formatted as JSON to PHP through Ajax, but the PHP code doesn't print out the result.
var array_str_idnum = [];
for (var i=0;i<2;i++) {
array_str_idnum[i] = [];
}
$('#movetoset').click(function() {
if ($('#selectsett').val() === 'General') {
}
for(j=0;j< (array_str_idnum[0]).length;j++) {
if((document.getElementById('check' + array_str_idnum[0][j]).checked) && (array_str_idnum[1][j] != "moved")) {
document.getElementById('imagediv' + array_str_idnum[0][j]).style.display = 'none';
array_str_idnum[1][j] = "moved";
index = ((array_str_idnum[0]).length - 1 - j) + '';
var str = $("#complicated").serialize() + "&myindex=" + encodeURIComponent(index) ;
var desc_str = document.getElementById('textarea' + array_str_idnum[0][j]).value;
str = str + "&mydescription=" + encodeURIComponent(desc_str);
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg) {
$("#formstatus").ajaxComplete(function(){$(this).fadeIn("slow").html(msg + '<br /><br />')});
$("#formstatus").append(msg);
}
});
}
}
mydata = JSON.stringify(array_str_idnum);
$.ajax({
type: 'post',
cache: false,
url: 'parser.php',
data: {myJson: mydata},
success: function(msg) {
$("#formstatus").ajaxComplete(function() { $(this).fadeIn("slow").html(msg) });
}
});
});
Here is my PHP code:
$decoded = json_decode($_POST['myJson'],true);
// do something with data here
echo "decoded = $decoded[1][0]";
What's wrong with the code?
I think you want to fix your PHP code like others suggested, like so:
<?php
if ( !empty($_POST['myJson']) && strlen($_POST['myJson']) > 0 )
{
$decoded = json_decode( $_POST['myJson'], true );
// Echo out the JSON onject as a JavaScript variable.
echo "decoded = {$decoded[1][0]};";
}
else
{
// Echo out the JSON onject as a JavaScript variable.
echo "decoded = null;";
}
?>
Here is your JavaScript code with some minor suggestions:
<script type="text/javascript">
$( document ).ready(function()
{
var array_str_idnum = [];
// Init the array with two elemsnts that contain empty literal arrays.
for ( var i = 0; i < 2; i++ )
{
array_str_idnum[ i ] = [];
}
$( "#movetoset" ).click(function()
{
var $checkbox, str, desc_str, elementSuffix;
// I believe the code in here was removed for privacy reasons.
// I also believe it populats 'array_str_idnum' with some values of some kind.
if ( $("#selectsett").val() === "General" )
{
// ...
}
for ( var i = 0; i < (array_str_idnum[0]).length; i++ )
{
elementSuffix = array_str_idnum[ 0 ][ i ];
// Grab the checkbox.
$checkbox = $( "#check" + elementSuffix );
if ( $checkbox.checked && (array_str_idnum[1][i] != "moved") )
{
// Hide the image.
$( "#imagediv" + elementSuffix ).css({ "display": "none" });
// Indicate that this one is now moved, so do NOT process it again.
array_str_idnum[ 1 ][ i ] = "moved";
index = ( (array_str_idnum[0]).length - 1 - i ) + '';
// Setting str here will reinitialize it
str = $( "#complicated" ).serialize() + "&myindex=" + encodeURIComponent( index );
desc_str = $( "#textarea" + elementSuffix ).value;
str = str + "&mydescription=" + encodeURIComponent( desc_str );
// Bad idea to put ajax call in a loop.
$.ajax({
"type": "POST",
"url": "addtoset.php",
"data": str,
"cache": false,
"success": function( msg )
{
$( "#formstatus" ).ajaxComplete(function()
{
$( this ).fadeIn( "slow" ).html( msg + "<br /><br />" );
});
$( "#formstatus" ).append( msg );
}
});
}
}
mydata = JSON.stringify( array_str_idnum );
$.ajax({
"type": "POST",
"cache": false,
"url": "parser.php",
"data": { myJson: mydata },
"success": function( msg )
{
$( "#formstatus" ).ajaxComplete(function()
{
$( this ).fadeIn( "slow" ).html( msg )
});
}
});
});
});
</script>
Maybe your only problem is the echo statement. You'll have to change that to
echo "decoded = ".$decoded[1][0];
or
echo "decoded = {$decoded[1][0]}"; //
This is because PHP only notices "normal" variables in double-quoted strings. For array elements (or object properties) you'll have to use curly braces around the variable or use string concatenation.
This code works perfectly, but when I will put the final HTML, only appears the values, but the HTML not. What is happening??
$('[role=query-username]').live( 'click', function() {
var output = "<table>";
$.post(
'/action/jsonUserInformation.php',
'username=' + $('#username').val(),
function(data) {
$('#user_results').html('');
var data_json = $.parseJSON( data );
$.each( data_json, function() {
$.each( this, function(i, v)
{
output = output + "<tr><td>" + i + "</td><td>" + v + "</td></tr>";
});
output = output + "</table>";
});
$('#user_results').html( output );
});
});
Result Output is:
code37username_code41account_passwordfb8465e62c8b2bd01d1d14965748b3e4account_status2account_type1creationdate2008-10-23mail_code39confirmedbb022e5a2419271daa2764f9cad5500crecoveryenabledreferrertimezonepreferred_currencycomission_plan1basemoney0privileges5paywaypersonal_info37last_update2008-10-23 00:00:00nameslastnamessexaddressphonemobilezipcitystatecountryidbusinessnameprofessionbirthdateaccount37usernamecjimenezhkemailyoyo#cjimenezhk.com
I'm not sure what you mean by "put the final HTML", but you should definitely move the
output = output + "</table>";
outside of your outer each loop.
Move it just before $('#user_results').html( output );