parseJSON to JSON rsponse in jquery-ajax not working - php

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

Related

How to Communicate between PHP and JavaScript

I wrote a JavaScript function to convert GeoJson data to WKT format. It works when i get the input value in the javascript code directly. But I don't know how to get the input from the php and send it back.
Here is the php code:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function.
Please help me finish the JavaScript Code:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}
Basically:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!
Since you already know your return data will be JSON, you can just use $.getJSON() for convenience. This is a $.get() request paired with JSON.parse(). With $.getJSON(), the JSON is parsed on response. To send the data back, just use use jQuery's $.post().
Here's an edited version of your code.
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};

How can I retrieve my JSON output into a JavaScript variable?

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

jQuery Json + jQuery onChange

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

AutoSuggest from JSON with Link

Hy!
I want to make a autosuggest from my php file that returns a Json Object.
I parse it in js to get a link with the right id (look at the json)
JSON from search_new.php:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200}
Calling in JS:
<script type="text/javascript">
$(function() {
var allRecipes = (<?php include("php/search_new.php"); ?>).Data.Recipes;
var recipeNames = [];
for(var i in allRecipes) {
recipeNames.push("" + allRecipes[i].TITLE) + "");
}
var arr = new Array();
for(var k in recipeNames){
arr.push(" " + recipeNames[k]);
}
$("#searchrecipes").autocomplete({
minLength: 3,
source: arr
});
});
</script>
Firebug Error:
missing ; before statement recipeNames.push("" +
allRecipes[i].TITLE) + "");
Before i had recipeNames.push("allRecipes[i].TITLE)"); everything worked well
Please help.
Yes I see your problem.
Here is the code you need:
$(function() {
var data = (<?php echo file_get_contents("php/search_new.php"); ?>).Data.Recipes;
var source = [];
for (var i in data) {
source.push({"href": "/php/get_recipe_byID.php?id=" + data[i].ID, "label": data[i].TITLE});
}
$("#searchrecipes").autocomplete({
minLength: 3,
source: source,
select: function(event, ui) {
window.location.href = ui.item.href;
}
});
});
You can find an example here: http://jsfiddle.net/dFApV/
there is for sure an extra bracket right to allRecipes[i].TITLE that must be erased! :D
I would say, you could achieve the same result, but with a much nicer solution by using the .result method.
Tell me what do you think about it!
JQuery API Autocomplete Result

OPTIONS request being made for $.ajax

I have the following code which,currently im running on my local machine.I am making a call to a php script called getxml.php,which should send the contents of an xml file as the response.
But,instead of a GET request, in Firebug i see that an OPTIONS request is being made, like
OPTIONS getxml.php . I think im not making a cross domain Ajax request,but still am facing this problem . Any way to fix this ?
var employee_list = new Object;
$(function(){
$.ajax({
type:"GET",
url:"http://localhost/projectname/getxml.php",
datatype:"xml",
success: function(xml){
$(xml).find('employee').each(function(){
var name_text = $(this).find('name').text();
var url_text = $(this).find('url').text();
employee_list[name_text] = url_text;
$('<li></li>').html(name_text + ' (' + url_text + ')').appendTo('#update-target ol');
});
} //closing function
}); //closing $.ajax
}); //closing $(
getxml.php
<?php
//Send the xml file as response
header('Content-type: text/xml');
readfile('employee_results.xml');
?>
Thank You
Make sure getxml.php exists. OPTIONS usually means you have a slight misspelling.
change datatype to dataType and see if that fixes your problem. The rest of the code looks right.
edit: also, I'm not a PHP pro, but I wrote a map application which uses a similar approach. To return xml, I used:
header("Status: 200");
header("Content-type: text/xml");
echo file_get_contents($q,0); /*$q is the query/filename*/
exit();
I remember reading somewhere that header("Status: 200"); was required.
edit: Here is how I've done the same thing. I hope this helps.
/* call ajax method to retrieve earthquakes */
$.ajax({
type: "GET",
url: "../getxml.php?q=" + xmlLocation,
dataType: "xml",
success: function(xml){
$(xml).find('entry').each(function(){
/* Retrieve all needed values from XML */
var title = $(this).find('title').text();
var summary = $(this).find('summary').text();
var coord = $(this).find('georss\\:point').eq(0).text();
if(!coord){var coord = $(this).find('point').text();};
var points = coord.split(' ');
var latitude = parseFloat(points[0]);
var longitude = parseFloat(points[1]);
var htmlString = "<div class=\"infowindow\"><b>" +
title + "</b>" + "<p>" + summary + "<br></div>";
var myLatlng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker(
{
position: myLatlng,
map: map,
title: title
});
markers[markers.length] = marker;
addInfoWindow(marker, map, htmlString);
$('#output').text("Showing " + markers.length + " earthquakes");
});/* end each */
}
}); /* end $.ajax */
The php file is exactly as I posted above, but with "security" to respond only to ajax requests.

Categories