Php not receiving post from JavaScript - javascript

I have implemented the same setup elsewhere in my site and can't figure out why it's not working this time.
When a user clicks the accept button, it calls a JavaScript function acceptOrder(orderID) which passes the orderID onto a php page to update a record in the db.
orderID is assigned ok in the JavaScript but it doesn't reach the php. Var_dump on POST shows nothing, nor does $_POST('orderID'). I've even tried just sending an integer to the php in case there was a problem with the var but it made no difference.
Js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft. }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
Php
<?php
require_once("config1412/class.shop.php");
session_start();
$shop = new SHOP();
echo var_dump($_POST);
//$orderID = $_POST['orderID'];
//echo "orderId var = ".$orderID."<br/>post ".$_POST['orderID'];
//$shop->acceptOrder($orderID);
?>
Needless to say I've searched about and don't see any solutions elsewhere.
Many thanks

As i can see, you didn't set variable name for orderID, change line of code:
xmlhttp.send(orderID);
to:
xmlhttp.send("orderID="+orderID);
If it's only SQL error of missing orderID, and all other passess okay, it's solution for you. As you said in comments "I just get a sql error because the variable orderID is empty".
You're missing only naming post send data, that's why it's empty.

Please replace this line
xmlhttp=new ActiveXObject("Microsoft. }
with following this line
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

You should write this in your js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}

I would recommend you to use jQuery for ajax calls. It's much easier to setup and straightforward. Especially, and specialy because it is very easy setup for a beginner. And for people who want to install ajax the easy way. I use it every single time I want to do ajax in my code. Here is a link:
http://api.jquery.com/jquery.ajax/
Just put the tag to include jQuery and then one javascript command to call the ajax.

Related

Sending a javascript AJAX request triggers multiple page loads

I have searched but cannot find an answer to this issue. I am calling an asynchronous javascript file and the php page it calls makes a database entry twice.
window.onload = function(){
var xmlhttp;
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);
//document.write(xmlhttp.responseText);
return;
}
}
xmlhttp.open("POST","http://example.com/api/tracking/index.php?cid=" + get["clientId"] + "&refUrl=" + encodeURIComponent(siteURL) + "&auk=" + get["auth"],true);
xmlhttp.send();
}
The index php page does an insert and returns the new row id. The alert in the successful response corresponds to that id, but there is another entry made one millisecond before. I assume this is happening because the page is being accessed until it gets the ready state of 4. The question is how do I stop or bypass this?

AJAX request with if statement for filename called

I'm making a quiz using AJAX to refresh each question. Instead of having individual AJAX calls for every different question in the quiz, I was wondering if there might be an easy way to use the same AJAX call but add a digit to the end of the filename each time.
So here is the basic AJAX request:
function nextQuestion()
{
var xmlhttp;
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("wordbank").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","question2.php",true);
xmlhttp.send();
}
As you can see the GET request pulls a file called question2.php
xmlhttp.open("GET","question2.php",true);
This is just a stand-in file at the moment, what I really want to do is something like this:
xmlhttp.open("GET","question" i++ ".php",true);
OK, I phrased that badly, but I'm not sure if this is the best way to do this. Essentially I want to have my button bound to the nextQuestion() function, but I want to work out a way to generate the next filename based on the one you're currently on.
Is this possible?
Another idea would be to give the button on each page a different ID and have the nextQuestion() function take that ID and use it to generate the next file. E.G if you are on question 2, the button would have an ID of question2. The ajax would take the last digit (2) and add 1 to it, so the filename called would be question3.php - and that is how it would know to move to the next question.
Here you go you can now place an ID on any button and have it take you to the correct page.
Your JS
function nextQuestion(buttonID)
{
var xmlhttp;
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("wordbank").innerHTML=xmlhttp.responseText;
}
}
var splitID = buttonID.split('_');
var questionID = splitID.pop();
xmlhttp.open("GET","question" + questionID + ".php",true);
xmlhttp.send();
}
Your Button
<button id="question_2" onClick="nextQuestion(this.id)">Go To Question 2</button>
or
<button id="question_14" onClick="nextQuestion(this.id)">Go To Question 14</button>
so build a string with the current index you have
xmlhttp.open("GET","question" + i + ".php",true);
You can have a global var with the current quest and do something like this:
var current_quest=1;
function nextQuestion()
{
...
xmlhttp.open("GET","question"+current_quest+".php",true);
xmlhttp.send();
window.current_quest++;
...
}

Show Save-As window from JSP

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
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);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

AJAX function(this)

I am not familiar with ajax, I am in the process of learning, but as far as I know, it utilizes javascript to access the DOM, so my question is, is it possible to put an argument inside a function?
<script type="text/javascript">
function loadXMLDoc( * * this * * ) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", ""
test.php ? access = "**+this**", false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
</script>
Shouldn't this work?
Thank you so much for your help.
this in JS changes according to the context you are running in. Depending on how you call it, it will change.
Read this article for more information : http://www.quirksmode.org/js/this.html
xmlhttp.open("GET",""test.php?access="**+this**",false);
This call wouldn't make much sense since this refers to an object, but what you're actually attempting to do is string concatenation (adding two strings together).
If you need to make variable calls, use a variable instead of the this keyword.
function loadXMLDoc(accessVar) {
....
xmlhttp.open("GET","test.php?access=" +accessVar ,false);
}
loadXMLDoc('accessIdentifier'); //passes the value 'accessIdentifier' to your method so it is passed along in the querystring.
You're close. It looks like you're using the example from w3schools. Be warned, that site is not always the most reliable source. See http://w3fools.com/ for more info.
Look over their code again, as it is taken from their page:
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
As you can see, the "on success" code is located within the onreadystatechange event handler. Your example code has three problems: one with the way you're passing a variable, two with the way you use this, and three that your response handler won't work as expected.
var xmlhttp;
var var1 = 'testdata';
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)
handleAjaxResponse(responseText);
}
xmlhttp.open("GET","ajax_info.php?var1="+var1,true);
xmlhttp.send();
function handleAjaxResponse(resp) {
document.getElementById("myDiv").innerHTML=resp;
}
In terms of this, it refers to the current scope of execution, a different subject entirely. It isn't a variable you'd pass via AJAX.

Ajax and VbScript: fetching Post variable in test.asp

current i am trying to use ajax for my site ....... because of size of data is not limited i need to use post method for send data to database but the problem is i am unable to fetch the Post variables in the test.asp
here is the script i am using
function SaveData(content )
{
var xmlhttp;
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)
{
msg=xmlhttp.responseText;
alert(msg);
}
}
var para = encodeURIComponent("content="+content)
xmlhttp.open("POST","test.asp",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(para)
}
and here is test.asp code
t = Request.form("content")
Response.write(t)
please help me solving this problem of fetching the Post method variable in test.asp
if possible any one can share code of jquery ajax with post method in asp classic too that would also be helpful
You need to change this:
var para = encodeURIComponent("content="+content)
into this:
var para = "content=" + encodeURIComponent(content);
The way that it was, you were submitting something like this to the server:
content%3Dtest%20data%20123
With the adjusted line of code, you're submitting something like this, which is as it should be:
content=test%20data%20123
Have you considered using a JavaScript library such as jQuery? A library will abstract away all this unpleasantness:
$.post("test.asp", { 'content': content }, function(data) {
alert("Returned data: " + data);
});

Categories

Resources