Get MYSQL Data Into AJAX - php

I'm an AJAX novice and I'm having major trouble trying to get data out of mySQL and into my javascript function.
What I want to do is loop through my data in php and somehow send that data into various named divs on the page.
Here's the code from my javascript page:
function loadPageContent(){
var projectID = getQuerystring('pid');
var templateID = getQuerystring('t');
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var url="getImages.php"
url=url+"?projectID="+projectID
url=url+"&templateID="+templateID
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("statusdebug1").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
Here's the code for my php page:
<?php
$projectID = $_GET["projectID"];
$templateID = $_GET["templateID"];
include_once('includes/php/conn.php');
$sql ="select * FROM imageSel WHERE projectID='$projectID' AND templateName = '$templateID'";
$results=mysql_query($sql, $link);
if(!($mysql_rs = mysql_query($sql, $link)))
die("Error in executing query");
echo "<script language='JavaScript'>";
while($row =mysql_fetch_assoc($results) ){
$imageSelID = $row['imageSelID'];
$templateName = $row['templateName'];
$tNode = $row['box'];
$image = $row['image'];
$sql2 ="select * FROM products WHERE productid='$image'";
if(!($mysql_rs = mysql_query($sql2, $link)))
die("Error in executing query");
//Retrieve values
$row2 = mysql_fetch_array($mysql_rs);
$productname = $row2['productname'];
$subcategoryid = $row2['subcategoryid'];
$sql3 ="select * FROM subcategory WHERE subcategoryid='$subcategoryid'";
if(!($mysql_rs = mysql_query($sql3, $link)))
die("Error in executing query");
//Retrieve values
$row3 = mysql_fetch_array($mysql_rs);
$foldername = $row3['foldername'];
$foldername = strtolower($foldername);
$theImage = '<img src="images/lowres/' . $foldername . '/' . $productname .'" />';
echo "document.getElementById(".$tNode.").innerHTML=".$theImage.";";
}
echo "</script>";
?>

That's typically not how I would implement AJAX.
AJAX, when done correctly, should send data to the browser, then let the browser decide what to do with it.
Try using json_encode to put the data you want to send to the browser in JSON format, then on the Javascript end use a JSON library to decode the data then handle it appropriately.
Good luck!

please use this code :
xmlHttp.open("GET",url,false);
because if you are keeping its true then it will call asynchronize ajax.
Please correct if i am wrong.

You are setting the Ajax response to the innerHTML of the div. But you output javascript in your PHP (which becomes your Ajax response). Try outputting just the img tag without the javascript wrapper. Or, even just outputting "Hello world";
EDITED TO ADD: You're using javascript getElementById and innerHtml on the client side and the server side. It's redundant. You probably want to keep it on the client side, ie, your html and javascript

Related

How to fetch data and pass. into form and response customername onkeyup or keydown json and php

This is Mysql DB connection.php
<?php
$conn = new mysqli("localhost", 'root', "", "laravel");
$query = mysqli_query($conn,"select * from customers");
while ($result2=mysqli_fetch_assoc($query)) {
$data[] = $result2['customername'];
}
echo json_encode($data);
?>
The json is not responding onKeyup or keydown it is displaying the whole output. But i want to display only the current related matched names on to display. I was new to json and ajax. i think ajax and json both respond the same.
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "connection.php?q="+str, true);
xhttp.send();
}
</script>
Thanks for your suggestions. All suggestions are welcome.
How pass into form and response on keyup or keydown and related suggestions customername should display down. I am new to JSON and javascript and examples sites. Thanks in advance. All suggestions are welcome.
You have a couple of options;
One is that you re-pull all the data in an ajax call by appending the text box input to the SQL query in a "WHERE name LIKE %" . $input . "%'"; but this will be costly in terms of speed an network traffic.
Another option and the one I would opt for, is getting all of the names in a SELECT as you have done, then using RegEx within javascript to filter the results shown.
Here is a good link on using regular expressions.
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Edit:
None of this is tested as I don't have the means to test right now.
For the first example, I am going to assume you are passing the query via the GET and thus in your PHP file you change your code to as follows:
<?php
// Your DB connection
$conn = new mysqli("localhost", 'root', "", "laravel");
// Initialise the query string
$qString = "SELECT * FROM customers";
// Providing a parameter is sent in the GET request to the PHP page, look for names
// containing that string
isset($_GET['q']) ? $qString .= " WHERE customername LIKE '%" . $_GET['q'] . "%'" : "";
$qHandler = mysqli_query($conn, $qString);
while ($qResult = mysqli_fetch_assoc($qHandler)) {
$data[] = $qResult['customername'];
}
echo json_encode($data);
?>
So when a request is made via call of showHint(str) it will append that str to the query in a 'like' statement, with the %% wildcards. So you put 'art' in the text box, it will return names like 'bART', 'mARTher', etc.

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

