Javascript-Ajax not able to send any data - php

i am having trouble making this part of code to work, basically i want to call this function which sends a variable to a php page. Ive tested that the variable is there and also tested that my php page is accepting information as it should be , however i cant make this Ajax thing work.
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else
{ // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name=myname';
AJAX.open("POST", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
This is my php part which should accept the variable
<?php
$var=$_GET['Name'];
echo $var;
?>

Okay firstly you need to change your request to GET from POST
like
AJAX.open("GET", url, true); // Open the url this object was set-up with.
and you also need to update this line
from
var url='http://localhost/main.php?Name=myname';
to
var url='http://localhost/main.php?Name='+myname;
my full script is:
<script type="text/javascript">
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name='+myname;
AJAX.open("GET", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
</script>
you might also be missing the callback function so add it so that it looks like this
function callback(x, y) {
alert(x);
}
And call your AJAX function by
ajaxRequest("ashley");
Here is your required main.php code (even though this isn't what you should be using AJAX for
<?php
session_start();
if(isset($_GET["Name"])) {
$_SESSION["Name"] = $_GET["Name"];
}
if(isset($_SESSION["Name"])) {
echo $_SESSION["Name"];
} else {
echo "The AJAX has not been run!";
}
?>

There are two ways to send an ajax request to server
Either GET or POST
1. GET Method:
var url='http://localhost/main.php?Name='+myname; // you can add any numner of vars here
AJAX.open("GET", url, true);
AJAX.send();
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['Name'];
}
2. POST Method:
AJAX.open("POST","ajax_test.asp",true);
AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
AJAX.send("Name="+myname);
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_POST['Name'];
}

Related

How do I get ajax to intermittently call my php?

I have ajax that is communicating with php to receive tweets from a twitter account. The code is working fine.
The only thing is I want the ajax to intermittently call the php so that any updated tweets automatically come back and get printed to my page without having to refresh or re-enter a twitter id.
Do I need to keep calling the getStatuses() function or something?
Or do I need to use the getUpdates() which I have started to make somehow?
Here are my ajax functions:
// the setInterval function added in the getStatusesX function
function getStatusesX()
{
setInterval(getStatuses(),300000);
}
//Create a cross-browser XMLHttp Request object
function getXMLHttp() {
var xmlhttp;
if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
XMLHttp = new XMLHttpRequest();
} else {
alert("Your browser does not support XMLHTTP!");
}
return XMLHttp;
}
//function that searches for the tweets via php
function getStatuses(){
XMLHttp1 = getXMLHttp();
var userID = document.getElementById("userid").value;
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'twitterTest2.php?userid='+userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
}
XMLHttp1.send(null);
}
//function to intermittently call php to check for updated tweets?
function updateInfo() {
if(XMLHttp1.readyState == 4) {
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
</script>
I then added the getStatusesX() function to my form as follows:
<form>
Input Twitter ID: <input type="text" name="userid" id="userid">
<button type="button" onClick="getStatusesX()";>Get recent tweets</button>
</form>
It's still not working. Am i using the setInterval in the wrong way?
Use the setTimeout or setInterval functions.
From what I can see in your code, getStatuses has too much responsability since in addition of getting the data, it also modifies the DOM.
I would suggest something like:
function getStatuses(callback) {
//...
XMLHttp1.onreadystatechange = function () {
//...
callback && callback(XMLHttp1); //execute callback if any
};
}
function updateStatuses(callback) {
getStatuses(function (xhr) {
document.getElementById("tweetbox").innerHTML = xhr.responseText;
callback && callback;
});
}
//this function update the statuses and as soon as it's finished, it sets
//a timeout to redo the process in ~10 seconds.
function startUpdatingStatuses() {
updateStatuses(function () {
setTimeout(startUpdatingStatuses, 10000);
});
}
startUpdatingStatuses(); //kick-start everything

Chained Select Menu - works, but requires a small change - AJAX

I am currently using the following script to run a PHP script each time a dropdown menu option is selected. It works great.
It then returns the results from a SQL query and places it in a 2nd dropdown.
However, I would also like to run a PHP script when the web page initially loads.
Basically, I hope my select menu ("2nd dropdown") will be populated with the results of the PHP script when the page first loads. And the user can then filter the results down by using the first dropdown menu.
Here is my current Javascript file. I'm not using jQuery.
// Have a function run after the page loads:
window.onload = init;
/* ------------------------------------------------------------------------
* Can I run this...
* ajax.open('get', 'dept_results_ajax.php');
* ... as soon as my page loads and return the results?
* ------------------------------------------------------------------------
*/
// Function that adds the Ajax layer:
function init() {
// Get an XMLHttpRequest object:
var ajax = getXMLHttpRequestObject();
// Attach the function call to the form submission, if supported:
if (ajax) {
// Check for DOM support:
if (document.getElementById('results')) {
// Add an onsubmit event handler to the form:
$('#did').change(function() {
// Call the PHP script.
// Use the GET method.
// Pass the department_id in the URL.
// Get the department_id:
var did = document.getElementById('did').value;
// Open the connection:
ajax.open('get', 'dept_results_ajax.php?did=' + encodeURIComponent(did));
// Function that handles the response:
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse(ajax);
}
// Send the request:
ajax.send(null);
return false; // So form isn't submitted.
} // End of anonymous function.
)} // End of DOM check.
} // End of ajax IF.
} // End of init() function.
// Function that handles the response from the PHP script:
function handleResponse(ajax) {
// Check that the transaction is complete:
if (ajax.readyState == 4) {
// Check for a valid HTTP status code:
if ((ajax.status == 200) || (ajax.status == 304) ) {
// Put the received response in the DOM:
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
// Make the results box visible:
results.style.display = 'block';
} else { // Bad status code, submit the form.
document.getElementById('dept_form').submit();
}
} // End of readyState IF.
} // End of handleResponse() function.
EDIT
// ajax.js
/* This page defines a function for creating an Ajax request object.
* This page should be included by other pages that
* need to perform an XMLHttpRequest.
*/
/* Function for creating the XMLHttpRequest object.
* Function takes no arguments.
* Function returns a browser-specific XMLHttpRequest object
* or returns the Boolean value false.
*/
function getXMLHttpRequestObject() {
// Initialize the object:
var ajax = false;
// Choose object type based upon what's supported:
if (window.XMLHttpRequest) {
// IE 7, Mozilla, Safari, Firefox, Opera, most browsers:
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE browsers
// Create type Msxml2.XMLHTTP, if possible:
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { // Create the older type instead:
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
} // End of main IF-ELSE IF.
// Return the value:
return ajax;
} // End of getXMLHttpRequestObject() function.
Many thanks for any pointers here.

Ajax http.responseText URL vs text

Is it possible to choose what response to get back from a PHP script called with ajax. It is possible to say that instead of getting back what the script writes that I want the entire script to be treated as a URL and have that as the response?
I am calling a PHP script like this.
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function LoadCalendar() {
http.abort();
http.open("GET", "luxcal/index.php?cP=2", true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
/* document.getElementById('litcal').src = http.responseText; */
document.getElementById('litcal').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
Loading the PHP script response in a div innerHTML works. I would rather load the response in an iframe. Does the http object have an option to get the URL response, e.g. http.responseURL? I could then do document.getElementById('litcal').src = http.responseURL. Thanks.
if you want to load response in an iframe, just do it in HTML without using AJAX
HTML
<iframe id="litcal"></iframe>
Javascript
<script type="text/javascript">
document.getElementById('litcal').src = 'luxcal/index.php?cP=2';
</script>

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