AJAX vs PHP submit of form - php

I originally had a form set up as such (CSS styles have been removed)
<form name="LoginForm" action="login.php" method="post">
<input name="email" id="email" type="text"></input>
<input name="password" id="password" type="password"></input>
<input name="login" id="login" type="submit" value="Login"></input>
</form>
and it worked fine, and login.php would validate the user creditionals. However, that approach required a page redirect. I am trying to migrate the code to AJAX so I can query the login details and stay within the page. [edit] here is the AJAX object I use
function Ajax(){
this.xmlhttp=null; //code below will assign correct request object
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
this.xmlhttp=new XMLHttpRequest();
}
else{ // code for IE6, IE5
this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
this.stateChangeFunction=function(){}; //user must reimplement this
var that=this;
this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct
if (this.readyState==4 && this.status==200){
that.stateChangeFunction();
}
else{
dump("Error");
}
}
}
then I have a login.js function, which I am not too sure how to incorporate, currently I add it to the onclick event of the submit button:
function login(email,password){
var ajax=new Ajax();
//ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true);
//ajax.xmlhttp.send();
}
You will notice how those last two lines are commented out, I am not too sure how to send arguments at the moment, but the point is that even with the two commented out, the entire site still reloads. What is the correct way to use AJAX in forms.
Thanks

I havent done enough ajax in raw js to give a tutorial here so Im' going to use jquery. However anything i show can be done in raw javascript so maybe someone else will be kind enough to show you a raw implementation.
First of all you should use POST instead of GET for your login. Secondly as i said in my comment you should use the actual URL to the login page as the action. This way users who dont have JS for whatever reason can still login. Its best to do this by binding to the forms onSubmit event.
<form name="LoginForm" action="login.php" method="post">
<input name="email" id="email" type="text"></input>
<input name="password" id="password" type="password"></input>
<input name="login" id="login" type="submit" value="Login"></input>
</form>
And with jquery:
function doLogin(event){
event.preventDefault(); // stop the form from doing its normal post
var form = $('form[name=LoginForm]');
// post via ajax instead
$.ajax({
url: form.attr('action'), // grab the value of the action attribute "login.php"
data: form.serialize(), // converts input fields to a query string
type: 'post',
dataType: 'text',
success: function(data){
/* callback when status is 200
* you can redirect here ... data is the response from the server,
* send the redirect URL in this response
*/
window.location.href = data;
},
error: function(textStatus){
alert('ERROR');
}
});
}
// bind our function to the onSubmit event of the form
$('form[name=LoginForm]').submit(doLogin);
Then on the serverside you can check if its an ajax based request:
<?php
// do your login stuff
// set $successUrl to the URL you want to redirect to
// check if its ajax
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo $successUrl;
exit(0);
}
else
{
// was a non-ajax request - do a normal redirect
header('Location: '.$successUrl);
}

Your code only shows HTML. AJAX uses javascript to communicate to PHP script.
So, Only on seeing the js code, Debugging is possible.

To avoid the default event you have to use action='javascript: void(null);' instead of removing it.

Related

AJAX not receiving POST variables

