I recently found a cool tabbed content page, where when you click on the tabs they show content http://codepen.io/unasAquila/pen/nDjgI What I discovered was, that these tabs were preloaded once you enter the page, rather than being loaded as the tabs are clicked on. I was wondering if it is possible to make it to where the content loads as you click on the tab. For example, If I have a PHP Query statement where I want to load information such as this:
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
while($row = mysqli_fetch_array($query3))
{
echo "$row[name]
}
How would I make it to where the content is only loaded once the tab is clicked on?
It can be done using AJAX. Simply put, AJAX is a technology that allows sending requests to the back-end when an event triggers on the front-end.
You could make the following:
In your HTML:
<!-- Change myTabId to whatever id you want to send to the server side -->
<element onclick="loadTab(myTabId)">my tab</element>
In your JS:
// Will be executed on tab click
function loadTab(tabId) {
var xmlhttp = new XMLHttpRequest();
// Define a handler for what to do when a reply arrives from the server
// This function will not be executed on tab click
xmlhttp.onreadystatechange = function() {
// What to do with server response goes inside this if block
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Change the content of the element with id "myTabContent" to the server reply
document.getElementById("myTabContent").innerHTML = xmlhttp.responseText;
}
}
// Opens a connection to "myServerSideScript.php" on the server
xmlhttp.open("GET", "myServerSideScript.php?id=" + tabId, true);
xmlhttp.send();
}
Now you need to create myServerSideScript.php on the server root with a content similar to the following:
$id = $GET[id]; //The GET parameter we sent with AJAX
$query3 = $db->query("SELECT * FROM mybb_game WHERE id='" . $id . "'");
$response = "";
while ($row = mysqli_fetch_array($query3)){
$response .= $row[name];
}
// To return a reply you just need to print it
// And it will be assigned to xmlhttp.responseText on the client side
echo $response;
You can learn more about AJAX here
Related
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.
At the moment, everything is working fine with the script, I insert data in my database, I refresh and I get the username with the new message. However I'm trying to figure out how to have the message added onto the page as soon as the database is updated without having to refresh.
Simple HTML, Here's where the messages load up
<div id="msg">
</div>
Whenever the page is done loading, I'm calling AJAX to get the data
<script type="text/javascript">
$(function(){
//AJAX
var hr = new XMLHttpRequest();
var url = "exampleclass.php";
var msg = document.getElementById("msg");
hr.onreadystatechange=function()
{
if (hr.readyState==4 && hr.status==200)
{
document.getElementById("msg").innerHTML=hr.responseText;
}
}
hr.open("GET", url, true);
hr.send();
});
</script>
Here is my PHP form that retrieves data
<?php
include('inc/connect.php');
$query = "SELECT message, user_name "
. "FROM chat "
. "WHERE (user_name='bryan' or user_name='derek') "
. "AND (user_to='derek' or user_to='bryan')";
while ($retrievedata = mysql_fetch_assoc($sql)){
echo $retrievedata['user_name'].": ".$retrievedata['message']."<br/>";
}
?>
I have created an YouTube search engine that sends video id, title etc. using session. I have created buttons with unique ids for each of them, onclicking which a page is called via ajax and the session is generated using the unique id for that button.
The javascript code is like follows:
<script type="text/javascript">
function loadXMLSession(videoid, videotitle) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "GenerateDownloadSession.php?videoid=" + videoid + "&videotitle=" + videotitle, true);
xmlhttp.send();
//strip off spaces and embed dashes - clean urls
var downloadtitle = videotitle;
downloadtitle = downloadtitle.toLowerCase();
downloadtitle = downloadtitle.replace("-"," ");//strip off dashes with spaces
downloadtitle = downloadtitle.replace(/ +(?= )/g,'');//replace multiple spaces with one space
downloadtitle = downloadtitle.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');//strip off all special characters from video title
downloadtitle = downloadtitle.replace(/ /g,"-");//replace spaces with dashes
downloadtitle = downloadtitle.replace(/-+$|(-)+/g, '$1');//replace multiple dashes with single dash
var url = window.location.hostname;
url = "/development"//only for development phase
url = url+"/download/"+downloadtitle+".html";
window.location=url;
}
</script>
The download buttons are coded as follows:
echo "<button id=\"downloadbtn\" class=\"btn\" value = \"" . $YouTubeVideoID . "\" onclick=\"loadXMLSession(this.value,'" . $VideoContent['6'] . "')\"><img src=\"" . $HostURLRedirect . "/img/Arrow-Down-icon.png\" alt=\"download\" /> Download</button> ";
The php page called by ajax has simple session creation:
session_start();
$videoid = $_GET['videoid'];
$videotitle = $_GET['videotitle'];
$_SESSION['DownloadID'] = $videoid;
$_SESSION['DownloadTitle'] = $videotitle;
$_SESSION['DownloadType'] = "Download";
The problem that I am having is, when I click on any of the download button for the first time after opening the browser, it is working well. But when I search again, it is returning the previous session values. I am calling the session function through ajax and passing values to it. And, it should overwrite the session values. But in this case, it is not overwriting the values. How can I overcome this issue? Any suggestions?
At
xmlhttp.open("GET", "GenerateDownloadSession.php?videoid=" + videoid + "&videotitle=" + videotitle, true);
xmlhttp.send();
you are doing an asynchronous Request, which means, that the javascript continues after sending the request, not waiting for it to complete. Most likely it will hit your redirect of your current page to the download before the call could change the Session data.
Solution 1.) Make the script synchronous by setting the last parameter to false.
Solution 2.) Move your forward logic into the onreadystatechange callback function.
on a side node: why using ajax for this? you could simple pass the parameters appended to the url when forwarding...?
Do you have the GET-Values set when requesting your Script?
Use your Firebug to check what is answered by the PHP-Script. (Network -> you will see the requested file being loaded when your Ajax Request is being started).
you should change the location of you page once you get the ajax response:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var downloadtitle = videotitle;
downloadtitle = downloadtitle.toLowerCase();
downloadtitle = downloadtitle.replace("-"," ");//strip off dashes with spaces
downloadtitle = downloadtitle.replace(/ +(?= )/g,'');//replace multiple spaces with one space
downloadtitle = downloadtitle.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');//strip off all special characters from video title
downloadtitle = downloadtitle.replace(/ /g,"-");//replace spaces with dashes
downloadtitle = downloadtitle.replace(/-+$|(-)+/g, '$1');//replace multiple dashes with single dash
var url = window.location.hostname;
url = "/development"//only for development phase
url = url+"/download/"+downloadtitle+".html";
window.location=url;
}
}
But I most be honest, I dont see the point of using ajax and then changing the location of the actual page.
Maybe you should start the download in another window?
I have written a simple application that displays a list of candidates for a job, then, upon clicking a hire button, should alter a database to reflect the newly hired candidate and display the rest as unhired. However, the function is not working properly. The problem I am having is the AJAX function never seems to provide a response, and I cannot figure out why. The database is also not getting updated. My files are below.
The line document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; is updating a div at the bottom of my html page, showing that the the readyState is 4 and the status is 200, which should mean that the AJAX function returned properly, but the echo'd response is not being displayed. Even when I remove all code from the new_hire.php file and simply make the file echo "hello";, nothing is returned in the responseText.
resumes.php:
<html>
<head>
<script type="text/javascript">
function new_hire(name){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";
//this line, when removed, does not change anything. I left it in for debugging purposes.
document.getElementById("errors").innerHTML+=xmlhttp.responseText;
if (xmlhttp.readyState=4 && xmlhttp.status=200){
var others = xmlhttp.responseText.split("|");
for (i=0;i<others.length;i++){
tag = others[i].replace(" ","_");
document.getElementById(tag).innerHTML="";
}
}
}
xmlhttp.open("POST","new_hire.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople");
var name_tag = name.replace(" ","_");
document.getElementById(name_tag).innerHTML="(Current Employee)<br>";
}
</script>
</head>
...
</html>
new_hire.php (AJAX response file):
<?php
$hiree = $_POST['hiree'];
$pos = $_POST['position'];
$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error());
mysql_select_db("dbname",$con);
$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;");
mysql_fetch_array($clear);
$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';");
mysql_fetch_array($reset);
$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;");
$array = array();
while ($row = mysql_fetch_array($people)){
array_push($array,$row['Name']);
}
mysql_close($con);
$response = join("|",$array);
echo $response;
?>
Please note that your if statement is not using the comparison operator == but rather the assignment operator = so you are using: if (xmlhttp.readyState=4 && xmlhttp.status=200) instead of if (xmlhttp.readyState==4 && xmlhttp.status==200)
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