Ajax Mysql Query - javascript

I am propably being a complete idiot and not seeing the big picture here. I am trying to write a little ajax thingie that would pull information from a database but i cant seem to get the thing going ... please tell me what i am doing wrong.
I put the code together by following a couple of online tutorials and i am no ajax genius. my ajax skills could propably start the next world war.
Here is my code. please feel free to tell me im an idiot if i missed something small.
<html>
<head>
<script>
function showDetail(str) {
if (str=="") {
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","process.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Wallet Number : <input type="text" name="wallet01" id="wallet01" />
<br />
<input type="submit" id="submit" name="submit" onsubmit="showDetail(wallet01)">
</form>
<br>
<div id="txtHint"><b>Kit info will be listed here.</b></div>
</body>
</html>
and here is my php
<?php
$q = $_GET['q'];
$con = mysqli_connect('10.1.75.131','markdv','qwerty123','MTNAutomation');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"MTNAutomation");
$sql="SELECT serialNumber FROM Kit_T WHERE serialNumber = '$q'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Wallet Number</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['serialNumber'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

There is an error in your HTML. You put 'onsubmit="showDetail(wallet01)"', but 'wallet01' is not a javascript variable.
I would suggest changing it to this:
<form onsubmit="return showDetail()">
Wallet Number : <input type="text" name="wallet01" id="wallet01" />
<br />
<input type="submit" id="submit" name="submit">
</form>
I added the "onsubmit" in the form, using the function with "return", to prevent the default submit from form. But remember to always return false in the function.
Than in the function you can get the value for the field.
function showDetail() {
var str = document.getElementById('wallet01').value;
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return false;
}
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","process.php?q="+str,true);
xmlhttp.send();
return false;
}
Or you can use the ajax from jQuery, it's easier.
See an example here
function showDetail() {
var str = $('#wallet01').val();
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return false;
}
var jqxhr = $.ajax( {
url: "example.php",
type: "GET",
data: {q: str}
}).done(function(data, textStatus, jqXHR ) {
alert( "success" );
}).fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
}).always(function( ) {
alert( "complete" );
});
return false;
}
See the JQuery Ajax docs
You also have the function "beforeSend" to start a gif "loading".

Related

Ajax/PHP - autocomplete value not recognised

I am using this example to run an ajax data query from an mysql db, that returns a table.
This is working fine when text is manually typed into this input form eg:
But the search form has an autocomplete jquery script that will help the user along. When a value is chosen from the dropdown autocomplete values, the onchange event isn't recognized, no table shows.
My question is, how would I put a button at the end of the search form, to change this to 'onclick' event, rather than 'onchange'? The hurdle I am facing is that the input for 'client_address' is part of a larger form, and clicking submit on any button causes the page to try submit the entire form.
create_wt.php:
// autocomplete
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php'
});
});
</script>
// retrieve data in table
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<div class="form-group <?php echo (!empty($client_address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<div class = "input-group">
<input id="clientsearch" type="text" name="client_address" onchange="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
<!---<span class="input-group-btn">
<button class="btn btn-success" value="submit" id="ajaxbtn" type="submit">Get Client Info</button>
</span> -->
</div>
<br><div id="txtHint"><b>Person info will be listed here...</b></div>
<span class="help-block"><?php echo $client_address_err;?></span>
</div>
ajax_get_client_info.php:
<?php
require_once 'config.php';
$q = trim($_GET['q']);
$query = $mysqli->query("SELECT * FROM client WHERE client_address LIKE '%".$q."%'");
//$data = array();
//while ($row = $query->fetch_assoc()) {
// $data[] = ($row);
//}
//echo json_encode($data);
echo "<table>
<tr>
<th>client_id</th>
<th>Client Name</th>
<th>Phone Number</th>
</tr>";
while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['client_id'] . "</td>";
echo "<td>" . $row['client_name'] . "</td>";
echo "<td>" . $row['client_phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
create_wt:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
select: function showUser(str) {
if (str == "") {
document.getElementById("txtHint").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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
}
{
source: 'backend_search_addressWT.php'
});
});
</script>
According to jQuery UI Autocomplete documentation:
http://api.jqueryui.com/autocomplete/#event-select
the select event of the autocomplete input does not accept the user's input as an argument but has 2 other: event, ui.
So you are trying to access the value: ui.item.value that is the selected item's value.
So that must be your problem.
CBroe has the same answer in the comments.
....
function getHint(value) {
if ((value !== "") && (typeof value !== 'undefined')) {
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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q=" + value, true);
xmlhttp.send();
return true; // return true to accept the selection of the user
} else {
document.getElementById("txtHint").innerHTML = "";
$(this).autocomplete( "close" ); // Close the autocomplete popup manual because by returning false negates the selection but it does not close the popup.
return false; // return false to negate the selection of the user
}
}
$( "#clientsearch" ).autocomplete({
select: function showUser(event, ui) {
return getHint(ui.item.value);
},
change: function showUser(event, ui) {
return getHint(ui.item.value);
},
{
source: 'http://www.example.com'
}
});
....
Be sure to read the documentation so you know how to treat this case from the start.
Hope this helps.
Change onchange in input box to onkeyup, that should solve, onchange is mainly used for radio buttons and checkboxes.
<input id="clientsearch" type="text" name="client_address" onkeyup="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
Use a input type button:
<input type="button" name="" id="">
and use its click event. Input type will not submit the form.

