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
Related
I am storing a PHP array variable in Jquery variable.
Following is the code that I am using:
<script>
var tagger = '<?php echo json_encode($tags); ?>';
var obj = jQuery.parseJSON(tagger);
$.each(obj, function(key,value)
{
$("#post_tags").tagging("add", value);
});
</script>
In tagger variable, I am getting this below data.
var tagger = '["sdf"," da"," adf"," ad"]';
But when I am running the loop it is showing values from the second index, the first index value is being eliminated.
Only these values are visible in the field : '[" da"," adf"," ad"]'.
The sdf value is not displayed.
May I know that where is it being wrong, as far as I am concerned the code is good to go. But still, want to confirm that is there anything missing.
<script>
// try this
var obj = <?php echo json_encode($tags); ?>;
//var obj = jQuery.parseJSON(tagger);
$.each(obj, function(key,value)
{
$("#post_tags").tagging("add", value);
});
</script>
You don't have to parse the tagger because it already in json format:
<script>
var tagger = <?php echo json_encode((array)$tags);?>;
$.each(tagger, function(key,value)
{
$("#post_tags").tagging("add", value);
});
</script>
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 followed other reslted question but still unable to solve this problem. I want to store the values of an array from php into an array of js. I tried myself butr getting indefined value in all the cases i tried
Plese anyone let me know where i am wrong
my Php code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
echo json_encode($myArray);
?>
and the js code
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array(); var i= 0;
jQuery.getJSON("phparray.php", function(data) {
while(i<5){
res[i]=data.i;
i++;
}
});
});
jQuery("#result").html(res[0]);
});
also treid this js
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
var i= 0;
jQuery.getJSON("phparray.php", function(data) {
jQuery(data).each(function(key, value) {
res[i]=value;
i++;
});
});
jQuery("#result").html(res[0]);
});
Try below code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
$dataarray=array("myarray"=>$myArray);
echo json_encode($dataarray);
?>
Jquery
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
jQuery.getJSON("phparray.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});
The problem with your code is you are updating the result before the JSON has been loaded. There is also no reason to copy every item in the array in this case just set res = data (although the above example of sending back an associative array or JS object is good practice).
PHP
<?php
for($var=5; $var<10; $var++){
$myArray[]=$var;
}
echo json_encode($myArray);
JavaScript
$(document).ready(function() {
var res;
$("#result").bind('update', function() {
$("#result").html(res[0]);
});
$("#previous").click(function(){
$.getJSON("phparray.php", function(data) {
res = data;
$("#result").trigger('update');
});
});
});
so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);