This is a Google suggestion-like script.
I rewrote the AJAX Call code by splitting it up into multiple functions and seems this is a better cross-browser/usability approach. Now I need to pass the input variable that I read from the input #search_text to a php file where I actually fetch the data from database.
For moment all I need is to pass search_text and display it with echo $_GET['search_text'];
Can someone help me?
Here is the script
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php");
}
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and the php file is:
<?php
echo 'Something';//'while typing it displays Something in result div
//echo $_GET['search_text'];
?>
Thanks
The issue is that you're not actually passing in any data to the PHP script. In this case, you need to stick the 'search_text' parameter on the end of the URL, since you're expecting it to be a GET request.
startRequest("ajax-submit.php");
should be
startRequest("ajax-submit.php?search_text="+document.search.search_text.value);
this jQuery Solution is way easier and Cross-Browser compatible:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$('#search_text').keydown(function(){ // Bind event to KeyDown
var search_text = $(this).val(); // get value of input field
$.ajax({ // fire Ajax Request
url: "ajax-submit.php?search_text=" + search_text,
success: function(result){
$("#results").html(result); // on success show result.
}
});
});
});
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" />
</form>
<div id="results" style="background:yellow"></div>
</body>
Related
I am trying a simple ajax call. The test.php is just echoing some text. But the ajax call always returns readyState 1 and status 0. Here is the piece of code which I am using for ajax call.
<html>
<head>
<script>
function showData()
{
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject(Microsoft.XMLHTTP);
}
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementById('data').innerHTML = xhr.responseText;
}
else
{
var content = document.getElementById('data').innerHTML;
document.getElementById('data').innerHTML = content + 'ERROR with ready state '+xhr.readyState+' and status of '+xhr.status+'<br>';
}
}
xhr.open('GET','test.php',true);
send(null);
}
</script>
</head>
<body>
<input type="submit" value="Get Data" onClick="showData()" />
<span id="data" ></span>
</body>
</html>
Thank you in anticipation.
You'd have to call the xhr.send() method.
xhr.send();
A readyState of 1 means that the xhr request is just set up, since you have xhr.open(). If the xhr.send() is called, then the other states come into play.
Im trying to send a value of a dropdown on change to a php script. But with my way of solving the problem, the form and also the status String are posted twice. Once with GET parameter set, and the other without. I dont know how to solve,but maybe you are smarter than me.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="js/jquery.ennui.contentslider.js"></script>
<script type="text/javascript">
function showUser()
{
var users = document.getElementById('users').value;
if (users=="" )
{
document.getElementById("pictab").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","slider.php?users="+users,true);
xmlhttp.send();
xmlhttp.reload();
}
<?php
//.............
//..............
//.............
//..............
$soso = mysql_num_rows($connn3);
for($i=0;$i<$soso;$i++)
{
echo "
$(function() {
$('#one$i').ContentSlider({
width : '280px',
height : '180px',
speed : 400,
easing : 'easeOutQuad'
});
});";
}
?>
</script>
<!-- Site JavaScript -->
<form>
<select id="users" name="users" onChange="showUser()" >
<option value="bikes">Bikes</option>
<option value="zub">Stuff/option>
<option value="sonst">Other</option>
</select>
</form>
<br>
<div id="txtHint"></div>
<?php
if(isset($_GET['users'])){
echo "<h2>Q posted</h2>";
$q = $_GET['users'];
echo $q;
//DB QUERY WITH Q
}elseif(!isset($q)){
echo "KEIN Q GEPOSTET";
// DB QUERY WITHOUT Q
}
?>
You've included Jquery into your project so use its features. Mostly Jquery Ajax to handle Ajax requests.
$(function (){ //document is loaded so we can bind events
$("#users").change(function (){ //change event for select
$.ajax({ //ajax call
type: "POST", //method == POST
url: "slider.php", //url to be called
data: { users: $("#users option:selected").val()} //data to be send
}).done(function( msg ) { //called when request is successful msg
//do something with msg which is response
$("#txtHint").html(msg); //this line will put the response to item with id `#txtHint`.
});
});
});
The php part of code should be in slider.php. Moreover, in example I use POST but if you want GET simply change type: "GET". In script.php to get value of it use:
$_POST['users']; or if you change the type to GET then $_GET['users'] you can also use $_REQUEST['users'] which handles POST, GET, COOKIE.
I think this is because your are actually making 2 calls. One in Javascript to the PHP file and the other your echoing no matter what is set. I would comment but haven't got enough juice yet.
Try and echo out $_GET and see what your are actually setting before the call and after the call. From there you may be able to see what's actually going on. I hope this helps guide you in the right direction.
var name=document.forms["myform"]["user"].value;
$.ajax({
type: "POST",
url: "yourpagenmae.php",
data: { name: user }
,
success: function(msg) {
// alert(msg);
}
});
hope it will help you
//view file
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//use jquery get method
$('#users').change(function() {
//get the user value
var user = $('#users').val();
$.getJSON( "http://localhost/test.php?users="+user, function( data1 ) {
console.log(data1);
//status
if (data1.status) {
alert(data1.q);
//whatever response variable key
$('#txtHint').html(data1.q)
} else {
alert('error'+data1.q);
}
});
});
});
</script>
<!-- Site JavaScript -->
<form>
<select id="users" name="users" >
<option value="bikes">Bikes</option>
<option value="zub">Stuff</option>
<option value="sonst">Other</option>
</select>
</form>
<br>
<div id="txtHint"></div>
//test.php file
<?php
$data = array();
if(isset($_GET['users'])){
//echo "<h2>Q posted</h2>";
$q = $_GET['users'];
$data['status'] = true;
$data['q'] = $q;
}elseif(!isset($q)){
$data['status'] = false;
$data['q'] = 'KEIN Q GEPOSTET';
}
header('Content-type:application/json');
//json response
echo json_encode($data);
?>
I am a beginner and I am trying to learn how to add, delete, retrieve and update a database using PHP and Ajax.
At this time I have accomplished how to retrieve and delete so I am trying to update some values. For retrieving data, I just pass the selected ID I want, so I can retrieve the data. Same goes for delete, I just assign which ID I want to delete. Now to update there are more things going on, its where I cant find the solution.
This is my Form:
<form onsubmit="updateuser()">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="Submit" value="Update">
</form>
and this is my javascript:
function updateuser() {
var str = $('.ud_id').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?q=" + str, true);
xmlhttp.send();
}
I think the problem comes because my form ajaxupdate.php file doesn't retrieve the First and Last name values from the form. It's like I am not passing them (?).
Here is my ajaxupdate.php file:
<?php include("connection.php");
$id=$_GET['ud_id'];
$first=$_GET['ud_first'];
$last=$_GET['ud_last'];
$query="UPDATE contacts SET first='$first', last='$last' WHERE id='$id'";
mysql_query($query);
mysql_close();
?>
What I'm I doing wrong so that I can update the value first and last of database for a specific ID ?
Try this code
<script type="text/javascript">
function updateuser() {
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
</script>
HTML
<form name="test">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="button" onClick="updateuser()" value="Update">
</form>
In your javascript, do this
function updateuser() {
var ud_id = $('input[name="ud_id"]').val();
var ud_first = $('input[name="ud_first"]').val();
var ud_last = $('input[name="ud_last"]').val();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
If you want to use the updateuser() function on submit, then it must prevent the form from actually submitting. Make it return false, otherwise the form gets submitted by the browser before the function has time to execute.
The browser runs the function before submitting the form (that's how on submit works). If the function doesn't return false, then it interprets that as "everything is OK, you can safely submit the form". The form then gets submitted as usual.
In the mean time, the function initiates the asynchronous request. But since the browser has already submitted the form, now you're on a totally different page, thus the connection and the asynchronous request get disconnected and most likely ignored (unless of course the request made it before the page was changed, in which case both requests are processed).
As an alternative, you could execute the function without placing it in the on submit event. See sam_13's answer.
Check this it will work as expected
ud_id = document.getElementById('ud_id').value;
ud_first = document.getElementById('ud_first').value;
ud_last = document.getElementById('ud_last').value;
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id +"&ud_first=" +ud_first+ "ud_last="+ud_last, true);
<form onsubmit="updateuser()">
ID Number: <input name="ud_id" id="ud_id"><br>
First Name: <input type="text" name="ud_first" id="ud_first"><br>
Last Name: <input type="text" name="ud_last" id="ud_last"><br>
<input type="Submit" value="Update">
</form>
I came accross this example because i am also running into a similar issue. however I couldnt help but notice that you do not specify a method for your form and your AJAX is assuming it should use the GET method. just food for thought... cheers
This code is tested and works. I needed to do the same thing, update MySql with ajax and combining the above with a wider research I got this to work.
The php file is called ajaxupdate.php:
<?php
$id= $_GET['ud_id'];
$first= $_GET['ud_first'];
$last= $_GET['ud_last'];
require_once ('mysqli_connect.php'); //connection to the database
$sql = "UPDATE contacts SET FirstName ='$first', LastName='$last' WHERE id='$id'";
$result = mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>
The Html file called anyNameYouWish.html:
<html>
<head>
</SCRIPT>
<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;
}
}
}
function MsgBox (textstring) {
alert (textstring) }
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
var queryString = "?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last;
ajaxRequest.open("GET", "ajaxupdate.php" + queryString + "&random=" + Math.random(), true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" name="test" onsubmit="ajaxFunction()">
ID Number: <input id="ud_id" name="ud_id"><br>
First Name: <input id="ud_first" type="text" name="ud_first"><br>
Last Name: <input id="ud_last" type="text" name="ud_last"><br>
<input type="submit" value="Update">
</form>
</body>
</html>
Ajax responds with an empty string when triggered via form onsubmit in Firefox, but it is working fine in Internet Explorer and Opera (works in Firefox if sent by a submit button instead of form onsubmit).
I am simply calling a php file with the ajax GET and the php file response with - echo $response = "something";. Then the response value is alerted. I am getting it work in IE but in Firefox the response is an empty string (checked by typeof()).
code is 4 files: index.php, ajax-connect.js, cbb.js, cbb.php
index.php
<html> <head> <script src="ajax-connect.js"></script> <script src="cbb.js"></script>
</head> <body>
<form name="condtactform1" method="get" action="" onSubmit="contactfunction()">
<input type="submit" name="hissubmit" id="hissubmit" value="submit"> </form>
</body> </html>
ajax-connect.php
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*#cc_on #*/
/*#
if (#_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
#end
#*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
cbb.js
function contactfunction() {
var url = "cbb.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var responsae = xmlHttp.responseText;
alert(responsae);
}
}
cbb.php
<?php $response = "something"; echo $response; ?>
If i trigger ajax by submit button instead of the form submit then it works fine in firefox like:
<form name="condtactform1" method="get" action="">
<input type="submit" name="hissubmit" id="hissubmit" value="submit" onFocus="contactfunction()"> </form>
Any idea why it is doing this?
Thanks.
I think part of the problem is that you aren't stopping the normal action of the submit. That it is working at all is probably based on how the return values of the last function executed is handled, though its hard to tell. Try adding a "return false" to your contactFunction();
If that doesn't work, I'd invest some time in retrofitting it to use a javascript framework for the AJAX (jQuery, MooTools, Prototype, etc.) rather than going down the route of debugging the cross browser differences. A jQuery solution would look like:
<form name="condtactform1" method="get" action="cbb-full.php">
<input type="submit" name="hissubmit" id="hissubmit" value="submit">
</form>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('#hissubmit').click( function() {
$.get( 'cbb.php', function(response) {
alert(response);
});
return false;
});
});
</script>
Note that the form ought to post to a url that will generate a full response if javascript isn't enabled.
I am trying AJAX for the first time on my localhost.
I am using IIS and PHP with MySQL.
This error is generated: "A HTTP Error 404.3 - Not Found" when I try this javascript command:
xmlhttp.send(null);
xmlhttp is a varable and is used to retrieve the GetXmlHttpObject
Just in-case something inside your xmlhttp object creation is not setup correctly or you have not waited for the correct status, have you looked at some simple xamples like from XUL.fr or W3 Shools or Your HTML Source?
Below is a simple example. Notice the inline function for the onreadystatechange callback and the check on readystate and status. I believe your issue may reside in you note doing these checks, but without your code I could be wrong.
<html>
<head>
<script>
function submitForm()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open(GET, "data.txt", true);
xhr.send(null);
}
</script>
</head>
<body>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>