I am using php to talk to a mysql database then encoding the associative array with json_encode. That much I know is working, I can call the php directly and see the json result.
With jQuery I am using onChange on a dropdown to call the php function and to get the results.
I think I have problems with the jQuery and json, but I have looked through multiple posts and cannot find a good answer.
Here is the code I am using. How do I get to the json array? I have tried data['ele'], data.ele, data[0] and all return undefined.
$('#itemDD').change(function(data){
alert("Changing");
askServer(function(data){
alert("!" + data['retailListPrice']);
//spin through the data and put the results in workingQuote
});
});
function askServer(callback)
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
alert(strUrl);
jQuery.ajax({
url:strUrl,
success:callback,
dataType: "json"
});
}
});
PHP
$sql="SELECT *
FROM items
WHERE modelNum='" . $selectedModel . "'";
$result = mysql_query($sql,$conn) or die("Error" . mysql_error());
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
echo json_encode($resultArray);
You using array and mysql_fetch_assoc. So to get the data, use data[0]['rowName'] or data[0].rowName
try this (note: object/array format is diffrent in JS):
function askServer()
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
alert(strUrl);
$.get(strUrl, function(data){
alert(data.retailListPrice);
});
}
Inside change event just call the askServer() function and declare it outside of change event, like
$('#itemDD').change(function(data){
//...
askServer();
});
and your askServer() function
function askServer()
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
$.get(strUrl, function(data){
$.parseJSON(data);
alert(data.retailListPrice);
});
}
Related
function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
});
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
/*when i use alert method, this function works very well, why?*/
alert('SomeString');
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
};
in Data1.php
/*give data from database1 and print to HTML File*/
if ($_POST['Sections']) == "String")
{ $results = mysql_query("SELECT * FROM Table1");
while($row = mysql_fetch_array($results))
{ echo $row['Tags']; }
in Data2.php
/*give data from database2 and Use for events*/
if ($_POST['GallerySec']) == "String")
{ $results = mysql_query("SELECT * FROM Table2");
while($row = mysql_fetch_array($results))
{ echo json_encode($row); }
in Client side when i use it then Data1.php works very well but Data2.php only when i write an
alert('Some stringh');
after
var data = jQuery.parseJSON(response);
line, it's work well, why? what's due to this problem?
I'm going to guess that you need the second .post() to be processed AFTER the first .post() and when you put the alert() in, that guarantees that it will go in that order, but without the alert(), it is a race condition and depends upon which .post() returns quicker.
There are a couple ways to fix the sequencing. The most straightforward is to start the second .post() from the success handler of the first so that you know the first has already completed.
You can also use jQuery promises or you could use your own flags to keep track of which has finished and call the last bit of code only when both have finished.
Here's how you would start the second .post() from the success handler of the first to guarantee the order:
function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
});
};
I am new to AJAX using jquery. I have a json response as below:
[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]
And my ajax file is :
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);//parse JSON
alert(json_obj);
var output="<ul>";
for (var i in json_obj)
{
output+="<li>" + json_obj[i].customer_name + "</li>";
}
output+="</ul>";
$('#resdiv1').html(output);
}
Though I can view the JSON response in div id resdiv, the div id resdiv1 is empty ! Also alert(json_obj); does not alerts anything ! Whats wrong with the file ?
NB: I am learning from Zuch Tutorial
You dont need to parse the json again.Simply do a iteration and try like this
var json = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
var output="<ul>";
$.each(json,function(key,val){
output+="<li>" + val.customer_name + "</li>";
});
output+="</ul>";
console.log(output);
See DEMO
check this out
// Need to parse if string.
var result = '[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]';
var json_obj = $.parseJSON(result);//parse JSON
// No need to parse
var json_obj = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
Also check this
// if undefined, you don't have resdiv1 div or you have call function before your div render.
alert($('#resdiv1').html());
Can you try this
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);
//parse JSON alert(json_obj);
var output="<ul>";
$.each(json_obj,function(key,val){
output+="<li>" + val.customer_name + "</li>";
console.log(key+":::"+val);
});
output+="</ul>";
$('#resdiv1').html(output);
}
I'm having the below output from an ajax script:
{"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"}, {"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"},
I am trying to populate a select menu with info from this JSON data:
<script type="text/javascript" charset="UTF-8">
$.getJSON(
'getcountries.php',
function(data) {
var items = [];
$('#country').append(data);
$.each(data['DATA'], function(key, val) {
$.each(val, function(key, value) {
console.log(value);
});
});
}
);
Issue with it is that the $('#country').append(data) (or append(data['DATA']) always returns error "Value does not implement interface Node."
Could anyone point out how I could get the specific JSON data I have into the select script?
.append() only accepts HTML string, DOM Element, or jQuery Object
See: http://api.jquery.com/append/
I assume this is the result you actually want.
var data = {"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}]};
var $select = $('#country').empty();
$select.append(
data.DATA.map(function (el, i) {
return $('<option>')
.val(el.COUNTRYID)
.text(el.DESCRIPTION)
.data('DATA', el); // in case you also want to access its COUNTRYCODE
})
);
jsFiddle: http://jsfiddle.net/terryyounghk/ZshG4/
DEMO: http://jsfiddle.net/q5Q3d/
var a = {
"DATA":[
{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},
{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},
{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}
]
}
$.each(a.DATA, function(idx, val){
var option = "<option value='" + val.COUNTRYID + "'>" + val.DESCRIPTION + "</option>";
$('select').append(option);
});
I have my jsonOutput.php page like this :
$response['imgsrc'] = $filename[1];
echo json_encode($response);
It outputs a filename like {"imgsrc":"071112164139.jpg"}
Now my question is, how can I use jQuery in my index.php to get the filename into a variable using ajax ?
$.getJSON('jsonOutput.php', function(data) {
var filename = data.imagesrc;
});
Try this:
$.get('<your php file>', {}, function(response) {
var imagesrc = response.imgsrc;
alert(response.imgsrc);
});
Have a read through http://api.jquery.com/jQuery.get/
All you'll have to do is execute a jQuery ajax call -
var imgSrc = '';
$.ajax(PATH_TO_PHP_SCRIPT,{},function(response){
imgSrc = response.imgsrc;
},'json');
Your imgsrc parameter will now be a JavaScript variable called imgSrc. Don't forget to specify that your dataType is a json.
Reference -
ajax()
You can use jQuery.parseJSON to parse json output into a javascript object.
Following code would work:
var json = json_encode(<?php echo $response ?>);
var obj = jQuery.parseJSON(json);
alert("file name is: " + obj.imgsrc);
I've been looking around for a solution to what appears to be a simple problem, but am unable to find the solution...any guidance would be appreciated.
I am attempting to build a select box using JSON object retrieved from a PHP script. The PHP script (versions.php) is running a query against a database table; code is as follows:
$posts = array();
if(mssql_num_rows($result)) {
while($post = mssql_fetch_assoc($result)) {
$posts[] = $post;
}
}
header('Content-type: application/json');
echo json_encode($posts);
...and returns the following json structure:
[{"version":"3.3.0"},{"version":"1.5.0"}]
The PHP file is being called from a central JS file, which is structured as follows:
jQuery(function($){
$.getJSON('versions.php', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
var option = $('<option/>');
option.attr('value', val)
.html(data)
.appendTo(select);
});
});
});
Looking at firebug, I see lists of objects, but not the values in the array. I guess this is related to the code in the javascript file above - just not sure how to access the values from the json object.
Thanks in advance.
You're almost there. Based on your JSON structure, It should look something like this:
jQuery(function($){
$.getJSON('versions.php', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
$('<option/>').attr('value', val.version)
.html('version ' + val.version)
.appendTo(select);
});
});
});