I used tutorialspoint to guide me to insert the values from input text into the db, but unfortunately, it will not insert to the database. Is this correct implementation for AJAX?
Here's my index.php
<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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gen = document.getElementById('gen').value;
// var queryString = "?age=" + age ;
queryString += "&fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
First Name: <input type='text' id='fname' /> <br />
Last Name: <input type='text' id='lname' /> <br />
Sex:
<select id='gen'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "my_db";
$con = new mysqli($dbhost, $dbuser, $dbpass,$dbname);
$query="INSERT INTO table1 (fname, lname, gender)
VALUES
('$_GET[fname]','$_GET[lname]','$_GET[gen]')";
$qry_result = $con->query($query);
?>
change your code to the bellow
var queryString;
queryString = "fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php?" + queryString, true);
and make sure ajax.php is in the same folder as index.php
Try this in ajax.php:
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$gen=$_GET['gen'];
$query="INSERT INTO table1 ('fname', 'lname', 'gender')
VALUES('$fname','$lname','$gen')";
Declare Form method="POST"
and
$query="INSERT INTO table1 (fname, lname, gender) VALUES
('".$_POST['fname']."','".$_POST['lname']."','".$_POST['gen']."')";
Related
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;
}
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
I just cant figure out what is wrong with this code.
I am just sending a username and password to the server, then server sending back a response. Server write to database with no problem, but in the client side sometimes it doesn't reach inside the if(xmlhttp.readyState==4 && xmlhttp.status==200). And after it execute the line alert('login5'), the jquery animation reset. I know it is the php problem, but I have no idea why it sometimes works but sometimes doesnt, any help is appreciated.
<script type = "text/javascript">
function sendLogin(){
var xmlhttp;
var getString;
var url = "login.php";
var username=document.getElementById('name').value;
var password=document.getElementById('pw').value;
var url= url+ "?username="+username+"&password="+password;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("get", url , true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert("reached inside");
getString = xmlhttp.responseText;
alert(getString);
}
}
xmlhttp.send();
alert('login5');
//problem here, have to wait a while
}
</script>
html code:
<form id="logInBoxes">
<input type="text" placeholder="username" id='name' size="15px">
<input type="password" placeholder="pw" id='pw' size="10px">
<input type="submit" value="Log In" onclick='sendLogin()'>
</form>
php code:
<?php
$username= $_GET['username'];
$password= $_GET['password'];
$salt = mcrypt_create_iv(32, MCRYPT_RAND);
$password = crypt($password, $salt);
$salt = mysql_real_escape_string($salt);
$password = mysql_real_escape_string($password);
$sql = mysqli_connect('localhost','root','','housescale');
// Check connection
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($sql, "INSERT INTO user (username, password, salt)
VALUE
('$username', '$password','$salt')") or trigger_error(mysql_error());
mysqli_close($sql);
echo $username;
?>
edit: it works if I do alert('login5') 9 more times in a loop. What exactly does this delay fix imply?
Here's the code I used that worked on my end:
test.html
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function sendLogin() {
var xmlhttp;
var getString;
var url = "login.php";
var username = document.getElementById( 'name' ).value;
var password = document.getElementById( 'pw' ).value;
url = url + "?username=" + username + "&password=" + password; //Don't Need to Re-Declare url Variable
if( window.XMLHttpRequest ) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
}
xmlhttp.open( "get", url , true );
xmlhttp.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
xmlhttp.onreadystatechange = function() {
if( xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) { //Separated readyState and Status
alert( "reached inside" );
getString = xmlhttp.responseText;
alert( getString );
}
}
}; //Missed Semi-Colon Here
xmlhttp.send();
alert( 'login5' );
}
</script>
</head>
<body>
<form id="logInBoxes">
<input type="text" placeholder="username" id='name' size="15px">
<input type="password" placeholder="pw" id='pw' size="10px">
<input type="submit" value="Log In" onclick='sendLogin()'>
</form>
</body>
</html>
login.php
<?php
$username= $_GET['username'];
$password= $_GET['password'];
$salt = mcrypt_create_iv( 32, MCRYPT_RAND );
$password = crypt( $password, $salt );
$sql = mysqli_connect( 'localhost', 'root', '', 'housescale' );
$salt = mysqli_real_escape_string( $sql, $salt );
$password = mysqli_real_escape_string( $sql, $password );
// Check connection
if ( mysqli_connect_errno() ){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query( $sql, "INSERT INTO user ( username, password, salt ) VALUE ( '$username', '$password', '$salt' )" )
or trigger_error(mysql_error());
mysqli_close( $sql );
echo $username;
?>
I use Mozilla Firefox 23 on Windows 7. My stack is Uniform Server 8.8.2 (PHP 5.4.14 / MySQL 5.5.30).
I set all the fields in my table to varchar(255) just to be quick. It worked for me with only one issue, sometimes the salt/crypt turned up empty in my database, but that's probably a charset issue because it was able to echo several different combinations just fine.
i got an useful tutorial where if you input 'id' [or first 1-2 letter of your id], the rest of form's field will filled automatically by pulling data from mysql database. this thing will happen without pressing ENTER key! now, what i'm trying to do is, i'll input the full 'id' & press ENTER key to fill the rest of form's field! what modification would need for this code below? here is my index.html file:
<html>
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var http; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
http = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var url = "getagentids.php?param=";
var idValue = document.getElementById("agid").value;
var myRandom = parseInt(Math.random()*99999999); // cache buster
http.open("GET", "getagentids.php?param=" + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
</script>
<form name="schform">
<table>
<tr>
<td>Contact ID:</td>
<td><input id="agid" type="text"
name="contactid" onKeyUp="ajaxFunction()"></td>
</tr>
<tr>
<td>Tel Number:</td>
<td><input id="agtel" type="text"
name="contacttel"></td>
</tr>
<tr>
<td>Name:</td>
<td><input id="agfn" type="text"
name="contactfullname"></td>
</tr>
<tr>
<td>Salutation:</td>
<td><input id="agsal" type="text"
name="contactsalutation"></td>
</tr>
<tr>
<td><input type="reset" value="Clear"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
and here is my getagentids.php file:
<?php
error_reporting(0); // turns off error reporting
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("contactdetail", $con);
mysql_select_db("contactdetail");
$param=$_GET['param'];
if (strlen($param) > 0) {
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
$agentname = $myrow["contactfullname"];
$agenttel = $myrow["contacttel"];
$agentsal = $myrow["contactsalutation"];
$agentid = $myrow["contactid"];
$textout .= $agentid . ", " . $agentname . ", " . $agenttel . ", " . $agentsal;
}
} else {
$textout = " , , ," . $param;
}
}
echo $textout;
?>
first create a javascript function to detect if the Enter key is pressed and call the ajaxFunction from within it:
function run(e) {
if (e.keyCode == 13) {
ajaxFunction();
return false; //disable the default Enter behavior
}
return true;
}
change the onKeyUp="ajaxFunction()" call in the Contact ID text input into onKeyUp="run()"
You can change your ajaxFunction like (just paste the code at the top of your ajaxFunction)
function ajaxFunction(e){
var e=e || window.event;
var keycode=e.which || e.keyCode;
if(keycode!==13 || (e.target||e.srcElement).value=='') return false;
// rest of your code
}
And change your onKeyUp with this (notice event in the argument)
<input id="agid" type="text" name="contactid" onKeyUp="ajaxFunction(event)">
Just for an idea.
I want to show a (chart) image using AJAX. I'm not sure what's wrong, but I'm getting the following 'error' and an incorrect image:
"|xtt�I������{饗BBBN�:��}�̛7oРA7n�0l߾} QQQIIIeee�aLHH������ضm��wm���v��U�&�Z���o�# Art]]]����{���#""��'���v|�ҥKqqq���ح�~;11�ȑ#����u��ںm6O�7o���.��ի��?~Ȑ!��~��۷��O�0A.�cv�����TäR)�� ����˗{N����5<��&0� ���ҷo��#�NХ<0�j�0��=���]�t��۷�j�T*5�\����۳g�F�����gfm���ݻ�'OF....."
The code I'm using:
ajax_select.php:
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function showUser(str,age)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="test_ajax.php";
url=url+"?q="+str+"&a="+age;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML="<IMG SRC='" + xmlhttp.responseText + "'/>";
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
</head>
<body>
<form>
<select id="users" name="users">
<option value="">Select a person:</option>
<?php
$con = mysql_connect(***);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
$sql="SELECT ***";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
mysql_close($con);
?>
</select>
<select id="age" name="age">
<option value="">Select a person:</option>
<?php
$con = mysql_connect('***');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
$sql="SELECT ***";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
mysql_close($con);
?>
</select>
<input type='button' value='Refresh Data' onclick="showUser(document.getElementById('users').value,document.getElementById('age').value)">
</form>
<br><br>
<div id="txtHint"><b>chart will be displayed here.</b></div>
</body>
</html>
ajax_select_NEW.php:
<script type="text/javascript">
var xmlhttp;
function showUser(str,age)
{
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
test_ajax.php:
<?php
/* Include the pData class */
include("class/pData.class.php");
include("class/pDraw.class.php");
include("class/pImage.class.php");
/* Get user from AJAX resquest */
$user_id=$_GET["q"];
$q=$_GET["q"];
$a=$_GET["a"];
/* Create the pData object */
$MyData = new pData();
/* Connect to the MySQL database */
$db = mysql_connect("***");
mysql_select_db("***",$db);
/* Build the query that will returns the data to graph */
$Requete = "
SELECT ***
";
***
/* Render the picture (choose the best way) */
$myPicture->autoOutput("examples/example.drawBarChart.png");
?>
I have hard coded the variables in the SQL code for now. (in test_ajax.php) So if I open that page it just shows the correct chart image. But when I open the ajax_select.php page I get the error in the picture above. (so it's not a wrong chart code information, since it's okay if I open the php page directly)
I have searched a lot, but can't find the solution. Hopefully someone can help me here, would be much appreciated!
You're trying to put the binary image data into the src attribute of the img. This attribute is meant for the source URL of the image, you can do this entirely without XmlHttpRequest, just insert your image by using test_ajax.php as the src.
function showUser(str, age) {
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
}
As for the broken rendering of the image, have you included a Content-Type-header?
header('Content-Type: image/png');
$myPicture->autoOutput("examples/example.drawBarChart.png");
This is what ajax_select_NEW.php should look like:
<script type="text/javascript">
function showUser(str, age) {
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
}
</script>