AJAX - Retrieving data using JavaScript XMLHttpRequest and PHP - php

I am trying to use AJAX on a form so that the user doesn't have to leave the current page to submit their name. I have got the function to work when the user types their name; it changes automatically while they're typing. What I'm struggling with is the onClick to submit the name. I am not receiving any response from the PHP file and I do not know why. Here is my code:
The form page: (The submit function sends the name through a global variable via the GET request)
<script type="text/javascript">
//Decalre the variables of name as Global variable
var name;
//For IE 5 + 6
function httpReq(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function nameTest(str) {
if (str.length==0) {
document.getElementById("nameTest").innerHTML="Please enter your name.";
return;
}
httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("nameTest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","nameTest.php?q="+str,true);
xmlhttp.send();
return name = str;
}
// function to submit the users details to the database
function submit(str) {
httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("submitted").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mailing-list.php?name="+name, true);
xmlhttp.send();
}
</script>
Name: <input type="text" onkeyup="nameTest(this.value)">
<span id="nameTest">Please enter your name.</span>
<input style="width: 100px; height: 40px;" type="button" onclick="submit" value="Join!">
<span id="submitted"></span>
The PHP page which doesn't give a response (Just echoing something simple until I get a response):
<?php
$name = $_GET["name"];
echo "Hello There " + $name;
?>
Can't seem to figure out why there is no response. Any help appreciated!

var name;
//For IE 5 + 6
function httpReq(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else {
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function nameTest(str) {
if (str.length==0) {
document.getElementById("nameTest").innerHTML="Please enter your name.";
return;
}
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("nameTest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","nameTest.php?name="+str,true);
xmlhttp.send();
window.name = str;
}
// function to submit the users details to the database
function submit() {
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("submitted").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mailing-list.php?name="+window.name, true);
xmlhttp.send();
}
You haven't assigned a value to xmlhttp, probably the console tells you it is undefined, you should check it.
Sorry, there are a lot of errors inside your code. I edited it, you should try now.
submit() doesn't get params, it just get the name from the global variable name(window.name), which was set before by the function nameTest(str).
Last thing: you should check compatibility between what you want client and server side. You used "?q=" instead of "?name=" in your query string, pay attention to these things!

According with LightStyle, you should use the return of httpReq() method to retrieve your requestObject.
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {...}
You have to modify
onclick="submit"
into onclick="submit();" to make it called.
This PHP script will return 0, the concatenation operator is . in PHP :
<?php
$name = $_GET["name"];
echo "Hello There " . $name;
?>

Value "name" in your function submit(str) is unknown, and thus empty. change that into
xmlhttp.open("GET","mailing-list.php?name="+str, true);
and call your function like this:
submit("NameToShow");
BTW: Using jQuery would make this alot easier for you.

Related

Second AJAX call unloading result of the first

Code below is run in the onLoad event of the page. I first would like to populate a drop down menu with getCompany() and then fill in data from the server into text boxes and choose the selected option.
Both functions work, in fact when I reload the page with debugger running and step into everything both do what they are supposed to.
When I just open the page or reload with out debugger the text boxes are filled but the options disappear from the dropdown, why is that?
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany();
setTimeout(200);
if (name[0] = "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
function getCompany() {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
I assume the input fields you are filling in data in the second request belong to the data fetched from the first request. I also assume you are using the setTimeout() to delay the 2nd request...
Javascripts are single threaded. To provide asynchronous behavior js uses callback mechanism. After sending a request to the server, js doesn't wait until the response comes. JS keeps executing the rest of code until the results from the server comes. When the response comes from the server the code in the callback function xmlhttp.onreadystatechange is executed. Because of that, both requests may happen at almost the same time and consequently the response for the 2nd request may come before the first response which leads the behavior you see as an error.
When you debug, you execute line by line. Therefore there is enough time to get the response for the first request before getting the response for the second request.
As a solution you can move the code for the second request inside the xmlhttp.onreadystatechange callback in the code for the first request. Then as the callback is always executed after the results are fetched, the second request is sent after the response for the first one comes.
You may google about asynchronous javascript and learn in details...
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany(name);
}
function getCompany(name) {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
if (name[0] == "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
It is happening because of a race condition between the two XHR calls made from getCompany and getTenant methods. Even though you are making the getTenant call 200ms after making the first XHR call there is no guarantee that the getComapny XHR call will finish first. When that happens the follwoing line of code
document.getElementById("company").innerHTML = xmlhttp.responseText;
removes all the options from the menu and also resets the selected index. To circumvent this issue do not make getTenant(id); call from init method. Instead make it from the success handler of the getCompany XHR call.
xmlhttp.onreadystatechange=function x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
**getTenant(id);**
}
}
Make two different object name instead of one (xmlhttp). Like
in 'getCompany()' function object name is 'xmlhttp'
in 'getTenant()' function changed object name to 'xmlTalenthttp' (or any other name which you wish)

Remove document and update database

I have 2 files that assist me in removing the document and updating the database.
My first file consists of 1 form with a remove button and a javascript function called remove(). Second php page would be removing the file which it does not return any results.
Code for Remove.php (Upon calling out remove() function):
$Doc=$_GET['Doc']; //Value get from remove() function
$ID= intval($_POST['ID']);
$FirstReport= $_POST['FirstReport'];
$SecReport = $_POST['SecReport'];
$FirstReportPath= $_POST['FirstReportPath'];
$SecReportPath = $_POST['SecReportPath '];
$DB = new PDO('sqlite:/database/Student.db');
//If i click remove firstreport button, i'll check it to see if it's the same
if(($Doc) == ($FirstReport))
{
$result= $DB->query("Update Student set FirstReport='No' WHERE ID=".$ID);
//This unlink should remove the document file from the path.
unlink($FirstReportPath);
echo "success";
}
else
{
//same code repeated as if statement
}
Javascript function
function RemoveDoc(Doc)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","functions/Resubmit.php?Doc="+Doc,true);
xmlhttp.send();
document.getElementById("RemoveMsg").innerHTML=xmlhttp.responseText;
return false;
}
I did try to alert(Doc) out and the document name does show but on the second remove.php, it does not run any of the coding. Tried "GET"/"POST" also the same results. Kindly advise.
It looks like your sending a post request, but sending your document name in the url, a $GET variable.
either switch to a get request:
function RemoveDoc(Doc)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","functions/Resubmit.php?Doc="+Doc,true);
xmlhttp.send();
document.getElementById("RemoveMsg").innerHTML=xmlhttp.responseText;
return false;
}
or send the document name as a post parameter:
function RemoveDoc(Doc)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","functions/Resubmit.php",true);
xmlhttp.send("Doc="+Doc);
document.getElementById("RemoveMsg").innerHTML=xmlhttp.responseText;
return false;
}
Also, your not waiting for a response from the server.
function RemoveDoc(Doc)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","functions/Resubmit.php",true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("RemoveMsg").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send('Doc='+Doc);
return false;
}
You have to send the values ad post to access from $_POST superglobal. Just modify the Javascript code
function RemoveDoc(Doc,FirstReport,SecReport,FirstReportPath,SecReportPath)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","functions/Resubmit.php",true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("RemoveMsg").innerHTML=xmlhttp.responseText;
}
xmlhttp.send("Doc="+Doc+"&FirstReport="+FirstReport+"&SecReport="+SecReport);
//do for others also in the same way
return false;
}

