Ajax Based search PHP - php

I am trying to create an AJAX based search in PHP. The code I have written so far does not seem to be working uptil now. Any suggesstions would be of great help. Thanks in advance. Here is my code.
index.php
<head>
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function showHint(str) {
if(str.length == 0) {
document.getElementById('inner').innerHTML = "search";
return;
}
if(window.XMLHttpRequest) {
xmlhttp = XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttpreadystate == 4 && xmlhttp.status == 200) {
document.getElementById('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST", "search.php?text"+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
search.php
<?php
$host = 'localhost';
$user = 'root';
$password= 'root';
$db = 'demo';
#$conn = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($db, $conn);
/*if($result) {
echo "success";
} else { echo "fail"; }
*/
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
$query = "SELECT * FROM users where first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
while($res = mysql_fetch_array($action)) {
$output .= $res['first_name']. ' '.$res['last_name'];
echo $output;
}
?>

You missed the equal sign in the script(after the text) in index.php.
xmlhttp.open("REQUEST", "search.php?text="+str, true);

Why you are doing this lengthy process, You can also try this jQuery ajax,
$.ajax({
url: 'search.php',
type: 'GET',
data: 'text='+str,
success: function(data) {
//called when successful
$('#inner').html(data);
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});

I am just getting the input in search.php. Can you try these codes:
index.html:
<html>
<head>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function getHttpRequest()
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function showHint(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById('inner').innerHTML = "search";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "search.php?str="+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
search.php:
<?php
$text=$_GET["str"];
echo $text;
?>

Use this :
$.ajax({
url: 'search.php',
type: 'GET',
data: 'text='+str,
success: function(data) {
//called when successful
$('#inner').html(data);
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert(e.message); // if you dont know how to check console
}
});

Related

Generating new id each time button is clicked

I am working on a reservation system where I need to generate a unique id for each reservation and display it on the form inside the modal when the user clicks on "Add new reservation"
I used ajax and SQL to do that however sometimes I get duplicates of ids. What I do is each time the button is clicked I insert the id into a table and
That's is my code
<script>
function showId() {
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("show-id").defaultValue=this.responseText;
}
}
xmlhttp.open("GET","getid.php?=",true);
xmlhttp.send();
}
</script>
<script>
$(function () {
$('#openModal').on('click', function () {
showId();
var mx_val=$("#show-idi").val();
$.ajax({
type: "POST",
url: "insert-id.php",
data: {mx_val:mx_val},
dataType: "JSON",
success: function(data) {
/* $("#message").html(data); */
getDu();
/* $("p").addClass("alert alert-success");*/
},
error: function(err) {
$("#message").html("Saved!");
$("p").addClass("alert alert-success");
console.log(err);
}
});
});
});
</script>
insert-id.php
<?php
include('db.php');
$mx_val=$_POST['mx_val'];
require_once("dbcontroller.php");
$db_handle = new DBController();
$query ='SELECT max(mx_val) from mxvalue';
$results = $db_handle->runQuery($query);
foreach($results as $references) {
$maxvalue = $references["max(mx_val)"] +1;
}
$stmt = $DBcon->prepare("INSERT INTO mxvalue (mx_val) VALUES ('$maxvalue')");
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Problem occured.";
echo json_encode($error);
}
getid.php
<?php
$con = mysqli_connect('','','','');
if (!$con) { die('Could not connect: ' . mysqli_error($con));
} mysqli_select_db($con,"ajax_demo");
$sql="SELECT max(mx_val) from mxvalue";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$maxid = $row["max(mx_val)"] +1;
?><?php echo $maxid; ?><?php } mysqli_close($con);
?>
You can either use ids based on unix timestamp mixed with some random number, or use a uuid generator Like:
https://github.com/ramsey/uuid
By this two ways you will not get duplicate ids ever

sending multiple parameters to mysql database

this code is to autosave form in mysql database
i am unable to send multiple parameters
the main issue is here
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
php code
<?php
$user_id = 1;
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$saved_text = mysql_real_escape_string($_POST["saved_text"]);
$sql = "UPDATE asave SET saved_text = '".$saved_text."' ";
$sql.= "WHERE user_id = $user_id";
mysql_query($sql) or die(mysql_error().$sql);
echo "Your data has been saved ".date("h:m:s A");
exit;
}
$sql = "SELECT saved_text FROM asave WHERE user_id = $user_id";
$rs = mysql_query($sql) or die(mysql_error().$sql);
$arr = mysql_fetch_array($rs);
$saved_text = $arr["saved_text"];
?>
html code
<html>
<head>
<script type="text/javascript">
function init(){
window.setInterval(autoSave,10000); // 10 seconds
}
function autoSave(){
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
var http = getHTTPObject();
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
msg = document.getElementById("msg");
msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>";
}
};
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
</head>
<body onload="init();">
<span id="msg" style="cursor:pointer;"></span>
<form method="POST">
<textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea>
<br/>
<input id="test" type="text" value="<?php echo $content;?>">
<input type="submit" value="save now" />
</form>
</body>
You're not posting saved_text in your javascript. You're posting params (that is missing a delimiter).
To post multiple parameters check this post: Posting parameters to a url using the POST method without using a form

