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
Related
I'm trying to connect my mysql database with an html page using an ajax script. Based on the tutorial from Adnan Afzal (http://adnan-tech.com/tutorial/get-data-from-database-using-ajax-javascript-php-mysql), I coded one php and one html file. However, each time I try to run the page, I get an error telling me that the first character at position 1 is not correct :
Here is a dump of my php (called data.php)
$data = array();
while ($row = mysqli_fetch_object($result))
{
array_push($data, $row);
}
echo json_encode($data);
exit();
Here is a dump of my html page
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<tr>
<th>id_country
<th>Country_name_en
<th>Country_name_fr
</tr>
<tbody id="data"></tbody>
</table>
<script>
var ajax = new XMLHttpRequest();
ajax.open("GET", "data.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var html = "";
for(var a = 0; a < data.length; a++) {
var id_country = data[a]['id_country'];
var Country_name_en = data[a]['country_name_en'];
var Country_name_fr = data[a]['country_name_fr'];
html += "<tr>";
html += "<td>" + id_country + "</td>";
html += "<td>" + Country_name_en + "</td>";
html += "<td>" + Country_name_fr + "</td>";
html += "</tr>";
}
document.getElementById("data").innerHTML += html;
}
};
</script>
</body>
</html>
I hope the way the question is published is acceptable, I am not expecting to have code written on my behalf. I would be very keen on understanding what I am doing wrong here and hopefully, this post could be useful to anyone else.
Edit : Following the reply of Aynber, I have added a screenshot below of the debugging network tab :
Edit 2 : Following the reply of Shivendra Singh, I have corrected the code as follows :
var id_country = data[a]['id_country'];
var Country_name_en = data[a]['country_name_en'];
var Country_name_fr = data[a]['country_name_fr'];
Thanks a lot to the help of the contributors.
It was the syntax of how I was referring the fields which was not correct :
[...]
var Country_name_en = data[a]['country_name_en'];
[...]
I have corrected the code accordingly above to depict the correct situation.
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);
Advance note: I have already looked at and looked at and tried the solutions in the SO question: Jquery checkbox change and click event. Others on SO deal more with reading the values rather than the issue that the event is not firing.
I will admit that I am a relative newbie to JQuery.
I am trying to make two changes. One when a text field changes and one when a checkbox is toggled. Both are within a form. The idea is that if the text field changes a computation is done and the return value is written into the text after the checkbox. The checkbox toggles that text on and off.
Once finished the form can be submitted.
the code (as seen below) also uses php.
I've pulled the relevant code. I read several examples on line so there is are attempts using
<span id="foo"><input></span>
<input class='romanCheck' id='romanCheck' type='checkbox'>
Neither alert is being called. JSFiddle kinda barfed on the PHP. For the checkbox I've tried both .change() and .click()
The browsers I've tested on are all Mac (my dev environ)
Safari: 7.0.3 (9537.75.14)
Chrome: 33.0.1750.152
Firefox: 28.0
I've attached the relevant code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Not Working.php</title>
<link rel="stylesheet" href="jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.css">
<script src="jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<script>
function romanize (num) {
return "(" + "roman for " + ")";
}
$(document).ready(function(){
$(".romanCheck").live("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$("span.iterationField input").live("change",function() {
alert("#iteration.change has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
</script>
<form action='EventValidateProcess.php' method='post'>
<?php
$doesShow = 1;
$isRoman = 1;
$iteration - 13;
print "<table>\n";
print "<tr>\n\t<td>Iteration</td>\n\t";
print "<td><span id='iterationField'><input type='text' name='iteration' value='" . $iteration . "'></span></td>\n\t";
print "<td><input type='checkbox' name='doesShow' value='1'";
if ($doesShow == 1) {
print " checked";
}
print "> visible | ";
print "\n<input class='romanCheck' id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print "> uses Roman numerals\n";
print "<span id='romanDisplay'>(XX)</span></td>\n</tr>\n";
?>
</table>
<button type='submit' name='process' value='update'>Update</button><br/>
</form>
</body>
.live() deprecated: 1.7, removed: 1.9
Use .on() as you are using jquery-1.10.2
Syntax
$( elements ).on( events, selector, data, handler );
$(document).on("change", "span.iterationField input" ,function() { //code here });
$(document).on("change", ".romanCheck" ,function() { //code here });
span.iterationField is not exist, instead span#iterationField,
and just use:
$(document).ready(function(){
$("input.romanCheck").on("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
Note: make sure jquery library in imported
After a lot of finessing it seemed the answer that worked best was the following:
$(document).change("input.romanCheck", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$(document).change("input.iterationField", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
Using:
print
"<input id='iterationField' type='text' name='iteration' value='";
print $iteration . "'/>";
print
"<input id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print ">";
print "<span id='romanDisplay'>";
if ($isRoman == 1) {
print "(" . $romanIteration . ")";
}
print "</span>";
Im not sure what is your problem but try this.
function romanclick(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//your code romanclick
$('span.iterationField input').click(function(){
textchange();// call it again
});
}
function textchange(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//change text code
$('.romancheck').click(function(){
romanclick();// call it again
});
} ;
1.$(document).on("change", "span.iterationField input" ,function() { //call your function here });
2.$(document).on("change", ".romanCheck" ,function() { //call your function here });
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>");
So I have a php page that gets data from database and displays a table. Each td symbolises a seat in a movie theater. What i want to do is when a user clicks on one or more tds, and clicks send, the status column for each td in the database changes to 1 from 0(default). When the database is accessed next time, the td's with status=1 have a different color.
My code upto now is:
<div id="screen">SCREEN</div>
<div id="Seatings">
<?php echo "<table border='1'>
<tr>
<th>Seating</th>
</tr>";
$count=0;
echo "<tr>";
echo"<td id='Seat_rn'>A</td>";
while($row = mysql_fetch_array($sql))
{
if($count<10){
echo "<td id='Seat_A' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo "</tr>";
$sql=mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
echo "<tr>";
echo"<td id='Seat_rn'>B</td>";
while($row = mysql_fetch_array($sql))
{
if($count>=10){
echo "<td id='Seat_B' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo"</tr>";
echo "</table>";
?>
</div>
<input type="button" value="Done" name="done" onclick="window.close()">
My jquery code is:
$("td #Seat_A").click(function(){
$(this).css("background", "red");
});
$("td #Seat_B").click(function(){
$(this).css("background", "red");
});
$(document."done").click(function(){
alert(price:750 Baht);
})
I am nowhere near what i want and I'm sorry if any of my code is "amatuer-ish" but I am new to this and I have been trying very hard. Would appreciate any help that I can get.
First of all you have to add an ID to every TD on your table, i.e. Seat ID, For example:
echo "<td id='Seat_A' data-seat='". $row['id'] ."'class='count'>" . $row['Seat'] . "</td>";
Then send this ID to your PHP script with Ajax:
$("td #Seat_A").click(function(){
var seat_number = $(this).data("seat");
$.ajax({
type: 'POST',
url: "/take_a_seat.php",
data: 'seat_number='+seat_number,
success: function(data){
$(this).css("background", "red");
}
dataType: "json"
});
});
On the PHP script you have to do what you want to the seat with this ID and return true or false as a result. Let's suppose you have a field named reserved in your database table. You can get the unique ID and update that row to reserved = 1 for example.
Try this easy to use ajax script to accomplish your task
Features: you can show an gif img before send data to db in beforeSend section get response from php file in success section hide img after data inset in db in complete section and show successful or not success msg
var myVar = 'your desire data you want to send to db';
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"myVar="+myVar,
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
Javascript is client side. Your database is server side.. So you have to use php to change your database entries.
In short, if you want to execute PHP stuff without reloading page, than use AJAX. You can use it with your favorite JQuery.
This is an overview. For existing records you should some thing like this
<?php
$count=1;
$res = mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
while($row = mysql_fetch_array($sql)) {
if($row['status']==1) {
$tdcolor = 'red';
} else {
$tdcolor = 'blue';
}
?>
<td id="td-<?php echo $count;?>" sytle="background-color:<?php echo $tdcolor; ?>" onclick="reserveseat(<?php echo $count; ?>);" >
<?php
$count++;
}
?>
For changing after page load you will do ajax operation
<script type="text/javascript" language="javascript">
function reserveseat(count) {
$.ajax({
type: 'POST',
url: "bookseat.php",
data: '',
success: function(data){
$("#td-"+count).css("background-color", "red");
}
});
}
</script>
In bookseat.php you will change the status ... :-) Read about ajax from here . :-)