Ajax Error : Not return database Value

I have a problem with my ajax php coding.
The problem is when the user enter their password to login ,the live checking function output only shown blank in select box below, not the data from database.
Below is my code:
Login.php
username:<input type="text" class="name" id="uname" placeholder="enter your username here"><br>
password:<input type="password" class="pass" id="pword" placeholder="password here"><br>
<div id="txt">
responsibility:<select id="opti">
<option value=""> Select your responsibility</option>
</select><br></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txt").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("txt").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","dblogin.php?q="+str,true);
xmlhttp.send();
}
}
document.getElementById('pword').addEventListener("keyup", function(str) {
showUser(str);
}, false);
</script>
Dblogin.php
<?
$q=intval($_POST["pword"]);
require ("config.php");
$link=mysqli_connect($host,$user,$pass,$db);
$query="select responsibility from testing where password = '".$q."'";
$result=mysqli_query($link,$query);
if($result){
?>
<form>
responsibility:<select id="opti">
<?
while($row=mysqli_fetch_array($result))
echo"<option value='$row[1]'>$row[1]</option>";
?>
</select>
<input type=submit value ="submit">
<?
}
else
{
?>
Error:No Data Found
<?
}
?>
config.php
<?
$host="localhost";
$db="logindb"
$user="root"
$pass="";
?>
the ajax function is work, but the database data not shown. Can anybody tell me what wrong with my coding.

javascript is not executing inserted in inner HTML

I am trying to get the response from another page for example its name is ajaxresponse.php through ajax request and I also want to perform some actions done by java script on that ajaxresponse.php page but the js code is not working. I am getting the response from that page but the js code for that page is not working. I want to only know why ajax code on mie second page is not working?
function ajaxinput(tinnerid)
{
var xmllhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("articledive").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();
}
Here is the php code for first page
<?php
$con1=mysqli_connect("127.0.0.1","root","root","databasetry");
$result=mysqli_query($con1,"select title,articleid from article");
$tinnerid=0;
$articledivid=0;
while($row = mysqli_fetch_array($result))
{
$tinnerid=$row['articleid'];
echo "<div class='tinner' id='$tinnerid' onclick='ajaxinput($tinnerid)' style='cursor:pointer;'>";
echo"<span class='fontdiv'>";
echo $row['title']."<br>";
echo "</span>";
echo"</div>";
$tinnerid++;
$articledivid++;
}
mysqli_close($con1);
?>
Here is the js code for second page
function run()
{
alert("example");
}
Here is the php code of second page
<?php
$id=$_GET['q'];
$result=mysqli_query($con1,"select user.username,article.articleid,article.title,article.artiletext from article inner join user on article.user_id=user.user_id where article.articleid=$id");
$divid=0;
while($row = mysqli_fetch_array($result))
{
$id=0;
echo"<div class='inner' id=$divid >";
$id=$row['articleid'];
echo "<font class='ftitle'>"."Title : "."<a href='#'onclick='ajaxinput($id)'>".$row['title']."</a>"."</font>"."<br>"."<font class='ftext'>".$row['artiletext']."</font>"."<br>"."<font class='flast'>"."Posted By : ".$row['username']."</br>"."</font>"."<br>"."<br>";
echo "<button type='button' onclick='con($id)' class='button'><font size='1'>Delete</font></button>";
echo"</div>";
$divid++;
echo"<script>run()</script>";
}
mysqli_close($con1);
?>
Javascript inserted as innerHTML at runtime won't be executed. A possible solution is to remove the script tag from the second page return, and call the method run() on the first page, after the ajax callback. Like this:
function ajaxinput(tinnerid)
{
var xmllhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("articledive").innerHTML=xmlhttp.responseText;
/* CALL IT HERE AFTER INSERT */
run();
}
}
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();

