AJAX module not submitting the form - php

I am having a problem with this JavaScript, it's reloading the page and not submitting the form!
JavaScript:
var xmlHttp
function GetXmlHttpObject(){
var objXMLHttp=null;
if (window.XMLHttpRequest) {
objXMLHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp
}
function ajax_module(){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request");
return
}
xmlHttp.open('POST', 'save.php');
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xmlHttp.send('user='+document.form1.user1.value+'&text='+document.form1.text1.value);
document.form1.test1.value = '';
document.form1.test1.focus();
}
HTML:
<form name="form1" method="POST" onsubmit="ajax_module(); return false;">
<textarea name='text1'></textarea>
<input type='hidden' name='user1' value='$user' />
<input type="submit" name="submit" value="submit" />
</form>

Double-check that no errors are occurring within ajax_module. If there are any, it will never get to return false and won't stop the onsubmit.
If you have Firebug or a similar debugger available, set breakpoints within ajax_module. Otherwise, add a try/catch right inside ajax_module:
function ajax_module() {
try {
/* place what you already have here */
} catch (e) {
alert(e);
}
}
You also commented that text inputs usually work. This may be due to newlines being allowed in textareas, which you aren't currently encoding.
Whether that's the cause or not, it's probably a good idea to encode the values anyways.
xmlHttp.send('user=' + encodeURIComponent(document.form1.user1.value) +
'&text=' + encodeURIComponent(document.form1.text1.value));
For more info, check out http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp.
An alternative would be escape -- though, note the character differences described on each page.

Perhaps it's the missing self-closing tag on the user input? Is there a JavaScript error?

Related

Sending POST with javascript

What is wrong with this code? Trying to send data over POST w/ javascript to a PHP page but it isn't sending anything, nothing comes across in the headers $_POST contains nothing.
HTML:
<form method="POST" id="userSub" class="userSub">
<table>
<tr><td colspan="2">Sign In Here </td></tr>
<tr><td>Username:</td><td><input name="username" type="text" id="username" /></td></tr>
<tr><td>Password:</td><td><input name="pwd" type="text" id="pwd" /></td></tr>
<tr><td><input name="submit" type="submit" value="submit" id="submit" onclick="loginSub()" /></td></tr>
<tr><td colspan="2">Need a Username? Sign Up</td></tr>
</table>
</form>
Javascript:
function loginSub(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("rssnav2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","PHP/login.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
PHP doesn't do anything special right now, just seeing if I can pass the post information to it:
<?php
echo "test";
$username=$_POST['username'];
echo $username;
?>
It is IS echoing that 'test' line to the correct so it is communicating w/ the PHP page. Also, I know that I still have the pwd input in "text" type and I know its probably a good idea to hash a password before sending it to the server.
Thanks for your help, everyone!
The xmlhttp doesn't actually have any knowledge of the <form>, so it won't send any data automatically.
You'll instead have to gather the <form>'s data yourself, format it as URL-encoded, and .send() it along with the request.
function loginSub(){
var user = document.getElementById('username');
var pass = document.getElementById('pwd');
var postData = [
encodeURIComponent(user.name) + '=' + encodeURIComponent(user.value),
encodeURIComponent(pass.name) + '=' + encodeURIComponent(pass.value)
].join('&');
// ...
xmlhttp.send(postData);
}
For more details, you may want to read through MDN's Using XMLHttpRequest, especially the sections on Using nothing but pure AJAX.
It includes a generalized solution for gathering <form> data in A little vanilla framework, which you could use with:
<form method="POST" action="PHP/login.php" onsubmit="AJAXSubmit(this); return false;">
Side note:
Your <form> is likely still submitting as well and may interrupt the Ajax request. You can prevent this by cancelling its onsubmit event:
<form method="POST" id="userSub" class="userSub" onsubmit="return false">
Also, there are more ways to submit a <form> than clicking the type="submit". For example, most browsers allow submitting by simply tapping Enter while typing in a type="text" or type="password". And, doing so won't typically imitate a click of the type="submit".
So, you'll want to at least consider moving the call out of the onclick and into the onsubmit:
<form method="POST" id="userSub" class="userSub" onsubmit="loginSub(); return false;">
You are not sending parameters in your XMLHttpRequest. Something like:
var params = "username=user&password=something";
xmlhttp.open("POST", "PHP/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("rssnav2").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(params);
Try changing
xmlhttp.send();
to
xmlhttp.send('username='+document.getElementById('username').value);
Of course you will need to put in validation logic.
function loginSub()
{
var xmlhttp = false;
if(window.XMLHttpRequest)
{
if(typeof XMLHttpRequest != 'undefined')
{
try
{
return xmlhttp= new XMLHttpRequest();
}
catch(e)
{
return xmlhttp= false;
}
}
else if( window.ActiveXObject)
{
try
{
return xmlhttp= new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e)
{
try
{
return xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
return xmlhttp = false;
}
}
}
}
var xmlhttp=false;
xmlhttp=createobject();
if(xmlhttp)
{
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('rssnav2').innerHTML = xmlhttp.responseText;
}
}
parameter=username+'='+document.getElementById('usernname').value;
xmlhttp.open('POST','PHP/login.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameter);
}
}
this will solve your problem

Really basic AJAX

I'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
Here is the html:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);
It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);
First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>

