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;
}
Related
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)
Hi I am new to this forum and hoping someone could help I have set a dropdown menu with option value dynamically pulling in from a mysql database. these values when selected use xml to return the ids and content according to whats been selected. In the url there is a variable which im having trouble getting PHP to create a session variable from it. Can this be done? Thanks
Thanks, this is the code where the url is set
function showUser(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("state").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("state").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send(null);
}
The php call '$id = $_GET['q'];
$_SESSION['q'] = $id;'
Do you mean this?
http://www.domain.com/?action=delete
$action = $_GET['action'];
$_SESSION['action'] = $action;
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.
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']
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 :(";
}