I have a form that executes an AJAX function to submit form values to a PHP page. The PHP page just responds by echoing out the variables in a DIV.
It works with GET method, but I can't get it working with POST.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Browser Not Supported");
return false;
}
}
}
// Get Response
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("response").innerHTML = ajaxRequest.responseText;
}
}
var name=document.getElementById("name").value
var email=document.getElementById("email").value
ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='Form1'>
Name: <input type='text' name='name' id="name"/> <br />
Email: <input type='text' name='email' id="email"/> <br />
<input type="button" value="Submit" onClick="ajaxFunction();">
</form>
<div id="response">
</div>
</body>
</html>
And the php page, process.php
<?php
echo date("H:i:s");
echo "<br/>";
// echo "Post Variables: ".$_POST['name']." ".$POST['email']; old code
echo "Post Variables: ".$_POST['name']." ".$_POST['email'];
echo "<br/>";
echo "Get Variables: ".$_GET['name']." ".$_GET['email'];
?>
The response I get is:
11:32:05
Post Variables:
Get Variables: name entered email entered
So i'm pretty sure it's to do with the variable being passed from PHP to Javascript.
Many thanks.
ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
ajaxRequest.send(null);
That's not posting the variables. Here you're sending them as GET parameters, with an empty body for your POST request. Instead, use
ajaxRequest.open("POST", "process.php", true);
ajaxRequest.send("name="+name+"&email="+email);
or even better
ajaxRequest.open("POST", "process.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email));
Related
I've searched everywhere but can't find an answer to this problem.
I'm writing a little ajax script but can't get the correct value of the POST request.
This is the code so far:
<textarea id="message" name="message" style="width:100%;"></textarea>
<input value="SEND" style="border-radius: 5px 5px 5px 5px;" type = 'button' onclick = 'ajaxFunction()'/>
<script type="text/javascript"> <!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('chbox');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var message = document.getElementById('message').value;
var queryString = message ;
ajaxRequest.open("POST", 'chatdata.php', true);
//ajaxRequest.send(null);
ajaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajaxRequest.send('queryString');
}
</script>
<?php
$message1 = $_REQUEST['message'];
echo $message;
?>
when i use print_r($message); to see the content of the POST value
this is what i get Array ( [queryString] => ). It has no values.
What could be wrong with my code?
(I would have used jQuery but i'm not well grounded in it yet.)
I fixed some bugs and code start works:
1.
<p id="chbox"></p> <!-- ajaxDisplay need this -->
2.
ajaxRequest.send("message="+queryString); //queryString is variable so without quotes
3.
var_dump($message1); //there was message without 1
Here's how you would do it in jQuery - much simpler:
$('#mybutt').click(function(){
var txt = $('#message').val();
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: 'ta=' + txt,
success: function(d){
if (d.length) alert(d);
}
});
}); //END mybutt.click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="message" name="message" style="width:100%;"></textarea>
<input id="mybutt" value="SEND" style="border-radius: 5px 5px 5px 5px;" type='button' />
my_ajax_processor_file.php
<?php
$txt = $_POST['ta'];
$out = 'You sent: ' .$txt;
echo $out;
Here are a bunch of free 5-min video tuts for jQuery
The trouble is with query string. You should put ajaxRequest.send(queryString) instead of ajaxRequest.send('queryString');. Don't use query string just use the name of the variable. It should work!
The ajax jquery I am using in my form takes almost 4 seconds to complete and create the fields I want in my form. Because of that, some users submit the form before those fields are created. I want the form not submitted until those fields are created.
Here is my code.
echo"<form action='http://teachers.teicm.gr/dvarsam/index.php/exelixi_aitisis/' method='post' onsubmit='return recaptcha();'>
<label class='formLabel'>Όνομα*</label><br />
<input name='FirstName' required='' type='text'/><br />
...
...
echo"<select name='ThesisID' id='link_block' onchange='showCourses(this.value)'>
<option disabled='disabled' selected='selected' value=''></option>";
while ($row = mysqli_fetch_array($result))
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";
//displays the courses when thesis is selected
echo"<p id='courses'></p> ";
//placeholder which you’ll need to add to your form markup wherever you want the reCAPTCHA to appear
echo"<div class='g-recaptcha' data-sitekey='6LcIzA4TAAAAABo7Ean4z9EbNJddkkh04x9v6pLs'></div>
<input type='submit' name='action' value='Αποστολή' />
</form>";
On submit function. It checks if receptcha "I am not a robot" is clicked
function recaptcha ()
{
if(grecaptcha.getResponse() == ""){
alert('Παρακαλώ επιβεβαιώστε ότι δεν είστε ρομπότ κάνοντας κλικ στο κουτάκι.');
return false;
}
else
{
return true;
}
}
OnChange javascript. It shows textboxes on < p id='courses'>
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and will update div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // the div section where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://teachers.teicm.gr/dvarsam/index.php/get_courses" + queryString, true);
ajaxRequest.send(null);
}
I think that I need to add something in my on submit function that will return true only when the ajax jquery is completed. Am I thinking correctly? Can someone help me with that?
First, give an ID to your submit button and disable it by default:
<input type='submit' ID="SUBMITBUTTON" name='action' value='Αποστολή' disabled />
Then you can do something like this in your On Success return from Ajax to enable the submit button:
$('#SUBMITBUTTON').removeAttr('disabled');
OR
$('#SUBMITBUTTON').prop('disabled', false);
Hey guys I'm trying to work with AJAX for my first time using Javascript, PHP, and HTML. I have created the following code, and saved it in the htdocs folder in xampp. xampp is up and running but every time I navigate to localhost/foodstore.html nothing works I just get the error "Object not found!" I've Checked my code over a few times with a tutorial Im following, and found and corrected quite a few errors. I was wondering if the Object not found is because of my code or something else I am doing wrong. This is also my first time really using PHP and xampp. Also is there any other method that you would recommend to learn AJAX?
HTML
<html>
<head>
<script type= "text/javascript" src="foodStore.js"></script>
</head>
<body onload="process()">
<h3>Quaff Bucket</h3>
Enter the food you are looking for:
<input type="text" id="userInput"/>
<div id="underInput"/>
</body>
</html>
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('bacon','beans','chicken');
if(in_array($food,$foodArray)){
echo 'we do have'.$food.'!';
}
elseif($food==''){
echo 'Please Enter a food you idiot!';
}
else{
echo 'we do not have'.$food.'punk!';
}
echo'</response>';
?>
JS
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 the object");
}
else{
return xmlHttp;
}
}
function process(){
//states 4 and 0 mean that the object is free for communication
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//get the info from the web page
food = encodeURICompnent(document.getElementById("userInput").value);
// (Request type,where it is sending,should it be handled asynchronously)
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange =handleServerResponse;
xmlHttp.send(null);
}
else{
//wait 1 second before trying again
setTimeout('process()',1000);
}
}
function handleServerResponse(){
//4= done communicating
if(xmlHttp.readyState==4){
//200= Object is ok
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
//response is the only child in the xml page data= the response that would be genterated from the PHP
message = xmlDocumentElement.firstChild.data;
//makes underInput= to message
document.getElementById("underInput").innerHTML='<span style ="color:blue">'+message +'</span>';
setTimeout('process()',1000);
}else{
alert('something went wrong');
}
}
}
I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>
What now is:
A page on localhost, which sends a request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://www.3dfind.ru/site/js.js');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
</head>
<body>
<form method="get">
<div id='searchform'>
<table>
<td>
<input name='q' id='searchinput' type='text' value=''>
</td>
<td>
<select name='type' id='searchselect'>
<option value='1'>Val 1</option>
</select>
</td>
<td>
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
</td>
</table>
</form>
<div id='ResponseDiv'>
</div>
</body>
</html>
Then there js script on the server, which receives the request:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
var params = 'q=' + encodeURIComponent(q) + '&type=' + encodeURIComponent(type) + '&search=' + encodeURIComponent(s)
xmlHttp.open("GET", '/result.php?'+params, true)
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
If the file result.php search on the server, you get a url:
http://3dfind.ru/site/result.php?q=%E4%F4%E4%E4%F4%E4&type=1&search=%CF%EE%E8%F1%EA%21
Also in result.php I accept the GET- request :
$var = #$_GET['q'] ;
$s = $_GET['s'] ;
$typefile = $_GET['type'];
What am I doing wrong ?
Alright my man, I think you're a bit confused. Your HTML contains
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
And your Javascript contains
function MakeRequest()
but you say "Then there js script on the server, which receives the request:"
The Javascript should be on the client and sends the request.
Then I'm not even sure what you're trying to do and what's going wrong. Are you getting errors? Is it supposed to do something that it isn't?
Back to basics: use Firefox and install Firebug. Enable the "console". Open your page and do what you're trying to do. If you have Javascript errors, they'll show in the console. You can open every ajax request in the console as well so you can see if you're getting a server side error.
Yeah, I'm a bit confused what you're asking, here is a reference you may look into for cross-site xmlhttprequests here. There is another good reference to cross-site requests here also
From your other question ("cross-site request") I think I understand what you're trying to do. I think you're trying to get the results from "results.php" which is hosted in a different server.
What you need to do is change your MakeRequest() function. Instead of
xmlHttp.open("GET", '/result.php?'+params, true)
it should be
xmlHttp.open("GET", 'http://URL_OF_OTHER_SERVER/result.php?'+params, true);
Hope this helps.