im having a setback, im making an Html page with javascript, and im using AJAX to call Perl functions. The thing is when my Perl program doesn't need parameters the calling is trivial. But i have a function to open and read a file so i need to give the location of the file to the perl script, thus having to passe it trough a paramenter in the AJAX calling.
Ex working call:
function getOption(){
var selectmenu=document.getElementById("Select1")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing"){
var s = chosenoption.text;
openFile("C:\PerlTest\test.txt");
}
}
}
EX. not working trying to pass parameter:
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Im attempting to pass the paremeter in that way because of this example:
http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201
Can anyone help??
Thanks a lot.
After the sugestion of Kinopiko, that makes sense, i have the following:
HTML-
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
var container = XMLHttp.responseText.split("\n");
if (container.length>0){
for ( i=0; i< container.length-1;i++){
document.getElementById("TxtArea").innerHTML += container[i] + " ";
}
}
}
else{
document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Perl script:
#!c:/Perl/bin/perl
use strict;
use CGI qw/param/;
use URI::Escape;
print "Content-type: text/html\n\n";
my $file = param ('file');
$file = uri_unescape ($file);
open (MYFILE, $file);
while (<MYFILE>) {
chomp;
print "$_\n";
}
close (MYFILE);
Now i dont get error in javascript, but my XMLHttp.readyState is never 4, so i dont get the content of the file.
Maybe im using the encodeURI wrong??
Thanks.
First of all you need to add a question mark:
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+name, true);
Also you need to percent-encode "name" using encodeURI.
On the Perl end, you can use a module like CGI to get the value of the file:
use CGI qw/param/;
my $file = param ('file');
Then
use URI::Escape;
$file = uri_unescape ($file);
open (MYFILE, $file);
should be
open (MYFILE, $file) or die "Cannot open file $file: $!\n";
Related
Website coding surely is awesome and I recently rialized that JavaScript and Ajax are really essential elements in order to build a outstanting website. I've done the research on internet, but the results weren't that useful. Every code included Jquery, which I don't comprehend. Also JSON is slightly unclear regarding the objects, etc.
W3schools published a few examples on how to generate an Ajax code that reacts with a PHP file. This data is retrieved through 'resonseText'. However this element only retrieves one unselected PHP string.
Is there a method to select specific variables or values from the PHP file and accordingly send it back to the Javascript (Ajax) file, so I can subsequently utilize them for further Javascript coding.
Thank you in advance. (It would greatly help, since Ajax is such a complex form of JavaScript.)
My Ajax code, to send data to the PHP file
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 (this.readyState == 4 && this.status == 200) {
var XMLResponse = this.responseText ;
document.getElementById("nameInputNote").innerHTML = "Status: " + XMLResponse ;
}
} ;
xmlhttp.open("GET","ajaxIndex.php?rq1="+valueNameInput,true) ;
xmlhttp.send() ;
The PHP code:
<?php
$rq1 = $_GET['rq1'] ;
if (empty($rq1) ) {
} else {
$sql1 = "SELECT userName FROM users WHERE userName = '{$rq1}' " ;
if ($result1 = mysqli_query($connection, $sql1) ) {
$resultsSql1 = mysqli_num_rows($result1) ;
if ($resultsSql1 == 0) {
echo "vacant" ; //select this value with JS
$permission = "true" ; //and select this value separately with JS
} else {
echo "occupied" ; // or in this senario: select this value
$permission = "false" ; // and this value
// In this case the $permission variable is needed to determine whether a form should be submitted or not.
}
}
}
Try with
let src = <?php echo json_encode($yourVar); ?>;
And then use that variable. Other ways you can do that is to use axios, cookie or VueJS and pass data into component. Hope that helps.
I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";
I've been learning to use AJAX with the GET request that allows me to access a PHP script with an array of data on a server. I want to be able to send a request that tells the server to run code that will open an application and manipulate some info on this application.
Here is the code I use to firstly communicate with the server, then send a request to the server and finally handle responses from the server.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("cant create that object hoss");
}
else
{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
Here is the PHP I was using while I was learning how to use AJAX. I got the following error when I printed the 'xmldom' variable from the above code to the console and inspected it - "error on line 2 at column 1: Extra content at the end of the document". This may be a different question to my original post, but I thought I'd bring up that this error occurred. This then had a knock on effect for the line 'var message = text.childNodes[0].nodeValue;' which produced the error - "Uncaught TypeError: Cannot read property 'childNodes' of undefined".
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>':
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food, $foodArray))
echo 'We do have '.$food.'!';
elseif($food == '')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
The code that I have been working with to learn AJAX may not be relevant, I just thought I'd post it in case I can use some of this code that has already been written.
To sum up, I want to be able to do be able to send a boolean, or whatever is viable with AJAX, to the server that tells it to run a script. This script will then open a Maya application and run some Python code that I have written.
Thank you in advance!
As soon as you call the PHP file, this begins running code on the server. If you want to run an external application from PHP, take a look at the exec() function:
http://php.net/manual/en/function.exec.php
You have jQuery listed in your question tags. Have you compared the javascript and jQuery code?
The advantages of using jQuery are:
less typing,
simpler structure
automatically cross-browser
easily use Promises interface
Have a look at these examples and see if you prefer the jQuery AJAX methodologies:
Three simple examples
dynamic drop down box?
Chain AJAX Requests with jQuery Deferred
I changed the GET methods into POST in php and ajax files but the logical error here is that every time I add a student into the database it doesn't work. I can't really figure out the problem because I'm new to AJAX.
Here's my code:
php file for adding
<?php
//I changed to POST
$q1=$_POST["q1"];
$q2=$_POST["q2"];
$q3=$_POST["q3"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("stud", $con);
$sql="INSERT INTO stud_info(IDno, LName, FName) VALUES ('$q1', '$q2', '$q3')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
getting the stud id
<?php
$q=$_POST["q"]; //I changed to POST
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("stud", $con);
$sql="SELECT * FROM stud_info WHERE IDno like '".$q."%'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>IDno</th>
<th>LName</th>
<th>FName</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['IDno'] . "</td>";
echo "<td>" . $row['LName'] . "</td>";
echo "<td>" . $row['FName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
JavaScript for ajax It doesn't work very well
// JavaScript Document
var xmlHttp;
function showStud(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getStud.php";
url=url+"?q="+id;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function addStud(id, ln, fn)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="addStud.php";
url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function editStud(id, ln, fn)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="editStud.php";
url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function deleteStud(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="deleteStud.php";
url=url+"?q="+id;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
There are few things I would like to point out. First you are executing the function stateChanged here:
xmlHttp.onreadystatechange=stateChanged;
and assigning the RESULT of that function (which in this case is undefined) to xmlHttp.onreadystatechange.
Now, when the readystate changes, XMLHttpRequest attempts to call onreadystatechange which is now undefined, so nothing will happen.
Try this:
function stateChanged(){
return function(){
if(xmlHttp.readyState==4){
if (xmlHttp.status==200){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
}
}
Now, you are still assigning the result of the function to http.onreadystatechange, but this time it is a callable function instead of undefined.
And second, to POST data like an HTML form, add an HTTP header with setRequestHeader(), and specify the data you want to send in the send() method, like this:
// Example of deleteStud(id) function
var url="deleteStud.php";
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged();
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q="+id);
Edited:
For example, your showStud function would be like this,
function GetXmlHttpObject(){
// your code
}
function stateChanged(){
return function(){
if(xmlHttp.readyState==4){
if (xmlHttp.status==200){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
}
}
function showStud(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert ("Browser does not support HTTP Request");
return;
}
var url="getStud.php";
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged();
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q="+id);
}
So change your other functions accordingly.
Re-edited:
There are few additional key things you need to know.
1) The correct order of calls is:
new XMLHttpRequest
xmlHttp.open()
xmlHttp.onreadystatechange = ...
xmlHttp.send()
In some browsers, calling .open clears any event handlers on it. This allows for clean re-use of the same xmlHttp object, which is supposedly more memory-efficient (but that really doesn't matter if you code properly to let the GC do its job). So, simply put the .open call before the onreadystatechange assignment and you should be good to go.
2) onreadystatechange isn't just fired once. It's fired multiple times, you need to be able to handle that. These are the codes you need to handle:
0 UNSENT - open()has not been called yet
1 OPENED - send()has not been called yet
2 HEADERS_RECEIVED - send() has been called, and headers and status are available
3 LOADING Downloading - responseText holds partial data
4 RESPONSE is ready - The operation is complete
Hence your error check should be inside the xmlHttp.readyState==4 check, like this:
if(xmlHttp.readyState==4){
if (xmlHttp.status==200){
// your code
}
}
POST method via JS XMLHttpRequest compared to GET is a bit different.
Just a quick untested example:
GET
url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
xmlHttp.open("GET",url,true);
xmlHttp.send();
POST
url=url; // stays the same
xmlHttp.open("POST",url,true);
xmlHttp.send(q1="+id+"&q2="+ln+"&q3="+fn); // params go into .send()
You can find working examples at w3schools.com
Based on your source
addStud function is missing xmlHttp.setRequestHeader
and xmlHttp.send string is missing & connecting parameters
like so:
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q1="+id+"&q2="+ln+"&q3="+fn);
Undefined index: q in the $q=$_POST["q"]; in the php file
Maybe because you are using q1 in your php file while on the javascript file you are using q only or vice versa. Make it the same and it should work fine.
And don't forget to add this before xmlHttp.send :
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
You changed your requests to post - but it seems that you didn't change the placement of your paramters. You still attach them to your url:
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
You send "null" in the request body.
You will need to send the paramters in the body to make it work as expected by you. Refer to this: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp for further information.
Edit: Small (non-tested) Example:
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("q=test?data=asd?moredata=das");
Update: Since you attached the dropbox folder / content I tried it.
You are still missing the essential function seRequestHeader as listed above. After adding this i am able to read the POST data.
Example for your code:
xmlHttp.open("POST","getStud.php",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("q="+id);
IMPORTANT: The seRequestHeader function needs to be called AFTER the open function and BEFORE the send function.
Endpoint dumps the POST variable and displays content as proof that it works
Okay, I've been struggling with this for a few hours now. I'm using ajax to update a div in my site with a php code however, i'm trying to send parameters in the function from the external javascript file to update the correct link(there are multiple drop down boxes)
for example: this is my select box
<script type='text/javascript' src='ajax.js'></script>//include ajax file
<select onchange='MakeRequest(raceupdate);
this.options[this.selectedIndex].value;'> //so no use of a button is needed to auto link to anchor tag
<option>Deathmateched</option>
<?php
dmList()
?>
</select>
Then next my external ajax function MakeRequest().
function MakeRequest(value)
{
var linkInfo = "teleport.php?call=" + value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
So as you can see I'm trying to pass a sting of text into this function, but I seem to be failing somewhere.
You probably want to setup your tag to pass "this". I don't see where your raceupdate variable is declared, unless it's global... in which case you should show us what you're doing with that variable.
<select onchange='MakeRequest(this);'>
<option>Deathmateched</option>
<?php
dmList();
?>
If you did it that way, you'd have to change this function as such:
function MakeRequest(element)
{
var linkInfo = "teleport.php?call=" + element.value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
And what are you trying to do here?
this.options[this.selectedIndex].value;
In your comments, it looks like you're saying you want to jump to an anchor tag? If so, then you would want to do something like
var anchorTag = document.getElementID("YOUR_ANCHOR_TAG_ID");
anchorTag.focus();