How to get json object using php and mysql array - php

I am trying to get json data from php and when by using jquery json it show me undefined object. I don't know where is problem in my code. can any one help ?
Here is json code :
$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
$("#subcat").html("");
$.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
$.each(data, function(index, array) {
$("#subcat").append("<input type='button' class='subcat' id='" + data.subcat_id + "' value='"
+ data.subcat_name + "'></p>");
});
});
});
});
and Here is PHP Code
$select_subcat = mysql_query("SELECT * FROM wp_leadsubcat WHERE cat_id=" . $_GET['catid']);
$rows = array();
while ($result2 = mysql_fetch_assoc($select_subcat)) {
$rows[] = $result2;
}
echo json_encode($rows);
Please check screenshot here : http://imageshack.us/photo/my-images/560/screenshotqvl.png/

read documentation about jquery each.
in short jQuery.each( collection, callback(indexInArray, valueOfElement) )
index means index and valueOfElement means the current element from the collection. In your case row.
here is a fix.
$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
$("#subcat").html("");
$.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
$.each(data, function(index, row) {
$("#subcat").append(
"<input type='button' class='subcat' id='" + row.subcat_id + "' value='"+ row.subcat_name + "'>"
);
});
});
});
and the append part could be optimized like this (it's more readable as you can see)
$("#subcat").append($(
"<input/>"
, {
cssClass: 'subcat'
, id: row.subcat_id
, value: row.subcat_name
}
));

i think an index would solve the problem
$("#subcat").append("<input type='button' class='subcat' id='" + data[index].subcat_id + "' value='"
+ data[index].subcat_name + "'></p>");

Related

show array object values inside ajax success section

Here am getting the result as follows
Now i want to show that content inside a select box with option values so how can we do that..
Here i have written like this
var data = data.user_contacts
var formoption = "";
$.each(data, function(v) {
var val = data[v]
formoption += "<option value='" + val + "'>" + val + "</option>";
});
$('#user_contacts').html(formoption);
but am getting value as undefined
You need to use keyname to get required values i.e : ContactID ,UserID..etc .
Demo Code :
var data = {
"user_contacts": [{
"ContactID": 1,
"UserID": 12,
"EmailAddress": "A#gmail.com"
}, {
"ContactID": 2,
"UserID": 122,
"EmailAddress": "A2#gmail.com"
}]
}
var datas = data.user_contacts
var formoption = "";
$.each(datas, function(v) {
var val = datas[v]
//use key to get value
formoption += "<option value='" + val.ContactID + "'>" + val.EmailAddress + "</option>";
});
$('#user_contacts').html(formoption);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="user_contacts">
</select>
Hope this will get the val.
var data = data.user_contacts
var formoption = "";
$.each(data, function(index,val) {
formoption += "<option value='" + val + "'>" + val + "</option>";
});
$('#user_contacts').html(formoption);

Php/jquery: How to show value of array loaded elements from db with a loop?

I've written the following php code:
$query = mysql_query("SELECT * FROM utenti WHERE username = '$username'");
$query_db = mysql_query("SELECT * FROM utenti");
$i = 0;
$array_user = mysql_fetch_array($query);
$dati = array("str"=>array());
while ($array_db = mysql_fetch_array ($query_db)) {
if ($array_user[country] == $array_db[country]) {
if ($array_user[city] == $array_db[city]) {
if ($array_user[cap] == $array_db[cap]) {
if ($array_user[square] == $array_db[square]) {
$dati["str"]["n".$i] = "Nome ".$array_db[username];
$i++;
}
}
}
}
}
echo json_encode ($dati);
I want to load an array using elements from database during a loop:
$dati["str"]["n".$i] = "Nome ".$array_db[username];
and then to show index and value of this array after an Ajax request:
...
success:function(msg){
if(msg){
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
});
}else{
$("#location").html('Not Available');
}
It doesn't work and I can't find the mistake. Could you help me, please?
Supposing your code
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
});
works fine.
Then, your attempt $("#location").html(key + ": " + value); means that everytime contents of #location will be overwritten.
Instead, you can use append():
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
$("#location").append(key + ": " + value);
});

Can't read json elements from mysql query via ajax

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);

Is there a more efficient way to write this PHP/jQuery

I have this PHP:
<?php
$data = file_get_contents('http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml');
$xml = simplexml_load_string($data);
$data1 = file_get_contents('http://www.skysports.com/rss/0,20514,11661,00.xml');
$xml1 = simplexml_load_string($data1);
$master[0] = $xml;
$master[1] = $xml1;
echo json_encode($master);
?>
And this jQuery:
var myRSS =[];
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, function(index, item){
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
$('#loader').remove();
}
});
$.each(data[1].channel.item, function(index, item){
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
}
});
});
}
rssReader();
setInterval(rssReader, 10000);
There seems to be a lot of repeated code and therefore isn't very DRY programming. The returned JSON actually has the same structure, from BBC and Sky Sports so there must be a more efficient way of writing this.
Thanks
you can cut your jquery down to this(havent tested it there might be a typo):
var myRSS =[];
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, function(index, item){
linkhandler(item)
if (jQuery.inArray(item.title, myRSS) == -1) {
$('#loader').remove();
}
});
$.each(data[1].channel.item, function(index, item){
linkhandler(item)
});
});
}
function linkhandler(item)
{ // check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) == -1) {
// save item title in the array
myRSS.push(item.title);
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
}
}
rssReader();
setInterval(rssReader, 10000);
Just to make things a little cleaner, you could do something like this:
var myRSS =[];
var handleData = function(index, item) {
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
$('#loader').remove();
}
}
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, handleData);
$.each(data[1].channel.item, handleData);
});
}
rssReader();
setInterval(rssReader, 10000);
But, as far as efficiency is concerned, I don't think it's that different. But, it's at least cleaner.
Just a note to be aware of, try and make less consecutive changes to the DOM. In some of the answers it is minimal anyway so not too much of a problem. But each change to them DOM has a massive overhead compared to say constructing blank objects and inserting them en mass or making mass changes to lists and the like.

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

Categories