In an ajax call, i need to obtain, as a response, the value of a parameter of a JSON object, but i don't understand how to do it.
If this is my PHP file in which i reproduce the JSON structure
echo " { ";
echo '"general" : {';
echo '"obj" : [
{"name" : "Primo", "description" : "Descrizione associata alla prima voce"},
{"name" : "Secondo", "description" : "Descrizione associata alla seconda voce"},
{"name" : "Terzo", "description" : "Descrizione associata alla terza voce"}
]}}';
And this is my HTML file
$(document).ready(function(e) {
$('#name li').click(function() {
var name = $(this).text();
url = "example.php?name=" + name;
$.getJSON(url,
function(json) {
//for (i = 0; i < json.general.obj.length; i++) {
//output = "<tr>";
output = "<td>" + json.general.obj[0].name + "</td>";
output += "<td>" + json.general.obj[0].description + "</td>";
//output += "</tr><br/>";
console.log(output);
$("#response").append(output);
//}
});
});
});
<ul id="name">
<li data-id="1">Primo</li>
<li data-id="2">Secondo</li>
<li data-id="3">Terzo</li>
</ul>
<div id="response">
<!--Data goes here-->
</div>
Which is the right way to go? Where do i need to place the $_REQUEST['name'] variable to receive back as a response the desired "Description" value?
I'm stuck there
You can use the data-id to retrieve the specific item of the array by its index, something like this:
$('#name li').click(function() {
var name = $(this).text();
var index = $(this).data('id') -1;
var url = "example.php?name=" + name;
$.getJSON(url, function(json) {
output = "<p>" + json.general.obj[index].name + "</p>";
output += "<p>" + json.general.obj[index].description + "</p>";
$("#response").append(output);
});
});
Example fiddle
Note that I changed td in the output to p as td elements are only valid within tables.
Also, if you only want the data of the last clicked element to be visible (instead of appending a new set each time) you can use:
$("#response").html(output);
Related
Hi I am trying to get attribute values from array of elements...
JQuery
function sendM(){
$.ajax(
{
type:'POST',
url:'../business_logic/send_chat_user.php', //URL
data:{ u_id: <?php echo $_SESSION['uid']?>,c_id }, //Data
beforeSend:function(){},
success:function(data,status){ //Data,status
var item = $(data).hide().slideDown("slow");
var el = $.parseHTML(data);
var e = $("a", el).attr ("value"); // This only gives me single value.. I want an array
$('#msg').append(item);
}
});
}
send_chat_user.php file
echo '<ul class="nav nav-list">';
for($i = 0 ; $i < count($list) ; $i++)
{
echo '<li>';
echo '<div class="user_list">';
echo '<img src="../images/default_profile_pic/d_boy.png" class="img-rounded">';
echo ''.$list[$i]['fn'].' '.$list[$i]['ln'].'';
echo '</div>';
echo '</li>';
}
echo '</ul>';
I want to get array of values from attribute 'value' of Anchor tag . I am able to get single value in jquery in variable e ... but i want array of values.
$.ajax({
type:'POST',
url:'../business_logic/send_chat_user.php', //URL
data:{ u_id: <?php echo $_SESSION['uid']?>,c_id }, //Data
beforeSend:function(){},
success:function(data,status){ //Data,status
var arr = [];
var item = $(data).hide().slideDown("slow");
var el = $.parseHTML(data);
var e = $("a", el);
e.each(function(index) {
arr.push($(this).attr('value'));
});
alert(arr.toString());
$('#msg').append(item);
}
});
How can I display the image in the following div id="image" using jQuery
HTML:
<h3 style="clear:both" class="margin_top30">Images</h3>
<div class="contentSection">
<div id="image"> </div>
</div>
jquery:
$(document).ready(function(){
var id = window.location.search.substring(1);
id = id.replace('id=','');
var url = "http://localhost/schoollife/services/author_chapter.php?a=image&id="+id;
//alert(url);
$.ajax({
url:url,
success:function(result){
var obj = $.parseJSON(result);
var table = "<table>";
for (var i = 0; i < obj.length; i++) {
table += "<tr>"
table += "<td><img src='http://img/"+obj[i].image_file_name+"' style='margin-right:20px;' /></td>";
table += "</tr>";
table +="<tr><td colspan='3'> </td></tr>";
}
table += "</table>";
$("#image").html(table);
}
});
})
Thanks in advance.
You rather rely on $.getJSON as it makes your code saying what you want to achieve with $.ajax - retrieving JSON-formatted data from a remote source. And check your server side code if it provides a valid JSON. Here is a working example:
$( document ).ready(function(){
var url = "./author-chapter.json";
$.getJSON( url, function( data ){
var out = "<table>";
$.each( data, function( i, row ) {
out += "<tr>";
out += "<td><img src='" + row.image_file_name + "' style='margin-right:20px;' /></td>";
out += "</tr>";
out +="<tr><td colspan='3'> </td></tr>";
});
out += "</table>";
$("#image").html( out );
});
});
Controller (author-chapter.json)
[
{"image_file_name": "./slides/sample_fussen.jpg"},
{"image_file_name": "./slides/sample_keukenhof.jpg"}
]
P.S. If you want to control exceptional behavior - just go with deferred methods - .done, .fail instead of the callback
I'm not sure if I'm doing this completely wrong, but I'm hoping what I'm trying to do is possible.
I have an existing ajax jquery function that saves the "selected" checkboxes from a user and stores them in $_SESSION['order_items'][index]['cheeseids'][]; When a user goes to recall this "item", I'd like to have the same checkboxes "selected" as before. See example below:
[order_items] => Array
(
[1] => Array
(
[cheeseids] => Array
(
[0] => 1
[1] => 2
[2] => 4
)
My "change/restore" jquery function uses the following variables to get the index number:
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
The function I'm trying to use to "re-select" boxes 1, 2, 4 (from cheeseids array) is not working (it is inside my jQuery function). It actually causes the entire jQuery code to not work:
<?php
foreach($_SESSION['order_items'] as $key => $value)
{
?>
var idnum = <?php echo $value['<script type="text/javascript">productIDVal</script>']['cheeseids'] ?>;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
<?php
}
?>
JS Output:
var idnum = ;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
var idnum = ;
$("div.cheesebox input[type=checkbox]").eq(" + idnum + ").attr("checked", "checked");
Entire JS/jQuery function that I'm adding the PHP too:
$("#basketItemsWrap li img.change").live("click", function(event) {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").show();
$.ajax({
type: "POST",
url: "includes/ajax/functions.php",
data: { productID: productIDVal, action: "deleteFromBasket"},
success: function(theResponse) {
$("div#order_qty input").attr('value', $("#order_" + productIDVal + " #order_qty").text());
$("div#order_listprice input#price1").attr('value', $("#order_" + productIDVal + " #order_listprice").text().replace("$", ""));
$("div#order_price input#discprice1").attr('value', $("#order_" + productIDVal + " #order_price").text().replace("$", ""));
$("div#order_price input#itemprice1").attr('value', $("#order_" + productIDVal + " #order_itemprice").text().replace("$", ""));
//The following functions restore the order details in the select menus, checkboxes, and radio buttons
//Restores the item selected
for(var i = 0; i < $("#item1 option").size(); i++)
{
if($("#order_" + productIDVal + " #order_item").text() == $("#item1 option:eq("+i+")").text())
{
$("#item1 option:eq("+i+")").attr("selected", "selected");
//$("#item1").val(i);
CalcPrice(1);
}
}
//Restores the promotion selected
for(var i = 0; i < $("#promo1 option").size(); i++)
{
if($("#order_" + productIDVal + " #order_promo").text() == $("#promo1 option:eq("+i+")").text())
{
$("#promo1 option:eq("+i+")").attr("selected", "selected");
//$("#promo1").val(i);
CalcPromo(1);
}
}
<?php foreach($_SESSION['order_items'][1]['cheeseids'] as $id): ?>
$("div.cheesebox input[type=checkbox]#<?php echo $id;?>").attr("checked", "checked");
<?php endforeach; ?>
//Restores the cheese options selected
// $('div.cheesebox input[type=checkbox]').size(); i++)
//$('div.cheesebox input[type=checkbox]').eq(1).attr('checked', 'checked');
$("#order_" + productIDVal).hide("slow", function() {$(this).remove();Calc();});
$("#notificationsLoader").hide();
}
});
});
PHP/HTML code to generate the checkboxes:
<?php
//Display all "cheese" options in a checkbox group
foreach($_SESSION['ingr_cheese'] as $key => $value)
{
echo "<div class=\"cheesebox\" style=\"float:left; width:175px; margin-bottom:7px;\">";
echo "<input type=\"checkbox\" name=\"cheese1\" id=\"cheese1\" class=\"cheeseCheck\" value=\"".$key."\"> <label for=\"cheese1\">".$value['cheese']."</label></br>";
echo "</div>";
}
?>
If the array you listed is already is an accurate representation of what's in the $_SESSION array, then this code should do what you're looking for.
<?php foreach($_SESSION['order_items'][1]['cheeseids'] as $id): ?>
$("div.cheesebox input[type=checkbox]#<?php echo $id;?>").attr("checked", "checked");
<?php endfor; ?>
This should generate javascript that looks like this:
$("div.cheesebox input[type=checkbox]#1").attr("checked", "checked");
$("div.cheesebox input[type=checkbox]#2").attr("checked", "checked");
$("div.cheesebox input[type=checkbox]#4").attr("checked", "checked");
This code assumes your markup for the checkboxes looks (somewhat) like this:
<div class=".cheesebox">
<input type="checkbox" id="1">
<input type="checkbox" id="2">
<input type="checkbox" id="3">
<input type="checkbox" id="4">
</div>
I verified the selector syntax, but if that doesn't work, then I probably made a bad assumption about the markup of your checkboxes. Paste in some more of your html if this isn't enough to point you in the right direction and I'll take another swing at it.
I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;
I'm following through an example which deals with the following json object passed from a php page:-
{"book":[{"title":"Harry Potter","author":"J K. Rowling","year":"2005","price":"29.99"},{"title":"Learning XML","author":"Erik T. Ray","year":"2003","price":"39.95"}]}
I know that you can iterate through and print all the data to a table as follows:
$.each(data.book, function(index, book) {
content = '<tr><td>' + book.title + '</td>';
content += '<td>' + book.author + '</td>';
content += '<td>' + book.year + '</td>';
content += '<td>' + book.price + '</td></tr>';
$(content).appendTo("#content2");
});
But say the json data is dynamic following the same structure, how can I adapt the above code to work for this? I was thinking I would need some sort of nested loop.
Whats causing me confusion is that for the line $.each(data.book, function(index, book) {
data.book will not always be data.book they would be data.foo
and the lines which refer to book.title will not always be the same it could be book.bar
Any guidance most appreciated
Yes you can do it in a nested loop like this
var content = '';
$.each(data.book, function(index, book) {
content += '<tr>';
$.each(book,function(k,v){
content += '<td>' + v + '</td>';
});
content += '</tr>';
});
$(content).appendTo("#content2");
http://jsfiddle.net/tjjQh/
Oh.. then use the for in loop
for (v in data) {
$.each(data[v], function(index, book) {
content += '<tr>';
$.each(book, function(k, v) {
content += '<td>' + v + '</td>';
});
content += '</tr>';
});
}
http://jsfiddle.net/8YCgA/
You may want to check out jQuery Templating.
var data = [
{ name : "John", age : 25 },
{ name : "Jane", age : 49 },
{ name : "Jim", age : 31 },
{ name : "Julie", age : 39 },
{ name : "Joe", age : 19 },
{ name : "Jack", age : 48 }
Can be expressed as:
<li>
<span>{%= $i + 1 %}</span>
<p><strong>Name: </strong> {%= name %}</p>
{% if ($context.options.showAge) { %}
<p><strong>Age: </strong> {%= age %}</p>
{% } %}
</li>