how to put search results inside a div using ajax - javascript

the idea is, I want to put my search results from mysql inside "result_div" without reloading the whole page using ajax. thank you.
<button class="btn btn-default" id = "search_jo" >
<?php
if(isset($_POST['search_jo'])){
?>
<div class="panel-body" id = "result_div">
<?php
$sql = "some sql statement here";
$retval = mysql_query( $sql, $db_conn);
while($row = mysql_fetch_array($retval, MYSQLI_ASSOC))
{
// php echo statement here fecthing data from sql
}
mysql_free_result($result);
?>
</div>
<?php
}
?>

try this w3school code
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>

Related

Validating form from ajax call with php

I have a farm that loads when an option is seleceted with ajax call, however i want to validate my form, immediately when i submit, it and there is error upon validation, the ajax called form dissapears.
This is my ajax
<script>
function salesType(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint2").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","showsalestype.php?&q="+str,true);
xmlhttp.send();
e.preventDefault();
}
}
</script>
my php
$q = $_GET['q'];
if($q == 'POS'){ ?>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">POS Referece No <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="atmref" name="atmref" class="form-control col-md-7 col-xs-12" type="text" value=" ">
</div>
<p><font size="2" color="#ff0000"> <?php echo $form->error("atmref"); ?> </font></p>
</div>
<?php } ?>
How do i prevent the ajax call to remain upon validation error

ajax http request without form reload?

I am having problem with form onsubmit().
I do not want to reload page and only want to pass 2 parameter to another php.
<script type="text/javascript">
function doSomething() {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("addCategory").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","/api/add_item_main_category.php?q1="+document.getElementById("myText1").value+"&q2="+document.getElementById("myText2").value,false); ///* Tested with true */
xmlhttp.send();
return false;
}
</script>
Here is my Form.
<form href="JavaScript:void(0);" onsubmit="return doSomething(); ">
<input type="text" id="myText1" name="maincategory" placeholder="Main Category" style="width: 100%;">
<input type="text" id="myText2" name="subcategory" placeholder="Sub Category" style="width: 100%;">
<br/>
<input type="submit" name="submit" value="Add Main Category">
<br/>
<div id="addCategory" ></div>
</form>
Submit button works on like this url "/api/add_item_main_category.php?q1=Car&q2=Toyota". Not working with user input just like above form and it redirected.

Questions on PHP,MYSQL,AJAX