How do I send a javascript value to a PHP page, then reference that value IN the PHP page?

How do I send a javascript value to a PHP page, then reference that value IN the PHP page?
Assuming I have some sort of javascript AJAX solution such as this:
var id=5;
obj.onreadystatechange=showContent;
obj.open("GET","test.php",true);
obj.send(id);
I want to work with this particular id in the test.php. How can I do this?
In the javascript (I'm making a function so you can assign it to some other event)
//jQuery has to be included, and so if it's not,
//I'm going to load it for you from the CDN,
//but you should load this by default in your page using a script tag, like this:
//<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"><\/script>')
function sendValueGet(passedValue){
jQuery.get('test.php', { value: passedValue });
}
function sendValuePost(passedValue){
jQuery.post('test.php', { value: passedValue });
}
And then in your PHP:
<?php
if( $_REQUEST["value"] )
{
$value = $_REQUEST['value'];
echo "Received ". $value;
}
?>
Notice that I use "value" in the javascript "object" { value: ... } and in the PHP "REQUEST" variable $_REQUEST["value"]
If you want to give that a different reference name, then you need to change it in both places.
Using GET or POST is your preference.
Change your code to this:
obj.open("GET","test.php?id=" + id,true);
obj.send();
Then in test.php use $_GET['id']
//GET
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("GET","test.php?q="+id,true);
xmlhttp.send();
in test.php
$id=$_GET['q']
//POST
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send("x=id");
in test.php
$id=$_POST['x']

Passing multiple value in ajax using <a> tag, and retrieving a value that was submitted

This is a very simple function if one where to use an input tag, unfortunately i have to use a link tag since i'm working with alphabet grouping that would retrieve the values on a different page.
here's a code i found for link tag to hold a value to be submitted to ajax
echo '<a onclick="passPagination(\'3\');passLetter(\'S\')">NEXT</a>';
i want to call all letters "s" page "3" from the other page.
function passLetter(str)
{
if (str=="")
{
document.getElementById("retail_group").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("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?letter="+str,true);
xmlhttp.send();
}
function passPagination(str)
{
if (str=="")
{
document.getElementById("retail_group").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("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?pageno="+str,true);
xmlhttp.send();
}
also i want to call again the letter that was passed to the otherpage so that i would make it as a reference for my pagination links that is also being hold in this page.
echo 'NEXT';
i am really at lost here since i am not familiar with link tag and ajax working together, also as you may have noticed i am not also that good with ajax judging from my very long ajax code.
Your help is greatly appreciated, Thank You.
i am really new at ajax. :)
The solution is to make a function with multiple arguments:
function passPaginationAndLetter(page, letter)
{
if (page=="" || letter == "")
{
document.getElementById("retail_group").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("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?letter="+letter+"&pageno="+page,true);
xmlhttp.send();
}
You can now call this with
echo '<a onclick="passPaginationAndLetter(\'3\',\'S\')">NEXT</a>';
The difference is that you are not calling two AJAX methods, just one.
I'm not pretty sure if i got what you mean, but i guess you want to something like that
echo '<a onclick="get(\'S\', '. ($_GET['page'] + 1) .')">NEXT</a>';
function get(letter, page) {
if (!letter) {
document.getElementById("retail_group").innerHTML="";
return;
}
if (!page) {
page = 1;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?letter=" + letter + "&pageno=" + page,true);
xmlhttp.send();
}
if it's really that, don't forget to validate the variables got from $_GET before use that, i just didn't because it's not the point...
I think this is what you're looking for:
html
PREVIOUSNEXT
javascript
var current = {
page: 0,
letter: a
};
function ajax(url) {
var xmlhttp = window.XMLHttpRequest || new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByI("retail_group").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function next() {
ajax("otherpage.php?letter=" + current.letter + "&pageno=" + (++current.page));
}
function previous() {
ajax("otherpage.php?letter=" + current.letter + "&pageno=" + (--current.page));
}
This code is not complete of course, it doesn't check for the max/min values of the pages, and there's no way of replace the letter, but it should point you in the right direction.

Calling a PHP page with MySQL query from Javascript function then returning results to another javascript function

I am refactoring some code. I have a PHP page that contains a MySQL query and stores the result in a PHP variable $my_result. This result is then echoed to a Flash SWF during embedding with SWFObject.
I now want to call this PHP page that makes the query from a javascript function like so - one change I have made to the PHP is that instead of storing the result in a variable $my_result I am echoing the result.
Javascript function to call the PHP page and make the database query
function getNewUploads() {
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) {
alert(xmlhttp.responseText); // shows the correct output in an alert box
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","dBaseConnect_uploadStep2.php",true);
xmlhttp.send();
}
Then I have the embedding of the Flash which I only want to happen when a certain tab is clicked on a page and is handled by jabvascript -
function show_tab(tab_id) {
$(tab_id).show();
if(tab_id == "#tab_2") {
var data_string = getNewUploads(); // CALLING THE FUNCTION TO CALL THE PHP QUERY
alert(data_string); // shows undefined in the alert box
var so = new SWFObject(".....");
so.addVariable("theDataString", data_string);
so.write("flashcontent2");
}
}
So it seems that the getNewUploads() function does not return the result from the PHP page.
Can anyone shed some light on my mistake please. Thanks
The call is asynchronous. After you call send, the call begins in the background. In the meantime, getNewUploads returns. Later, the function you've assigned is called with the answer. When you do return xmlhttp.responseText, you're returning from this anonymous function (assigned to onreadystatechange), not from getNewUploads (which is already done).
You can use a callback instead. Something like:
function getNewUploads(callback) {
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) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET","dBaseConnect_uploadStep2.php",true);
xmlhttp.send();
}
function show_tab(tab_id) {
$(tab_id).show();
if(tab_id == "#tab_2") {
getNewUploads(function(data_string) {
alert(data_string);
var so = new SWFObject(".....");
so.addVariable("theDataString", data_string);
so.write("flashcontent2");
}); // CALLING THE FUNCTION TO CALL THE PHP QUERY
}
}
We define getNewUploads to take a single argument, callback. Then, in the success function, we call the callback with a single argument, the response text. In show_tab, we pass an anonymous function that takes a single parameter (the response text) to getNewUploads, as the callback parameter.
The true in xmlhttp.open("GET","dBaseConnect_uploadStep2.php", true); makes it asynchronous and hence the error. Change it to:
function getNewUploads() {
//initialize xmlhttp
xmlhttp.open("GET", "dBaseConnect_uploadStep2.php", false);
xmlhttp.send();
if(xmlhttp.status == 200)
return xmlhttp.responseText;
else
return "Oops :(";
}

Categories