Javascript form & Ajax request to PHP - php

Why is this not working? When the Ajax code IS NOT wrapped in function xmlhttpGet() it does work: PHP returns the called page and inserts it into the DIV. In this code i have wrapped the code into the function xmlhttGet() amd nothing happens. The requested page is not loaded into the DIV.
<html><head><title>AJAX GET </title>
</head><body><center />
<h1>Loading a web page into a DIV</h1>
<FORM id="form" method="post" action="">
<b> Enter argument: </b>
<input size="40" name="q" id="q" value="">
<INPUT TYPE="submit" id="submit" VALUE="Submit" onClick="xmlhttpGet(this.form)">
<INPUT TYPE="reset" VALUE="Reset">
</FORM>
<div id='info'>This sentence will be replaced</div>
<script>
function xmlhttpGet(form)
{
nocache = "&nocache=" + Math.random() * 1000000
request = new ajaxRequest()
var $q = form.q.value
request.open("GET", "urlget.php?url=amazon.com/gp/aw" + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
}// END xmlhttpGet
request.send(null) ;
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}// ajaxRequest
</script></body></html>
[EDIT]
the onClick is triggered fine. I have verified by inserting alerts into the functions.
[EDIT2]
i suppose it would help if i show the PHP bit too
<?php // urlget.php
if (isset($_GET['url'])) {
echo file_get_contents("http://".sanitizeString($_GET['url']));
}
else {
echo "problem!" ; // [edited line]
}
function sanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>

you have to call xmlhttpGet() somewhere in ur script to get it to 'run'

When your code is not wrapped in a function, it will simply execute as the code is parsed by the browser.
Once you wrap it in a function, it will not execute until the function is explicitly called.
If you want to get the script to run automatically, try changing your body tag to:
<body onload='xmlhttpGet();'>
If you want to fire the function with user interaction, use one of the many events such as onclick or onmouseover or onmousedown

Your xmlhttpget function should start as:
function xmlhttpGet(form)
{
... as it is you're referencing the variable form in the function (eg var $q = form.q.value) but never assigning it a value (so it's being created/pulled from global scope).
The scope of this in your function for onreadystatechange will vary wildly depending on browser and how it's called - not a good design decision, try replacing this with request in the function.

Related

AJAX request to a php file

I am having problems with a really basic request to a php file from AJAX. I am running all this stuff through XAMPP. What I'm trying to do with this code is to echo the name typed into the textbox once the submit button is clicked and the results to be posted in the div "results". I am doing this to try and weed out errors in another script and so far it hasn't gone too well.
<html>
<head>
<script type="text/javascript">
function go() {
var request;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var uname = document.getElementById("name").value;
request.onreadystatechange= function() {
if(request.readyState == 4) {
document.getElementById("result").innerHTML = response.Text;
}
}
url = "win.php?name="+uname;
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>
Name:<input type="textbox" name="jesus" id="name" />
<input type="button" value="Submit" onlick="go()" />
<div id ="result"> Result:</div>
</body>
</html>
<?php
$name = $_GET['name'];
echo $name;
?>
You don't have an object called response, you are looking for the responseText property on the request object.
document.getElementById("result").innerHTML = request.responseText;
Also:
avoid using globals
don't send your HTTP request before the target div exists, you run the risk of it still not existing when the response comes back
you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4).
Don't put raw user input in URLs, escape it with encodeURIComponent first
Use that
document.getElementById("result").innerHTML = response.responseText;

onchange won't print out error for empty input

I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.
For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.
Here's the php part:
if(isset($_GET["isbn"]) )
{
$isbn = $_GET["isbn"];
$error="";
if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
{
$error .= "Please enter a valid ISBN";
echo $error;
}
else
echo $error;
}
Here's the rest:
<script type="text/javascript">
function validateIsbn(keyword)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
document.getElementById("err1").innerHTML = res;
}
}
xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
xhr.send();
}
</script>
<form method="get" action="">
<label class="top-label">ISBN:</label>
<input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
<div id="err1"> </div>
<p></p><p></p>
You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.

Javascript. Passing input variables throughout pages via AJAX

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>

Call php from javascript and return an array from php to Javascript function