I have encountered a problem, where I planned to get values with javascript which is from mysql.
What I am trying to do is, when you load a PHP page to edit info, you add a div using javascript, there will be a bunch of types to choose from, But I would like to do it through retrieve from database. But it seems doesn't work, so I went on with another type of code.
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$mysql_server_name="localhost";
$mysql_username ="root";
$mysql_password ="root";
$mysql_database ="master_db";
$conn =mysql_connect($mysql_server_name,$mysql_username,$mysql_password);
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database,$conn);
$sql="SELECT * FROM `bopl_certification_type`";
$result = mysql_query($sql);
echo "<div class='span6 form-horizontal'><i class='icon-remove' onclick='removeDiv(this)'></i><div class='control-group'><label class='control- label'>Certificate Name: </label><div class='controls'><select style='width:250px' name='certType[]'>";
//To get option
while($row = mysql_fetch_array($result)) {
echo "<option value=$row[certName]>$row[certName]</option>";
}
//End of option
echo "</select><input type='text' class='input-xlarge' name='test' style='width:235px' name='fileInServ[]' readonly='readonly' /><input type='file' name='docupload[]' /></div><div class='control-group'><label class='control-label'>Issue date: </label><div class='controls'><input type='text' id='datepickerIs' name='certIsDate[]' placeholder='dd-mm-yyyy' class='comboDate' /></div></div><div class='control-group'><label class='control-label'>Expired date: </label><div class='controls'><input type='text' id='datepickerEx' name='certExDate[]' placeholder='dd-mm-yyyy' class='comboDate' /></div></div> </div>";
?>
</body>
</html>
That was the getuser.php and this is the index.html
<html>
<head>
<script>
function showUser() {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onclick="showUser()">
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
This is the proper result that I wanted. But it seems that I tried to integrate into my existing codes. It doesn't work at all. Is there any other way around it?
First I would create a function for your server calls to simplify things. This is the one that i use but it uses the main thread so if you want it to be async then you will have to add on readystatechange and change true to false on the initial declaration however, this is my function for retrieving.
function httpGet(theUrl){
//FETCH Data From Server
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", theUrl , false );
xmlhttp.send();
return xmlhttp.responseText;
}
Then from anywhere in your script you can call
document.getElementById("txtHint").innerHTML = httpGet("getUser.php");
now for any additional help we really need to know, what errors your receiving.

cant get ajax get to show in page but can see in google element inspector

I am making a simple invoice page. I populate a dropdown box from mysql and when I check the item i want the description box to prepopulate. But its not working....i can see it in the network inspector on chrome and preview it. my code as follows htmlinputform, php, ajaxget
<div class="row">
<div class="col-md-2">
<select type="text" name='idd' id="inputItem" placeholder="Item #1" class="form-control" onblur="showUser(this.value)">
<option></option>
<?php
require ('dbconnect.php');
$result = $con->query("select id, item from items");
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['item'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
mysqli_close($con);
?>
</div>
<div class="col-md-6">
<input type="text" id="description1" placeholder="Description" class="form-control" onchange="1description()"></div>
<div class="col-md-1">
<input type="text" id="qty1" placeholder="Qty." class="form-control"></div>
<div class="col-md-1">
<input type="text" id="tax1" placeholder="Tax" class="form-control"></div>
<div class="col-md-2">
<input type="text" id="itemprice1" placeholder="Item Total" class="form-control" onchange="myFunction()" onblur="myFunction1()"></div>
</div>
php
<?php
$q = intval($_GET['q']);
require ('dbconnect.php');
mysqli_select_db($con,"items");
$sql="SELECT description FROM items WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['description'];
}
mysqli_close($con);
?>
AJAX
<script>
function showUser(str) {
if (str=="") {
document.getElementById("description1").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("description1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
Use .value instead of innerHTML. innerHTML is not used for input fields.
document.getElementById("description1").value =xmlhttp.responseText

How to populate a response in the same div, which was populated as ajax

I have a html page
say main.php, which populates "upload.php" in div using ajax.
Now in this upload.php, I upload an image, and I want to somehow, make this div in main.php to show me the response of image load success or not.
my code is shown below:
The main.php
<script type="text/javascript">
function showHint()
{
var str = document.form1.filenumber.value;
if (str.length==0)
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","upload.php?filenumber="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="form1" >
<tr>
<td>File Number </td><td><input type="text" id="11" name="filenumber" /></td>
</form>
<td colspan="2"><input type="submit" onclick='showHint()'></td>
</tr>
</table>
<div id="txtHint"></div>
And the upload.php
<?php
$filenumber = clean($_GET['filenumber']);
if($filenumber != '') {
$qry = "SELECT * FROM profile WHERE filenum='$filenumber'";
$result = mysql_query($qry)
or die(mysql_error());
$row = mysql_fetch_array( $result );
if($result) {
if(mysql_num_rows($result) == 0) {
$errmsg = '<div style="width:300px; height:100px;color:red;margin:0px auto;position:relative;top: 30%">No such record found. Redirecting back to the status page. </p>';
$errflag = true;
}
else
{
?>
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
<?php
}
//#mysql_free_result($result);
}
else {
die("Query111 failed");
}
}
?>
And the upload.php calls for uploader.php, whose response I want to show in the same div
<?php
$target = "images/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
You suggestion are most welcome and your help is appreciated.
Thanks
Zee
As GolezTrol mentioned, you should consider using JQuery, it makes working with AJAX a lot easier.
To answer your question, you could use a JSON encoded response to be able to seperate information about the result of the uploading process and the real result you want to fill your div with.

Categories

Resources