PHP page not returning value

I am trying to retrieve a value from a database through ajax and php.
The ajax code is as follows:
<script>
$(document).ready(function() {
$("#buyprice").change(function() {
if ($("#sname").val() == "") {
alert("Enter Stock name.");
} else {
var sn = $("#sname").val();
alert(sn);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var x = xmlhttp.responseText;
};
};
xmlhttp.open("GET", "getstockprice.php?q="+sn, true);
xmlhttp.send();
alert("here");
};
alert("here");
var bp = $("#buyprice").val();
alert(bp);
alert(x.val());
if(bp>(1.1*x)||bp<(1.1*x)){
alert("Price violating 10% constraint.");
}
alert("here");
});
});
</script>
The php page is as follows:
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','stock_market');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT stock_price FROM live_prices WHERE stock_name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
mysqli_close($con);
?>
Can someone please tell me where I am going wrong.
you should use echo or return to return something from php.
<script>
$(document).ready(function() {
$("#buyprice").change(function() {
if ($("#sname").val() == "") {
alert("Enter Stock name.");
} else {
var sn = $("#sname").val();
alert(sn);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var x = xmlhttp.responseText;
};
};
xmlhttp.open("GET", "getstockprice.php?q="+sn, true);
xmlhttp.send();
alert("here");
};
alert("here");
var bp = $("#buyprice").val();
alert(bp);
alert(x);
if(bp>(1.1*x)||bp<(1.1*x)){
alert("Price violating 10% constraint.");
}
alert("here");
});
});
</script>
PHP
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','stock_market');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT stock_price FROM live_prices WHERE stock_name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
mysqli_close($con);
echo $row['stock_price'];
?>
The php script needs to echo the value. This does not display the value on your page, it merely makes the value avalailble to the javascript.
I would suggest using jquery and use the built in ajax functionality. This works much easier.
See the jquery ajax page, and an example straight from there:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});

Automatic update in JavaScript using PHP code