I've read at least 20 of these similar questions and can't figure out what's wrong with my code.
I've got a login form as shown below:
<div class="login-form">
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="submit" value="Log in"/>
</div>
</form>
</div>
My login.js script is as below:
$(document).ready(function(){
$("#login-button").click(function(e){
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php", //.js file is in a diff directory
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
This is supposed to get sent back to 'index.php', which has included a separate php file that handles the login information. The reason for this is so I can update the page with the user's successful login without refreshing.
My other php file is simply checking for the post data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
if (isset($_POST['login']) && $_POST['login']) {
} else if (isset($_POST['reg']) && $_POST['reg']) { //this is for registration, which will be used once this login is working
} else {
echo 'Neither login/reg were set';
}
The var dump shows:
array(0) { }
So the data is not being received. However, it clearly reaches the php page. I don't know what's wrong, any suggestions?
Edit: I figured I would add, that adding an alert at the top of login.js with the username/password does print the entered values. So the login.js is being reached, and the data is accessible there. But it doesn't go beyond that.
Edit2: Here is my updated HTML and login.js code:
index.php:
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="button" value="Log in"/>
</div>
</form>
login.js
$(document).ready(function(){
alert(1);
$("#login-button").click(function(e){
alert(0);
//e.preventDefault();
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php",
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
The solution was to change my
$("#login-button").click(function(e){
to
$(document).on("submit",".login-form-container",function(e) {
which will handle the form submit, and this includes pressing the button as well as hitting enter (ideal situation).
Now the data is being sent successfully and I can handle the actual login/registration SQL, so thank you to #Ashokkumar M. Prajapati for helping to come to the conclusion that the .js script was not actually firing upon submit (not that the rest of you didn't help!)
please replace type: "POST" with method: "POST"
you mentioned it wrong in jquery ajax function.
Default is "GET" in case you don't specify it. So, if you had checked both $_POST & $_GET then you would have found your data in $_GET.
try var_dump($_REQUEST) if it don't show up anything then your client is not sending data to server.
also, check net panel of you browser developer console. so, you will know what data are passed to server.

ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="Zmień" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.

ajax post but can't prevent refresh

I have a problem with my page refreshing after ajax posts, I've tried like 6 differing variations and at one point I was getting the proper result but couldn't stop the page from refreshing and after searching the net and around on this site now none of it is working and it's still refreshing...
current code is:
$('#submit_btn').click(function() {
/*event.preventDefault();*/
var curPassword = $("input#curPassword").val();
var newPassword = $("input#newPassword").val();
var new2Password = $("input#new2Password").val();
/*var params = 'curPassword='+ curPassword + '&newPassword=' + newPassword + '&new2Password=' + new2Password; */
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
$.ajax({
type: "POST",
url: "testAjax.php",
data: params,
success: function(msg){
alert(msg);
}
});
return false;
});
the form is:
<form method="post" action="" name="confirmChange" class="confirmChange">
<label for="curPassword">Current Password:</label>
<input type="password" name="curPassword" id="curPassword" value="" />
<label for="newPassword">New Password:</label>
<input type="password" name="newPassword" id="newPassword" value="" />
<label for="new2Password">Confirm New Password:</label>
<input type="password" name="new2Password" id="new2Password" value="" />
<br />
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change" />
Appreciate any help in getting this to work =/
Update:
Took out the other non-directly-related code as it kinda cluttered the question. Also updated code to refelect latest revision.
I changed the ajax url to a simple textAjax.php with a simple echo hello world nothing else, where I'm still getting nothing.
Update 2
Tried changing javascript code to:
$('#submit_btn').click(function() {
alert('Button Clicked');
});
And I'm getting nothing... If that is the form below how is it possible the click function isn't working at all?
You don't need to use the type="submit" for your input. Just use type="button" and call the ajax function on the button's click event.
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change">
$('#submit_btn').click(function() {
(ajax code here)
});
preventDefault() would also work, but, in my opinion, why prevent an event from naturally occurring when you can just avoid using the submit button altogether?
Update: I just realised that using the submit would allow users to hit enter to trigger your actions, so perhaps there's also some merit in that. In any case, here's a similar question that contains elaborations into preventDefault().
Update 2: You need to fix your parameters in the ajax function. Use an array instead of trying to build a query string:
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
Encapsulate your AJAX call within the following code block
$('form.confirmChange').submit(function(event) {
event.preventDefault();
#Rest of your code goes in here
});
preventDefault() will prevent the default action of an event from triggering.
Try this
<script>
function refreshpage(){
(ajax code here)
return false;
}
</script>
<form onsubmit="return refreshpage();">
<input type = "submit" value="submit_btn">
</form>
I think I fixed it by using:
$('#submit_btn').live('click', (function() {
I at least started getting a response when clicking, but I'm not updating or getting any echo's back from the php file but hopefully that'll be easier to debug. :)
I had the same problem. Just like you, I had wrapped my <input> tags inside a <form> tag pair. Even though there was no <submit>, I found that when I clicked my button to trigger the Ajax call, it was refreshing the page - and actually submitting the form to the page.
I ended up removing the <form> tags and this behaviour stopped, but the Ajax still works as expected. I hope this helps anyone else that is experiencing this.
Use a loop to run the ajax call only once.
var i;
for(i=0;i<1;i++){
//ajax code here
}
So, then it will not call again and again..

Ajax jquery php post beginner

I am have a hard time learning how to use ajax and jquery to post a button without reloading the page. Specificly: The form is still reloading the page and no variables are being updated.
Here is the code I am stumbling through.
What I used before I tried Jquery/AJAX. Just php
// $_POST['selected_dir'] is set when you click on a folder or link within the explore(r).php
if (isset($_POST['selected_dir']))
{
// last selected folder/directory
$current_dir = $_POST['selected_dir'];
// current_dir is the folder we are looking inside of.
// we make it a $session so that if we click a different submit (RELOAD)
// within the page it will remember $current_dir;
$_SESSION['selected_dir'] = $current_dir; //
}
else // if $_post isint set but $_session is
if (isset($_SESSION['selected_dir']))
{
$current_dir = $_SESSION['selected_dir'];
}
else
{
// default folder/directory
$current_dir = "$root"; //'D:\Hosting\538\html';
}
<form action='explore.php' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
value='submit'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
class='submit_into_link'/>
</form>
so that worked great except everytime you click the image or the link the page reloads.
I finally came to the conclusion i need to use jquery and ajax and I never even used javascript up till now. Ive been reading through tutorials and i cant really connect the dots to make this work
I have this in my header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
I have this at the top of my page within the body
$.ajax
({
type: 'POST',
url: 'explore_be.php',
data: data, success:
success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
I have a few questions about the code above. I'm not sure how to use it.
Do I need to put this ajax code inside an onclick function? seems like some examples ive looked through in jquery use something like this..
$(document).ready(function()
{
$(".flip").click(function() // this is a piece of code i got from w3schools.com
});
.flip above is a class. I have seen them use button when talking about
<button>
but what about a button within a form with a specific input id? Or should i just add to the form input
onclick="clicked()" then put the ajax in that function? Does the ajax need be in the $(document).ready(function()) as well?
What should i put for datatype?
I put my php code in the explore_be.php file.
explore_be.php
// $_POST['selected_dir'] is set when you click on a folder or link within the explore(r).php
if (isset($_POST['selected_dir']))
{
// last selected folder/directory
$current_dir = $_POST['selected_dir'];
// current_dir is the folder we are looking inside of.
// we make it a $session so that if we click a different submit (RELOAD)
// within the page it will remember $current_dir;
$_SESSION['selected_dir'] = $current_dir; //
}
else // if $_post isint set but $_session is
if (isset($_SESSION['selected_dir']))
{
$current_dir = $_SESSION['selected_dir'];
}
else
{
// default folder/directory
$current_dir = "$root"; //'D:\Hosting\538\html';
}
Is that all there is to the code behind page?
I changed my forms to have no action but added an onclick They are still reloading the page. What do I need to do to the form inputs to stop that?
My new form looks like this
<form action='' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
onclick='clickity()'
value='submit'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
onclick='clickity()'
class='submit_into_link'/>
</form>
Any help is greatly appreciated.
you can do it like this:
html
<form action='explore.php' method='post' id='myForm'>
jquery
$('#myForm').submit(function(event){ //added event
event.preventDefault(); //added to prevent submit
$.ajax
({
type: 'POST',
url: 'explore_be.php',
data: data, success:
success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
});
});
edit: remove the onclick events you added in your edit
<form action='javascript:;' method='post'>
<input type='image'
src='$folder_icon'
alt='Submit'
name=''
onclick='clickity();'/>
<input type='hidden'
value='$f_path/$value'
name='selected_dir'/>
<input type='submit'
value='$value'
name='$value'
onclick='clickity();'
class='submit_into_link'/>
</form>
Firstly change this and tell me if it's ok and also tell me why you need 2 submits on the same form?
You are trying three things at a time. which will make things complex to find where the error lies. Just use ajax without jquery with a small example. Then extend it.
<html>
<head>
<script type="text/javascript">
function getdata(str)
{
if (str.length==0)
{
document.getElementById("result").innerHTML="";
return;
}
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("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<input type='submit' onclick='getdata(input)'>
<div id='result'>
</div>
<body>

How do I use a submit button to activate an AJAX function?

I have the following form and javascript function on my web page. This is a dummy function that I am using to test whether what I would like to do is possible.
What I am attempting to do is have a form send an AJAX request to the server, so that the server can update the database while the page itself continues along it's predetermined path. I am in a tight time crunch, so I unfortunately do not have time to rewrite the entire page to better support this. The problem that I have is the xmlhttp object does not seem to return properly. I get a readyState of 4 but a status of 0. can someone please explain what I need to do?
Here's my code:
ajax.php
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post">
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
response.php
<?php
echo "Hello there";
?>
EDIT
Please note that I do not want to prevent the default behavior. In fact, the forn must be submitted as usual. I simply want to add an AJAX request to the process.
You can't trigger an AJAX request and allow the form to submit at the same time. Incomplete AJAX requests are cancelled when the page reloads (as is the case when the form is submitted). You'll either have to not submit the form at all, or wait until your AJAX call has completed before submitting the form. If you wanted to go the second route, you could make the following changes to your code:
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
**document.getElementById("ajaxform").submit();**
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post" **id="ajaxform"**>
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();**return false;**" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
Changes/additions are marked with **.
Note that there are a few practices in there I don't like, in particular using the onsubmit, etc attributes of HTML tags to attach Javascript event handlers.
I know this doesn't directly answer your question but if you are strapped for time then I would suggest just using jQuery to handle the AJax.
You can attach it to a button press and then call some code: http://api.jquery.com/jQuery.ajax/
I can dig out some code examples if you need them.
Once the submit button is pressed the browser will submit data to the server and a new page will be loaded. You can bind the submit event of the form and in the event make the ajax call but you will have 2 problems.
The browser may redirect before all ajax data is sent
You have no idea if the ajax call was successful or not
I would try sending the data you are sending via ajax in the same form data using hidden inputs. If both calls are aimed at different urls then try this:
var ajaxSent = false;
$('#myForm').submit(function(e){
if (!ajaxSent){
e.preventDefault();
$.ajax({
url: "ajaxUrl",
// data, method, etc
success: function(){
ajaxSent = true;
$('#myForm').trigger('submit');
}
}
// else submit the form
});

Categories