Submit Values via POST to multiple PHP files

I have a form :
<form action="moods.php" method="post" id="geog">
Longitude: <input size="15" id="lonbox" name="lon" type="text" />
Latitude: <input size="15" id="latbox" name="lat" type="text" />
<input type="submit" />
</form>
I wish to submit the values of latitude and longitude to multiple .php files apart from moods.php at the same time using the single above form.
How can I do that?? please suggest some ways ..
why have the form submit to multiple pages, when you can have one single script include() the other scripts?
require('script1.php');
require('script2.php');
require('script3.php');
You could submit it to a file containing a cURL script that would handle multiple submissions
<form action="multi_submit.php" method="post" id="geog">
on multi_submit.php handle the form submission using cURL
If you really need to submit the values over multiple .php files, and the require option gave by dqhendricks does not solve it, why not to use several Ajax calls? One for each file.
You could have something like this:
<form onsubmit='sendSeveralPost()'>
... form fields
</form>
And the javascript function
function sendSeveralPost() {
var f1 = document.getElementById('field1');
var f2 = document.getElementById('field2');
var x = getXmlHttp();
var params = 'field1='+f1+'&field2='+f2;
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.setRequestHeader("Content-length", params.length);
x.setRequestHeader("Connection", "close");
var files = new Array();
files[0] = 'script1.php';
files[1] = 'script2.php';
files[2] = 'script3.php';
for (i=0;i<files.lenght;i++) {
var url = files[i];
x.open("POST", url, true);
x.onreadystatechange = function() {//Call a function when the state changes.
if(x.readyState == 4 && x.status == 200) {
alert(x.responseText);
}
}
x.send(params);
}
}
function getXmlHttp() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
try { // Internet Explorer 6.0+
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e){
try { // Internet Explorer 5.5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
Further explanations about the commands can be found at the article http://www.openjs.com/articles/ajax_xmlhttp_using_post.php, from where I took the inspiration for this example.
Hope this helps.
Namastê!

Ajax responds with empty string when triggered via form onsubmit in Firefox, but working fine in Internet Explorer

Ajax responds with an empty string when triggered via form onsubmit in Firefox, but it is working fine in Internet Explorer and Opera (works in Firefox if sent by a submit button instead of form onsubmit).
I am simply calling a php file with the ajax GET and the php file response with - echo $response = "something";. Then the response value is alerted. I am getting it work in IE but in Firefox the response is an empty string (checked by typeof()).
code is 4 files: index.php, ajax-connect.js, cbb.js, cbb.php
index.php
<html> <head> <script src="ajax-connect.js"></script> <script src="cbb.js"></script>
</head> <body>
<form name="condtactform1" method="get" action="" onSubmit="contactfunction()">
<input type="submit" name="hissubmit" id="hissubmit" value="submit"> </form>
</body> </html>
ajax-connect.php
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*#cc_on #*/
/*#
if (#_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
#end
#*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
cbb.js
function contactfunction() {
var url = "cbb.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var responsae = xmlHttp.responseText;
alert(responsae);
}
}
cbb.php
<?php $response = "something"; echo $response; ?>
If i trigger ajax by submit button instead of the form submit then it works fine in firefox like:
<form name="condtactform1" method="get" action="">
<input type="submit" name="hissubmit" id="hissubmit" value="submit" onFocus="contactfunction()"> </form>
Any idea why it is doing this?
Thanks.
I think part of the problem is that you aren't stopping the normal action of the submit. That it is working at all is probably based on how the return values of the last function executed is handled, though its hard to tell. Try adding a "return false" to your contactFunction();
If that doesn't work, I'd invest some time in retrofitting it to use a javascript framework for the AJAX (jQuery, MooTools, Prototype, etc.) rather than going down the route of debugging the cross browser differences. A jQuery solution would look like:
<form name="condtactform1" method="get" action="cbb-full.php">
<input type="submit" name="hissubmit" id="hissubmit" value="submit">
</form>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('#hissubmit').click( function() {
$.get( 'cbb.php', function(response) {
alert(response);
});
return false;
});
});
</script>
Note that the form ought to post to a url that will generate a full response if javascript isn't enabled.

Simple AJAX code not being recognized

I'm trying to begin learning AJAX, and I've already hit a little stump. So I'm starting simple and just trying to get an alert to pop up showing the length of the string the user types into a text field.
The HTML:
<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" onClick="check(this.form.email.value);"/>
</form>
The JS:
function check(email) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
email=encodeURIComponent(email);
req.open("POST","/scripts/addemail.php");
req.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
req.send(email);
req.onreadystatechange=function() {
if(req.readyState==4) {
result = req.responseText;
alert("The length of the email is:" + result);
}
}
return false;
}
The PHP (addemail.php):
<?php
function check_email($input) {
return strlen($input);
}
$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>
And yes, I've included the JS in the section. I got this almost directly from a tutorial so I'm not sure what's going on. My testing browser is Safari, but I've also tried FF. Sorry is this is obvious, as this is my very first AJAX attempt. Thanks!
EDIT: Sorry, the problem is that its just going to the file described in action="addemail_fb" instead of the JS.
-iMaster
Change the onclick handler to onsubmit (on the form), like so:
<form onsubmit="return check(this.email.value);"> ... </form>
Also, set your req.onreadystatechange before calling req.send ()
inline javascript is bad practice. this solution may seem a bit more convoluted but if you implement it into the rest of your scripts then you will find this much more elegant.
JS libraries use similar methods, but if you cant use one then do this instead:
onDomReady(function(){
var oForm = document.getElementById("myform");
addListener(oForm,"submit",function(){
removeListener(oForm,"submit",arguments.callee);
// do stuff here
});
});
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.addEventListener) { // Standard
element.addEventListener(type, expression, bubbling);
return true;
} else if(window.attachEvent) { // IE
element.attachEvent('on' + type, expression);
return true;
} else return false;
}
// Cross-browser implementation of element.removeEventListener()
function removeListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.removeEventListener) { // Standard
element.removeEventListener(type, expression, bubbling);
return true;
} else if(window.detachEvent) { // IE
element.detachEvent('on' + type, expression);
return true;
} else return false;
}
function onDomReady(fn) {
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
fn();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
fn();
} else {
setTimeout( arguments.callee, 0 );
return;
}
});
} else {
// A fallback to window.onload, that will always work
addListener(window,"load",fn);
}
}
Here is the problem:
You are doing it wrong.
And jQuery is the Answer.
But seriously. Try using jQuery, as it will make you Javascript life easier than cutting into a piece of pumpkin pie.
AJAX is one of the most annoying subjects in Javascript, and jQuery, along with other libraries have gone and made the problem much easier to deal with. Plus, there are many many other great features of jQuery that just make it so much more wonderful to work with Javascript.
In jQuery, the entire code would look like:
$.post("/scripts/addemail.php", {email_address:email}, function(data){
alert("The length of the email is:"+data);
});
Speaking of pumpkin pie.....
Now that I've finished my public server announcement for jQuery, you will want to check the Javascript console (Ctrl + Shift + J in Firefox), and run the page. It will give you any errors that you are bound to have such as syntax errors or various other things that go wrong.
If you can go there and then give us any error messages that pop-up, we will be more likely to be able to solve your problem.

Categories