I'm trying to make auto update on my page using JavaScript and php code to read the data from the server
<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var myVar=setInterval(function(){myTimer()},5000);
}
function myTimer()
{
document.write("<?php
session_start();
$userdata = $_SESSION['views'];
$name = $userdata[1];
$mysql_host = 'localhost';
$mysql_user = 'root';
$connection = mysql_connect($mysql_host,$mysql_user);
mysql_select_db("twitter2", $connection);
$query = "SELECT * FROM `logindata`";
$result =mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['loginname'];
}
echo "<br>";echo "<br>";
?>");
}
</script>
</head>
<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>
this code works fine but only display what found in the DB first time
but if I add more rows in the DB this new rows doesn't appear on the page.
thanks All
I changed some of my code to be like this
<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var myVar=setInterval(function(){myTimer()},1000);
}
function myTimer()
{
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","phptest.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
<div id="txtHint"></div></p>
</form>
</body>
</html>
and the php file
<?php
$mysql_host = 'localhost';
$mysql_user = 'root';
$connection = mysql_connect($mysql_host,$mysql_user);
mysql_select_db("twitter2", $connection);
$query = "SELECT * FROM `logindata`";
$result =mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['loginname'];
}
?>
and it works fine to me. Thanks for your help
You doin it wrong - the content of your JavaScript function is interpreted on the server and always the same. Your JavaScript function have to send a request to the Server and handle the response.
If you use JQuery this could look i.e. like this
$.get('ajax/script.php', function(data) {
$('.result').html(data);
});
and inside script.php, you could output the database results
javascript is a client side language.
You cannot print out some php with javascript because it happens in the clients browser.
You need to do it on the server, so I think what you want is an ajax request (XMLHttpRequest) to a server-side php script which look like the content of your document.write.
A very simple and nice cross-browser way doing this is to use jquery.ajax.
http://api.jquery.com/jQuery.ajax/
simple tutorial:
http://viralpatel.net/blogs/jquery-ajax-tutorial-example-ajax-jquery-development/
Use Ajax to combine client and server side languages!
steven is right, here is how I would do with jquery:
In javascript:
function myTimer()
{
$.ajax({
url:'path/to/your-script.php',
type:"POST",
data:"ajax=true",
success:callBackMyTimer
});
}
function callBackMyTimer(data)
{
alert(data);
}
In your-script.php
<?php
if(isset($_POST['ajax']) && $_POST['ajax'] == 'true')
{
session_start();
$userdata = $_SESSION['views'];
$name = $userdata[1];
$mysql_host = 'localhost';
$mysql_user = 'root';
$connection = mysql_connect($mysql_host,$mysql_user);
mysql_select_db("twitter2", $connection);
$query = "SELECT * FROM `logindata`";
$result =mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['loginname'];
}
echo "<br>";echo "<br>";
}
exit;
?>

Javascript PHP synchronisation problem

I want to call a javascript function with parametars that are stored in MySQL. All this is happening on an onClick event.
Here is the javascript code:
function getFile() {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", "gmap.php", false);
AJAX.send("searchField=" + searchField.value);
return load(AJAX.responseText);
} else {
return false;
}
}
So, the gmap.php is echoing the parameters for the javascript load function. But it doesn't load the parameter because the function is called before the MySQL query in gmap.php is executed. I've tried sync and async AJAX.
If I try to call the javascript function from PHP, it doesn't get executed, because it is called on a onClick event, and this is inside a div.
Please help me, I'm doing this over a week now. I've tried everything.
Here is the php code with the MySQL query:
<?php
header( 'Content-Type: text/html; charset=UTF-8' );
mb_internal_encoding( 'UTF-8' );
$a = $_POST['searchField'];
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$dbname = "citydb";
//connect sql
mysql_connect($dbhost, $dbuser, $dbpass);
//select db
mysql_select_db($dbname) or die(mysql_error());
//retrieve data
//$city=$_GET['city'];
//escape user input to help prevent SQL injection
//$city=mysql_real_escape_string($city);
//query
mysql_query('SET CHARACTER SET utf8');
$result=mysql_query("SELECT citystart, cityend FROM cityids WHERE city='$a' ");
if(!result) {
die("Database query failed: " . myql_error());
}
while($row=mysql_fetch_array($result)) {
$lat=$row['citystart'];
$lng=$row['cityend'];
}
echo $lat;
echo ", ";
echo $lng;
?>
pass the php url together with the variable to search.
if (AJAX) {
var url = "gmap.php?searchField="+ searchField.value;
AJAX.open("POST", "url", false);
AJAX.send(true);
return load(AJAX.responseText);
}
I think searchField.value does not contain anything.
Replace
searchField.value
With this
document.getElementById('searchField').value
assign the searchField as an id to the search box.
add this code after AJAX.open and before AJAX.send.
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", searchField.value.length);
AJAX.setRequestHeader("Connection", "close");
I have succesfully tested this
<html>
<head>
<script>
function load(response) {
alert(response);
}
function getFile() {
if (window.XMLHttpRequest) AJAX=new XMLHttpRequest();
else AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX) {
var params = "foo=" + searchField.value;
AJAX.open("POST", "http://localhost/test.php", true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", params.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.onreadystatechange = function() {
var ok;
try { ok=AJAX.readyState; } catch(e) { }
if(ok==4) load(AJAX.responseText);
}
AJAX.send(params);
}
}
</script>
</head>
<body>
<input type="text" id="searchField"/>
<input type="button" onclick="getFile()"/>
<script>
searchField = document.getElementById("searchField");
</script>
</body>
</html>

Categories