Ajax auto update not updating

Hello I'm working on a shoutbox and I need help with auto updating them via ajax.
Here is my shoutbox with ?getShouts=true at the end:
Here is my shoutbox without that:
My goal here is to run a web request and get the contents of the shoutbox in ?getShouts and update on the page I'm in.
This PHP code is run on the top of the page:
if(!empty($_GET['getShouts']))
{
$sbinfo = "";
$rows = $db->query("SELECT * FROM shouts order by shoutid DESC limit 20");
while($row = $rows->fetch_array(MYSQL_ASSOC))
$sbinfo .= $row['username'] . ": " . $row['shout'] . "<br />";
}
That stores the markup for the text into one string.
later in php file it displays the markup by: if(!empty($_GET['getShouts'])) echo $markup;
Here is my ajax I'm currently running:
<script>
$(document).ready(function() {
getMessages();
});
function getMessages()
{
//make request
var req = new XMLHttpRequest();
req.open("GET", location.href+"?getShouts=true", true);
req.send(null);
document.getElementById("shouts-box").innerHTML = req.responseXML.getElementsById("shouts-box")[0].innerHTML;
//loop
window.setInterval(getMessages,3000);
}
</script>
any ideas?
I have found a solution for this using:
$('#div').load('index.php?getShouts=true #div');

No response from PHP code using jQuery post()

I am trying to retrieve data from a PHP file the reads a mySQL db. The data comes in fine on a browser:
http://www.primaryaccess.org/REST/geteasyfile.php?id=25
But when I try to access it using jQuery's get() or post() methods, I get no response. The response header in Firebug says there is the right amount of data, but nothing shows up:
$.get("http://www.primaryaccess.org/REST/geteasyfile.php?id=25",function(data) { alert(data); });
Here's the PHP:
<?
$id=$_GET['id'];
$query="SELECT * FROM easyfile WHERE id = '$id'";
$result=mysql_query($query);
mysql_close();
if (($result == false) || (!mysql_numrows($result)))
echo "Can't load file!";
else
echo mysql_result($result,0,"data");
?>
Thanks!
Bill
Try getJSON and replace alert() with console.log(). Additionally, your URL looks strange ('id=25' + id). I hope you also noticed that there is a Same Origin Policy in JS, so you need to upload your testfile to the specified domain.
probably your problem is in the url, you already setted id=25 and then you concatenate the id variable
Hope this help
Try using a json callback
JS
$.ajax({
url: "http://www.primaryaccess.org/REST/geteasyfile.php?id=25&jsoncallback=?",
success: function(data) {
alert(data)
},
error: function(error){
alert(JSON.stringify(error));
}
});
PHP
<?
$id=$_GET['id'];
$query="SELECT * FROM easyfile WHERE id = '$id'";
$result=mysql_query($query);
mysql_close();
if (($result == false) || (!mysql_numrows($result)))
$result = "Can't load file!";
else
$result = mysql_result($result,0,"data");
$result = array('result' => $result);
echo $_GET['jsoncallback'] . '(' . json_encode($result) . ');'
?>

How to receive data from a database using AJAX

I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.

Categories