UPDATE... this is the code I've implemented from the tutorial, within chrome dev tools in network i can see in header the variable is being sent and in preview i can see the drop down menu however it is not inserted into the loaded webpage
<script type="text/javascript">
$(document).ready(function() {
$('#selectEvidence').change(function(){
alert($(this).val());
});
});
function evidencesearch(str)
{
if (str=="")
{
document.getElementById("case").innerHTML="";
return;
}
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("case").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","searchfunction.php?variable="+str,true);
xmlhttp.send();
}
</script>
<?php
$variable = $_GET['variable']; //used for second drop down menu
//echo "test test test $variable";
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<label class="input" for="case" type="input">Specify: </label><select id="case" name="case"><option=value"null"></option>'; //Insert to loaded page
$resource = mysql_query("SELECT $variable FROM `evidence`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row[$variable].'">'.$row[$variable].'</option></select>';//Insert to loaded page
}
}
mysql_close($conn)
?>
I think your problem sticks within POST/GET functions; try to call them synchronously and paste please the w3schools tutorial's link you mentioned. Maybe I can help you then by writing more detailed answer.
Cheers.
Related
Hi I need to load a url inside to a div tag using Ajax. This is the code I used.
function loadXMLDoc()
{
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("Loading_Page").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","UserTypesPHP.php",true);
xmlhttp.send();
}
And this is how my UserTypesPHP.php looks like.
<?php
// Create connection
include('connectionPHP.php');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Adding Student records
if (!empty($_POST['UserTypeSubmit'])){
$sqlstu1="INSERT INTO user_type(User_ID ,User_Name) VALUES('$_POST[UserTypeID]','$_POST[UserType]')";
if (!mysqli_query($con,$sqlstu1))
{
die("<script>alert( \"Error: ". mysqli_error($con)."\");window.location.href='AdminUser.php';</script>");
}
else
echo "<script>alert ('The lecture was recorded successfully');
window.location.href=' AdminUser.php';
</script>";
}
mysqli_close($con);
?>
Im trying to redirect AdminUser.php to Loading_Page div. But this doesn't work out as expect. Please someone let me know the reason.
Thank you in advance.
function loadXMLDoc()
{
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)
{
if(xmlhttp.responseText == 'success'){
response();
}
//document.getElementById("Loading_Page").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","UserTypesPHP.php",true);
xmlhttp.send();
}
function response(){
alert ('The lecture was recorded successfully');
window.location.href=' AdminUser.php';
}
And on the php file:
<?php
// Create connection
include('connectionPHP.php');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Adding Student records
if (!empty($_POST['UserTypeSubmit'])){
$sqlstu1="INSERT INTO user_type(User_ID ,User_Name) VALUES('$_POST[UserTypeID]','$_POST[UserType]')";
if (!mysqli_query($con,$sqlstu1))
{
die("<script>alert( \"Error: ". mysqli_error($con)."\");window.location.href='AdminUser.php';</script>");
}
else
echo "success";
}
mysqli_close($con);
?>
Here's a simple solution. It assumes that if the response contains <script>, the entire response is a script -- it doesn't try to parse the script out of other HTML.
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (/<script>/.test(xmlhttp.responseText)) {
var script = document.createElement('script');
script.appendChild(document.createTextNode(xmlhttp.responseText.replace(/<\/?script.*?>/g, '')));
document.getElementByTagName("head").item(0).appendChild(script);
} else {
document.getElementById("Loading_Page").innerHTML = xmlhttp.responseText;
}
}
}
I'm sure there's an easy answer to this but I've looked everywhere and can't seem to find an answer. I have a dropdown box at the start of a form for office names being populated from an sql table. Depending on which office the user selects, I want the other fields to be filled out with the corresponding information for that record. I used the w3schools php ajax database page as a my guide but it only shows how to update one id in the page and I need to update the input field for address, city, state, zip, and contact.
Here's the relevant code which isn't working. The Code for to trigger the script for the dropdown:
<select name="users" onchange="showOffice(this.value)" class="field select" tabindex="1" >
The Script on that page:
<script>
function showOffice(str)
{
if (str=="")
{
document.getElementById("practice_name").innerHTML="";
document.getElementById("contact").innerHTML="";
document.getElementById("address").innerHTML="";
document.getElementById("city").innerHTML="";
document.getElementById("state").innerHTML="";
document.getElementById("zip").innerHTML="";
return;
}
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("practice_name").innerHTML=xmlhttp.practice_name;
document.getElementById("contact").innerHTML=xmlhttp.contact;
document.getElementById("address").innerHTML=xmlhttp.address;
document.getElementById("city").innerHTML=xmlhttp.city;
document.getElementById("state").innerHTML=xmlhttp.state;
document.getElementById("zip").innerHTML=xmlhttp.zip;
}
}
xmlhttp.open("GET","getoffice.php?q="+str,true);
xmlhttp.send();
}
</script>
And then my getoffice.php code:
<?php
$q=$_GET["q"];
$host="********"; // Host name
$db_username="******"; // Mysql username
$db_password="******"; // Mysql password
// Connect to server and select database.
$con = mysqli_connect("$host", "$db_username", "$db_password");
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"*****");
$sql="SELECT * FROM initial_practice WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
$row=mysql_fetch_array($result);
?>
var practice_name = <? echo $row['practice_name']; ?>
var contact = <? echo $row['contact']; ?>
var address = <? echo $row['address']; ?>
var city = <? echo $row['city']; ?>
var state = <? echo $row['state']; ?>
var zip = <? echo $row['zip']; ?>
<?
mysqli_close($con);
?>
Any help would be greatly appreciated.
Your problem is you aren't using the response text back correctly. This can be fixed in a couple steps. The AJAX request pulls back everything that is printed out from getoffice.php.
First
We're gonna want to change these lines on the on-page script from this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("practice_name").innerHTML=xmlhttp.practice_name;
document.getElementById("contact").innerHTML=xmlhttp.contact;
document.getElementById("address").innerHTML=xmlhttp.address;
document.getElementById("city").innerHTML=xmlhttp.city;
document.getElementById("state").innerHTML=xmlhttp.state;
document.getElementById("zip").innerHTML=xmlhttp.zip;
}
}
To something a bit easier (I tend to separate readyState and status if statements, my delusional belief that it can randomly fail when combined):
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if(xmlhttp.status==200)
{
eval(xmlhttp.responseText);
}
}
};
Now we're simply evaluating all we get back from the request. Also, note that I added a semi-colon to the end of the onreadystatechange function.
Second
Change the following lines in getoffice.php from:
var practice_name = <? echo $row['practice_name']; ?>
var contact = <? echo $row['contact']; ?>
var address = <? echo $row['address']; ?>
var city = <? echo $row['city']; ?>
var state = <? echo $row['state']; ?>
var zip = <? echo $row['zip']; ?>
To:
document.initialpractice.practice_name.value = <?php echo $row['practice_name']; ?>
document.initialpractice.contact.value = <?php echo $row['contact']; ?>;
document.initialpractice.address.value = <?php echo $row['address']; ?>;
document.initialpractice.city.value = <?php echo $row['city']; ?>;
document.initialpractice.state.value = <?php echo $row['state']; ?>;
document.initialpractice.zip.value = <?php echo $row['zip']; ?>;
Now, when we get the response back from the server, the javascript will evaluate the above response appropriately and fill in the fields. At least it should, providing the query doesn't fail.
Also, you can change mysqli_fetch_array() to mysqli_fetch_assoc(), since you only need the associative array.
Note: We could have solved the problem by just adding eval(xmlhttp.responseText); below the readyState/status checks and removing xmlhttp. in front of all the innerHTML variables.
Finally figured it out. For any of you having the same trouble here's a fix.
php code:
$row=mysqli_fetch_assoc($result);
$name = $row['practice_name'];
$contact = $row['contact_name'];
$address = $row['address'];
$city = $row['city'];
$state = $row['state'];
$zip = $row['zip'];
echo $name."#".$contact."#".$address."#".$city."#".$state."#".$zip;
On-page Script:
function showOffice(str)
{
if (str=="")
{
document.getElementById("practice_name").innerHTML="";
document.getElementById("contact").innerHTML="";
document.getElementById("address").innerHTML="";
document.getElementById("city").innerHTML="";
document.getElementById("state").innerHTML="";
document.getElementById("zip").innerHTML="";
return;
}
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)
{
if(xmlhttp.status==200)
{
var data = xmlhttp.responseText.split("#");
var name = decodeURIComponent(data[0]);
var contact = decodeURIComponent(data[1]);
var address = decodeURIComponent(data[2]);
var city = decodeURIComponent(data[3]);
var state = decodeURIComponent(data[4]);
var zip = decodeURIComponent(data[5]);
document.initialpractice.practice_name.value = name;
document.initialpractice.contact.value = contact;
document.initialpractice.address.value = address;
document.initialpractice.city.value = city;
document.initialpractice.state.value = state;
document.initialpractice.zip.value = zip;
}
}
};
xmlhttp.open("GET","getoffice.php?q="+str,true);
xmlhttp.send();
}
</script>
instead of populating the "tempDiv" in html, the print.php is loaded showing the content. The same code is working for other files and javascript functions. :/
HTML:
<li><a class="button black" href="#searchbox" onclick="viewall()" >View All</a></li>
<li><button class="button black" type="submit" form="selectcol" onclick="printDiv()"></button></li>
<div id="searchresults" style="padding-top:30px; padding-bottom:10px; max-height:280px; ">
The results will show up here..!!
</div>
<div id="tempDiv"></div>
The viewall() function :
function viewall(){
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("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "viewall.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
}
The printDiv() function called to print the selected columns:
function printDiv()
{
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("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "print.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("tempDiv").innerHTML = xmlhttp.responseText;
}
}
}
PHP :
<?php
$col = $_POST['print'];
$flds = "";
foreach($col as $value){
if(isset($col)){
if($flds !="")
$flds .= ",";
$flds .= $value;
}
}
$sql = "SELECT ". $flds." from student";
$con = mysqli_connect("localhost", "root", "","university") or die("could not connect". mysqli_error($con));
$rs = mysqli_query($con, $sql);
echo "<table border='1'";
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='searchtabledata'>".$r[0]."</td>";
echo "<td class='searchtabledata'>".$r[1]."</td>";
echo "</tr>";
}
?>
the result i get on clicking the submit button
Shouldn't you define the readystate function before sending the request?
part 2. It looks like your printdiv function submits a form. You should be able to remove the form tags if you are using a strictly AJAX procedure. You'll need to adjust a few other things to make that work.
For some reason \u009a is being sent to the xmlhttp.responseText and not \u0161, and I'm not sure why. I want ลก to be displayed in the textbox, but, instead, the single character introducer is being sent instead. Any ideas how I can fix this?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
document.getElementById("textbox3").value=a.third;
document.getElementById("textbox4").value=a.fourth;
document.getElementById("textbox5").value=a.fifth;
document.getElementById("textbox6").value=a.sixth;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
header("Content-type: application/json");
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
$textboxValue5 = $queryResult[4];
$textboxValue6 = $queryResult[5];
echo json_encode(array('first'=>utf8_encode($textboxValue),'second'=>
utf8_encode($textboxValue2),'third'=>utf8_encode($textboxValue3),'fourth'=>
utf8_encode($textboxValue4),'fifth'=>utf8_encode($textboxValue5),'sixth'=>
utf8_encode($textboxValue6)));
?>
Adding in the line $mysql->query("SET CHARACTER SET 'utf8'"); inside loadTextBox.php after connecting to the DB and before the SQL query and removing the lines with utf8_encode fixed it.
I keep getting an unexpected character error in the console for the line
var a = JSON.parse(xmlhttp.responseText);
and I'm not sure why. Could this be why my textboxes aren't populating with the parsed data?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").innerHTML=a.first;
document.getElementById("textbox2").innerHTML=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
Your loadTextBox.php file should not contain any HTML because the JSON.parse method expects only JSON:
<?php
header("Content-type: application/json");
$db_username = placeholder;
$db_password = placeholder;
$db_host = placeholder;
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
If your DB login info is in a separate file, then there should be no HTML or BODY tags only the PHP tags.