I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.
GetFilenme.php is another file and I am trying to access this from Config.html
PHP :
Getfilename.php
<?php
$dir = 'uploads/';
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
if ($file!='.' && $file!='..' )
{
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'<br>';
$Counter = $Counter + 1;
}
}
return $filesArray;
?>
This is assuming you download and include the jQuery javascript library:
$(function() {
$.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
});
This should be your PHP (although very insecure):
<?php
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
?>
Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.
For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).
new Ajax.Request('/validate.php', {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText == 'true')
notice.update('Validation successful');
else
notice.update('Validation failed');
}
});
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;
}
function CallSomePHP(username, password)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="myPhp.php";
url = url+"?username="+username+"&password="+password;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText); // this will alert "true";
}
}
myphp.php
<?
// Get the values of username and password
$username = $_GET['username'];
$password = $_GET['password'];
echo"true";
?>
You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.
<div id="form">
<input type="text" id="email" /><br />
<button id="submit">Submit</button>
</div>
<div id="response">
</div> <!-- load jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>
// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;
$("#submit").click(function(){
// when the user clicks the submit button
// get the value of email and put it in the variable we made above
emailValue=$("#email").val();
/* am going to send a post variable called "email"
* with the value of "emailValue" to a script called receiver.php
*/
$.post('receiver.php',{email:emailValue},function(e){
// "e" is variable that contains the echoed string
// check if it's true or false
if(e=="true")
alert ("valid email");
else
alert("invalid email");
});
});
});
receiver.php
$email=$_POST['email'];
// checkMail is a fictional function that returns a bool
$valid=checkMail($email);
if($valid)
{
// email is valid
echo "true";
}else{
// email is invalid
echo "false";
}
Note: if you are not sending data to the PHP script you should use $.get instead of $.post, it's a little bit faster.
You can also use the JavaScript variable e and load its contents in the response division in your form like this
$("#response").html(e);
This would accomplish the same thing as if you used JQuery's load() function like Coder mentions below.
At the end, do this:
print json_encode($filesArray);
and it will send back a json object, which Javascript can read easily.
If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.
eg:
<script src="Getfilename.php" type="text/javascript"></script>
Then in your PHP, instead of:
return $filesArray;
have it write some JavaScript.
echo "var result = ".json_encode($filesArray).";";
Your $filesArray value will now be in your javascript as the variable result.
<script>alert(result)</script>
The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.
You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.
If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up.
Something like the following:
function GetHttpObject()
{
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return false;
}
You can get it easily by ajax. Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.
p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){} );
html:
<div id="data">
</div>
In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page.
In our php code
//get the posted value into some $value
and
if($value==2)
echo 'true I got 2'
else
echo 'I didnot got 2 You posted wrong value';
This will print true I got 2 in the div #data.
This may not be your exact requirement but its very helpful.

How to pass value from JavaScript to PHP and get return of PHP back to JavaScript [duplicate]

I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.
GetFilenme.php is another file and I am trying to access this from Config.html
PHP :
Getfilename.php
<?php
$dir = 'uploads/';
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file)
{
if ($file!='.' && $file!='..' )
{
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'<br>';
$Counter = $Counter + 1;
}
}
return $filesArray;
?>
This is assuming you download and include the jQuery javascript library:
$(function() {
$.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
});
This should be your PHP (although very insecure):
<?php
$dir = $_REQUEST['dir'] ;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
?>
Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.
For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).
new Ajax.Request('/validate.php', {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText == 'true')
notice.update('Validation successful');
else
notice.update('Validation failed');
}
});
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;
}
function CallSomePHP(username, password)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="myPhp.php";
url = url+"?username="+username+"&password="+password;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText); // this will alert "true";
}
}
myphp.php
<?
// Get the values of username and password
$username = $_GET['username'];
$password = $_GET['password'];
echo"true";
?>
You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.
<div id="form">
<input type="text" id="email" /><br />
<button id="submit">Submit</button>
</div>
<div id="response">
</div> <!-- load jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>
// put this in script type="text/javascript" tags
$(document).ready(function(){
var emailValue;
$("#submit").click(function(){
// when the user clicks the submit button
// get the value of email and put it in the variable we made above
emailValue=$("#email").val();
/* am going to send a post variable called "email"
* with the value of "emailValue" to a script called receiver.php
*/
$.post('receiver.php',{email:emailValue},function(e){
// "e" is variable that contains the echoed string
// check if it's true or false
if(e=="true")
alert ("valid email");
else
alert("invalid email");
});
});
});
receiver.php
$email=$_POST['email'];
// checkMail is a fictional function that returns a bool
$valid=checkMail($email);
if($valid)
{
// email is valid
echo "true";
}else{
// email is invalid
echo "false";
}
Note: if you are not sending data to the PHP script you should use $.get instead of $.post, it's a little bit faster.
You can also use the JavaScript variable e and load its contents in the response division in your form like this
$("#response").html(e);
This would accomplish the same thing as if you used JQuery's load() function like Coder mentions below.
At the end, do this:
print json_encode($filesArray);
and it will send back a json object, which Javascript can read easily.
If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.
eg:
<script src="Getfilename.php" type="text/javascript"></script>
Then in your PHP, instead of:
return $filesArray;
have it write some JavaScript.
echo "var result = ".json_encode($filesArray).";";
Your $filesArray value will now be in your javascript as the variable result.
<script>alert(result)</script>
The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.
You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.
If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up.
Something like the following:
function GetHttpObject()
{
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
try
{
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return false;
}
You can get it easily by ajax. Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.
p['value']=2;//some input value to be posted
$('#data').load('http://example.com/validator.php',p,function(str){} );
html:
<div id="data">
</div>
In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page.
In our php code
//get the posted value into some $value
and
if($value==2)
echo 'true I got 2'
else
echo 'I didnot got 2 You posted wrong value';
This will print true I got 2 in the div #data.
This may not be your exact requirement but its very helpful.

Categories