Javascript pass title attribute through function

I have a function that gets the value of a select menu and this work great. But i am trying to add another value to the function. So I thought I would use the title attribute for option (please see code below). The problem is the username parameter in my JavaScript function is undefined.
Does anybody have any ideas of what im doing wrong?
FORM
<form action="">
<select id="acyear" name="acyear" onchange="showyearlogdays(this.value, this.title)">
<option value="" label="">- Year -</option>
<?php
$is_business_result = mysql_query('SELECT DISTINCT(academic_year)FROM holiday_entitlement_business_manual WHERE employee = \'' . $username . '\'');
while($acyear_filter = mysql_fetch_array($is_business_result)) {
echo '<option value="'.$acyear_filter['academic_year'].'" title="'.$username.'"';
$datestr = $acyear_filter['academic_year'];
$currentyear = substr($datestr, 0, 4);
if(intval(substr($datestr,4,2)) < 8){$ayear = ($currentyear - 1).'/'.$currentyear;}
else{$ayear = ($currentyear).'/'.($currentyear + 1);}
echo '>';
echo $ayear;
echo '</option>';
}
?>
</select>
</form>
Javascript
function showyearlogdays(str, username)
{
if (str=="")
{
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","days_yearlog.php?username="+username+"&q="+str,true);
xmlhttp.send();
}
You need to get the title attribute of the selected option. Your code is pointing to the title attribute of the select tag. Make the change below:
showyearlogdays(this.value, this.options[this.selectedIndex].title)
You should also address the security concern mentioned in the comments. The way your query is setup would make for a really simple SQL Injection attack. If you don't want to rearchitect it the way the commenter suggested, I would at least escape $username so that SQL can't be injected.

window.XMLHttpRequest combine with script .change

I have a problem with combinning two scripts.
Fisrt script is working perfectly and taking stuf from mysql:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
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','includes/test-search.php?q='+str,true);
xmlhttp.send();
}
</script>
The second one is working perfectly and it's simple script for inserting data after change:
<script type="text/javascript">
$("document").ready(function(){
$("#selection").change(function () {
$("#someDivName").html( $("#selection option:selected").val() );
});
});
</script>
now the hole point is to combine them.
It's look like, when I load the site it don't have id selection and second script stops but after taking data from php and mysql file test-search.php the missing id selection is on site but the first script is not checking if id selection apear and don't work.
The php code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="SELECT * FROM prod_models WHERE prod_main_group_id = '".$q."'";
$result = mysql_query($sql);
echo '
<select id="selection" name="prod_main_group_id" onchange="change_val()">
<option value="">Wybierz produkt</option>
';
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">';
echo $row['product_name'] . "</option>";
}
echo "</select>
";
mysql_close($con);
?>
Code to display changed script:
<input type="text" id="someDivName" value="" />
if any one can help with solving the problem will be realy nice.
Thx i'm waiting for it now and trying to solve this for my self but now I don't have other ideas for it.

Categories

Resources