Retrieve image from database and display using ajax - javascript

I'm facing problem while retrieving image location from database and display it using ajax.
Below is the code.
I can retrieve all the data except image.
Needed help with that please.
<script type="text/javascript">
$(document).ready(function() {
var url = "http://localhost/project/app/read.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
var bookname = field.bookname;
var publisher = field.publisher;
var author = field.author;
var location = field.location; //image location
$("#listview").append("<h2>" + bookname + " </h2><p>" + publisher + "</p><p>" + author + "</p>");
});
});
});
</script>
read.php
<?php
include "db.php";
$data=array();
$q=mysqli_query($con,"select * from `book`");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
echo json_encode($data);
?>
the below code is also not working
"<img src=" +location+ /">"

Related

PHP - Onchange reload page with value of select

I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k

Unwanted JSON Response

I'm using this small JSON function with a database.
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
This produces this in the browser, which I don't want/need.
{"users":[{"Title":"Anyway","ArtistNumber":"2","TrackTime":"167","Composer":"John
Glaze","Lyricist":"Kellee
Maize","FileLocation":"public/Anyway.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"One
Way Heartbeats","ArtistNumber":"4","TrackTime":"187","Composer":"Bill
Bobs","Lyricist":"Michael
McEachern","FileLocation":"public/OneWayHeartbeats.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Parallel
Me","ArtistNumber":"3","TrackTime":"192","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"private/ParallelMe.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"1"},{"Title":"Poisoned
Oxygen","ArtistNumber":"3","TrackTime":"177","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"public/PoisonedOxygen.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Xmas
Prison Blues","ArtistNumber":"1","TrackTime":"192","Composer":"Steve
Perry","Lyricist":"Steve
Perry","FileLocation":"private/XmasPrisonBlues.wma","rated":"0","scores":"[0,0,0,0,0]","free":"1"}]}
Any ideas on how to hide it or remove it from coming up?
Thanks
This is the Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
Using jQuery 1.10.2
The songlist element is found here
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><div id= songlist> </div> </p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p>Songs</p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
And basically whenever I run these files, I get that long string I stated at the beginning as a response in my browser everytime.
Well your PHP appears to be returning a valid json string, but it is not being coverted automatically to a json object so that it can be processed by javascript as an object.
You could try forcing the parse to a json object like this
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {

Trying to populate a drop down list with jquery and ajax

Here's my code :-
<script>
$(document).ready(function(){ //#This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ //# the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json',
success:function(data){
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
And here's the php script.
<?
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo json_encode($res);
}
$i++;
}
?>
I want options with time values inserted inside a select on my html page which looks something like this :-
<select id="timing" name="timing"></select>
My java script code is posting values to the php script alright but the code is still not working. There aren't any errors in my javascript as I see it. Kindly help me out
var postUrl = "time.php";
$.ajax({
type: "POST",
url: postUrl,
data: {day: day,doctor: doctor},
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
$('#timing').append('<option value="' + key + '">' + value + '</option>');
});
}
});
hope it's help to you
success:function(data){
var select= '<select>';
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
select = select+option'</select>';
$('#timing').html(select);
}
HTML :
<div id="timing"> </div>
var day=$("#day option:selected").val();
var doctor=$("#doctor option:selected").val();
data:"{day:'"+day+"', doctor: '" + doctor + "'}" ,

.load content when checkbox checked, remove when unchecked

I have a number of checkboxes which, when checked invoke the below script to show a chunk of html inside a form using .load:
$('input.article').click(function(){
var bits = $(this).attr('id').split('_');
var id = bits[1];
var article = 'article_' + id + '.html';
$('#form_' + id).load('<?php echo base_url(); ?>assets/html/' + article);
$('#form_' + id).toggle();
$('.submit').show();
});
The forms are dynamically created in the view like so:
<?php for($i = 1; $i <= 8; $i++){ ?>
<div id="form_<?php echo $i; ?>" class="hide">
</div>
<?php } ?>
However, I need the loaded html to be removed whenever the checkbox is unchecked, and that's where I get stuck. Using .toggle()the html is hidden, but it is being submitted anyway. Any idea how to achieve this?
Try this -
$('input.article').click(function(){
var bits = $(this).attr('id').split('_');
var id = bits[1];
var article = 'article_' + id + '.html';
if(this.checked){
$('#form_' + id).load('<?php echo base_url(); ?>assets/html/' + product);
}
else{
$('#form_' + id).empty();
}
$('.submit').show();
});
So add a check to see if it is checked. If it is not, empty its contents and hide it.
var bits = $(this).attr('id').split('_');
var id = bits[1];
if (this.checked) {
//...get content
} else {
$('#form_' + id).empty().hide();
}
Only load the content if the container is empty, and toggle the container based on wether or not the checkbox is checked :
$('input.article').on('change', function(){
var id = $(this).attr('id').split('_')[0],
article = 'article_' + id + '.html',
form = $('#form_' + id);
if (form.is(':empty'))
form.load('<?php echo base_url(); ?>assets/html/' + article);
form.toggle(this.checked);
$('.submit').show();
});

Jquery and get the eq value of my returned XML

Hi I have a simple ajax search that returns the results in a table. I can extract the XML and display it fine but what I cannot do is get the index number of the data (var Rows) .
When a user clicks the returned result I believe I would need this in order to retrieve all the data in order to use IE $("name:eq(1)",data).text();. Can anyone help me please and I hope this makes sense !!, thanks
My Jquery code is here
$(document).ready(function(){
$.ajax({
type: "GET",
url: "search_action.php?" + string ,
dataType: "xml",
success: disxml ,
});
})
}
function disxml(data){
dv = $('#crmbox')
$(data).find('list').each(function() {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
var rows = $(this).eq() ;
display = display + "(" + rows + ")" + " Name :" + name + " ID :" + cus_id + " <br>" ;
})
dv.html(r);
};
here is the php that generates my xml
echo '<results>' ;
while($row = mysql_fetch_array($result)) {
$name = $row['name'] ;
$major_id = $row['address1'] ;
echo '<list>' ;
echo '<name>';
echo $name;
echo '</name>';
echo '<mid>';
echo $major_id ;
echo '</mid>';
echo '</list>' ;
} ;
echo '</results>' ;
the extra tag is the close of an earlier function - no relevence to question
It sounds like you want the index you're currently at, in which case use the first parameter passed to the .each() callback, like this:
$(data).find('list').each(function(row) {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
//row is the index, starting at 0

Categories