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>
Related
I have a HTML page index2.html. In this page, I have a DIV which I am using to call a PHP page. The Php page has DB connection parameters, an SQL to fetch values from the DB.
However, when the PHP is called from the HTML, I am getting redirected to the PHP page. All I want is to use this stored procedure to get the data from the database.
HTML Code Snippet
</head>
<body>
<div id="background">
<div id="Layer0"><img src="images/Layer0.png"></div>
<div id="Layer2"><img src="images/Layer2.png"></div>
<div id="parceldeliveryservic"><img src="images/parceldeliveryservic.png"></div>
<div id="Layer10">
<form action="insert4.php" method="post">
<input type="image" src="images/Layer10.png"/>
</form>
</div>
The PHP Code Snippet:
<?php include("connect.php");
//$q = intval($_GET['q']);
try {
$proc_rate ='rtPreston';
$proc_price = 0.0;
$conn = new PDO("mysql:host=$servername;dbname=testdb", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "GetPrice(?, ?)";
$sql = "Call GetPrice(:input, #output_price)";
$stmt = $conn->prepare($sql);
echo $proc_price;
$stmt->bindParam(':input',$proc_rate, PDO::PARAM_INT);
$stmt->execute();
$stmt->closeCursor();
$proc_price = $conn->query("SELECT #output_price AS output_price")->fetch(PDO::FETCH_ASSOC);
if ($proc_price) {
echo sprintf('Price for %s is %lf', $proc_rate, $proc_price['output_price']);
}
} catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
//$conn = null; ?>
can you please let me know what needs to be done to display the result in the calling HTML page?
Many thanks
HTML
<div onclick="callPHP();">Click me!</div>
Javascript
<script>
function callPHP() {
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) {
// xmlhttp.responseText contains the result of the PHP
alert( xmlhttp.responseText );
}
};
// Call the PHP
xmlhttp.open("GET", "insert4.php", true);
xmlhttp.send();
}
</script>
I am trying to calculate the sum of prices sold between two specific dates. My query is okay but it isn't returning anything when i use in PHP. It works when i directly execute in database.
Here is my code,
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
var queryString = "?startdate=" + startdate ;
queryString += "&enddate=" + enddate;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Start Date: <input type='date' id='startdate' /> <br />
End Date: <input type='date' id='enddate' /> <br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Here is my PHP Code
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "temp";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
//build query
$query = "SELECT SUM(price) FROM ajax_example WHERE daterec >= '$startdate'";
$query .= " AND daterec <= '$enddate'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
echo "Query: " . $query . "<br />";
?>
What am i doing wrong? Thank you in advance
Satisj Rajak! you are right!
check mysql_query
first, this function will be deprecated after PHP 5.5.0, try to dont use it.
second, to get the results you have "transform" the variable in an associative array using this example code:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field_name'];
}
and if you use ajax, try to send a json format response.
hope my answer help you.
In your button click handler, try returning false. My first instinct would be that your form is being submitted by that button and your AJAX request is never being completed.
<input type='button' onclick='ajaxFunction(); return false;' value='Query MySQL'/>
If that doesn't solve it, open up google chrome and the network debugging tools. When you execute the AJAX request, check the request and response data.
In addition, you should optimize your JavaScript to be more effective.
Here is a snippet of JS which could be used in your situation:
var get = function(path) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', path);
request.onload = function() {
if (request.status == 200)
resolve(request.response);
else
reject(Error(request.statusText));
};
request.onerror = function() {
reject(Error(request.statusText));
};
request.send();
});
}
function fetchQueryResults() {
get('/test.php').then(function(response) {
var el = document.getElementById('results');
el.innerHTML = response;
}).catch(function(error) {
// Something went wrong, handle the error here
});
return false;
}
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
}
});
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;
?>
I was looking around for a ajax script which could populate triple drop down list using PHP. And I came across this piece of code although the code works pretty well I would like to know what is actually happening behind the scene, as I am a newbie to AJAX or JavaScript I am unable to understand what does the below function exactly do. Here is the code:
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getState(countryId) {
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
function getCity(stateId) {
var strURL="findCity.php?state="+stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
and here is the code from finsState.php
<?php
$countryId=intval($_GET['country']);
$host = "localhost";
$username = "username";
$password = "password";
$database = "test";
$connection = mysql_connect($host,$username,$password) or die(mysql_error());
$database = mysql_select_db($database) or die(mysql_error());
$query = "SELECT * FROM states WHERE country_id = ".$countryId;
$result = mysql_query($query) or die(mysql_error());
?>
<select name="states" onchange="getCity(this.value)">
<option>Select State</option>
<?php while($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>
and this is findCity.php
<?php
$stateId=intval($_GET['state']);
$host = "localhost";
$username = "username";
$password = "password";
$database = "test";
$connection = mysql_connect($host,$username,$password) or die(mysql_error());
$database = mysql_select_db($database) or die(mysql_error());
$query = "SELECT * FROM cities WHERE state_id = ".$stateId;
$result = mysql_query($query) or die(mysql_error());
?>
<select name="city">
<option>Select City</option>
<?php while($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?> </option>
<?php } ?>
</select>
My questions :
a) Can anyone please summarize the first, second and third javascript function and how does it select all the values from findState.php and findCity.php
b) If I was to catch the value of the stateId and CityId the user selected how do i do it. as because the list is populated from JavaScript I am unable to catch the value from PHP ($_POST['state']).
The first function is attempting to open up and XML HTTP request, allowing the clients-side scripts to interact with server-size scripts. Since various browsers handle that differently, it trys to use the standard method before attempting a modern IE implementation, an older IE implementation and finally giving up.
The second two do roughly the same thing. They define the script they wish to interact with an use the first function to connect. If the connection was successful, it sends over the information using an HTTP GET request (traditionally GET is used for getting information, POST is used for setting it).
When information is sent using XmlHttpRequest, the onreadystatechange event fires at key points during the connection and gives access to the readyState (referring to how the stage of the request) and the status which is a standard server response (you're probably familiar with "404" meaning "file not found"). A "200" status means "everything is fine", so when that is received the script knows it can act on the information it was given. Any other response will create a popup that tells the user what went wrong.
Without seeing the actual page this script interacts with, I don't know the best way to get stateId and CityId. At a guess, they will be the value of an input when a certain button is pressed. If that's the case, something like the following piece of code would do it:
document.getElementById('id-of-submit-button').onclick = function() {
var stateId = document.getElementById('id-of-stateid-input').value,
CityId = document.getElementById('id of cityid-input').value;
};