Im making some web appication which loads pages without refresching te page. This all works great but now i have a form on one of these pages. I want to submit the form without the page to refresh. But when i submit the form after i loaded it with ajax the url in the browser will change from
localhost/documents/projects/test/
to
localhost.documents/projects/test/?form_type=register&Username=&first_name=&surname_prefix=&surname=&surname=&email=
When i just put the form html in my index.php and submit it there it works fine.
I hope someone can tell me what im doing wrong and how to fix it.
part of index.php
<div class="message"></div>
<div id="content">
<div id="page">
<div class="form_container">
<form id="form">
<input type="hidden" name="form_type" value="register" />
<input class="type_text" type="text" name="username" maxlength="20" placeholder="username" />
<input class="type_text" type="text" name="first_name" maxlength="50" placeholder="First Name" />
<input class="type_text" type="text" name="surname_prefix" maxlength="20" placeholder="Surname Prefix" />
<input class="type_text" type="text" name="surname" maxlength="50" placeholder="Surname" />
<label class="label" for="birth_date">dd-mm-jjjj</label>
<input id="birth_date" class="type_text" type="text" name="birth_date" maxlength="10" placeholder="Birth Date" />
<input class="type_text" type="text" name="email" placeholder="Email Address" />
<input class="type_submit" type="submit" value="Register" />
</form>
</div>
</div>
pageHandler.js
$(document).ready(function() {
var request;
//page handler
//pageRequest('home');
$('.click').click(function(event) {
var temp = $(this).attr('id');
var pages = ['home','register'];
if($.inArray(temp, pages) !== -1) {
pageRequest(temp);
//$('.message').html(temp);
}
event.preventDefault();
});
function pageRequest(temp) {
var page = $('#page');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
type: "POST",
url: "core/posts.php",
data: 'temp=' + temp
});
request.done(function(data) {
page.fadeOut(function() {
page.html('');
page.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
page.fadeOut(function() {
page.html('');
page.html(textStatus).fadeIn();
});
});
}
//form handler
$('#page').delegate( "#form", "submit", function(event) {
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
formRequest(serializedData);
event.preventDefault();
});
function formRequest(values) {
var message = $('.message');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
url: "core/posts.php",
type: "POST",
data: values
});
request.done(function(data) {
message.fadeOut(function() {
message.html('');
message.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
message.fadeOut(function() {
message.html('');
message.html(textStatus).fadeIn();
});
});
}
});
posts.php
If(isset($_POST['temp'])) {
$temp = $_POST['temp'];
$url = '../content/templates/'.$temp.'.html';
if(file_exists($url)) {
$html = file_get_contents($url);
echo $html;
}
else {
echo 'Sorry, couldn\'t find the page.';
}
}
//form handler
if(isset($_POST['form_type'])) {
require_once('../admin/config/database.functions.php');
$function = new myDBFunctions();
switch($_POST['form_type']) {
case 'register' :
$username = $_POST['username'];
$firstname = $_POST['first_name'];
$surnamep = $_POST['surname_prefix'];
$surname = $_POST['surname'];
$birthdate = $_POST['birth_date'];
$email = $_POST['email'];
echo 'Thanks for your registration';
break;
case 'login' :
echo 'login';
break;
case 'password_recovery' :
echo 'password recovery';
break;
}
}
I have found the problem but not why it occured. I had a $_POST['username'] in my posts.php file while the the name of the html input field was Username. I have changed this and now the url in the browser doesn't change anymore. I'm happy I've found the problem but i still dont get why the data send by ajax would appair in the url.
"I want to submit the form without the page to refresh"
There are a few ways to do this, I think the easiest is to intercept and stop the form from actually submitting like a regular HTML form and instead make an ajax call with the data in the form fields.
To do this, you will need to intercept the submit event of the form, get the values of all the inputs in the form and make an ajax call with the data to the server:
<form id="myForm">
....
</form>
<script>
$('#form').on("submit", function(event) {
// stop the form from submitting
event.preventDefault();
// get data in the inputs of the form
var data = {};
var $inputs = $('#form').children("input, select, textarea");
inputs.each(function($element){
data[$element.attr('name')] = $element.val();
});
// submit data to the backend
request = $.ajax({
type: "POST",
url: "",
data: data
});
});
</scipt>
Related
I don't know how can i apply this to my login page, once captcha success response on ajax then submit form.
Here's my html form(i leave action null because i'm still in testing)
<form action = "" method = "post">
<input type = "text" id = "email" name = "email">
<input type = "password" id = "pass" name = "password">
<div class = "form-group col-lg-6">
<div class="g-recaptcha" data-sitekey="MY_KEY"></div>
</div>
<input type = "button" id = "submit" value = "submit">
</form>
Here's how i understand ajax on captcha sending captcha word.. if captcha success submit form if failed i will give an alert.
$('#submit').click(function() {
var captcha = "captcha";
$.ajax({
url: "captcha.php",
method: "post",
data:{captcha:captcha},
success:function(data){
if(data=='success'){
$('form').submit();
}
}
else{
alert('captcha failed. try again');
}
});
});
my captcha.php how i receive $_POST['captcha']
<?php
if($_POST['captcha']){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = 'MY_SECRET_KEY';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if($data->sucess==true){
echo "success";
}
else{
echo "failed";
}
}
?>
please help me to understand how will it work and how can it be done using AJAX
THANK YOU IN ADVANCE :)
UPDATE
i just notice how can i $_POST['g-recaptcha-response']; ??
You can use this code:
HTML Code:
<form action="" method="POST" id="loginForm">
<input type="text" id = "email" name="email">
<input type="password" id="pass" name="password">
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="10LDDpf0ehtMZY6kdJnGhsYYY-6ksd-W"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
JavaScript
$(document).ready(function() {
var loginForm = $("#loginForm");
//We set our own custom submit function
loginForm.on("submit", function(e) {
//Prevent the default behavior of a form
e.preventDefault();
//Get the values from the form
var email = $("#email").val();
var pass = $("#pass").val();
//Our AJAX POST
$.ajax({
type: "POST",
url: "login.php",
data: {
email: email,
password: pass,
//This will tell the form if user is captcha varified.
g-recaptcha-response: grecaptcha.getResponse()
},
success: function(response) {
console.log(response);
//console.log("Form successfully submited");
}
})
});
});
PHP Code:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '10LDDpf0ehtMZY6kdJnGhsYYY';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//captacha validated successfully.
$email = !empty($_POST['email'])?$_POST['email']:'';
$password = !empty($_POST['password'])?$_POST['password']:'';
echo "captacha validated successfully.";
else:
echo "Robot verification failed, please try again.";
endif;
else:
echo 'invalid captcha';
endif;
else:
//Nothing
endif;
?>
I am using re-captcha validation using jQuery / ajax as per below :
<script src="https://www.google.com/recaptcha/api.js" >;
<form method="post" name="contactForm">
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="Phone"/>
<div class="g-recaptcha" data-sitekey="[site_key]" data-callback="onReturnCallback" data-theme="dark"></div>
<input value="submit" type="submit"/>
</form>
Validation / ajax :
//Initialize jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var onReturnCallback = function(response) {
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response},
success: function(result) {
var res = result.success.toString();
alert(res);
if (res == 'true') {
document.getElementById('g-recaptcha').innerHTML = ' Your Success Message';
}
}
});
};
</script>
I'm trying to submit a form using jquery and ajax, but it fails. Here's the code:
$(document).ready(function ()
{
$('.crazytext').keydown(function (event)
{
if (event.keyCode == 13)
{
$.ajax(
{
url: '/sendchat.php',
type: 'POST',
data:
{
'from': $('#from').val(),
'to': $('#to').val(),
'when': $('#when').val(),
'msg': $('#chatty').val()
}
});
}
});
});
It's simple, I want to submit the form once enter is pressed and send data to sendchat.php without reloading the page. This is the html:
<form id="send-message-area" method="POST" action="sendchat.php">
<input type="text" name="from" id="from" value="<?php echo $me;?>" hidden>
<input type="text" name="to" id="to" value="<?php echo $other1;?>" hidden>
<input type="text" name="when" id="when" value="<?php echo $date;?>" hidden>
<textarea class="crazytext" name="msg" id="chatty"></textarea>
<input type="submit" name="chat" values="chat" class="crazytext2" hidden>
</form>
And if necessary, the php code for sendchat.php
$fromuser = $_POST['from'];
$touser = $_POST['to'];
$when = $_POST['when'];
$msg = $_POST['msg'];
$seen = 0;
$addchat = $db->prepare("INSERT INTO scorp_chats (Fromuser, Touser, Messagetime, Message, Seen) VALUES (:fromuser, :touser, :messagetime, :message, :seen)");
$addchat->execute(array(':fromuser' => $fromuser, ':touser' => $touser, ':messagetime' => $when, ':message' => $msg, ':seen' => $seen));
That's it really, it's super simple but it fails. If I remove the ajax part completely, it works, but I get redirected to the page, which shouldn't happen.
SOLUTION (Thanks to Barmar):
$(document).ready(function () {
$('.crazytext').keydown(function (event) { // your input(textarea) class
if (event.keyCode == 13) {
event.preventDefault();
$.ajax({
url: 'sendchat.php', // script to process data
type: 'POST',
data: $("#send-message-area").serialize(), // form ID
success: function(result) {
$("#result").text(result);
}
});
}
});
});
You need to prevent the default submission action:
$('.crazytext').keydown(function (event)
{
if (event.keyCode == 13)
{
event.preventDefault(); // <----
$.ajax(
{
url: '/sendchat.php',
type: 'POST',
data:
{
'from': $('#from').val(),
'to': $('#to').val(),
'when': $('#when').val(),
'msg': $('#chatty').val()
}
});
}
});
DEMO
I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery.
HTML
<form action="login.php" method="post" onSubmit="return login()" >
<input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
JQuery Ajax
function login()
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
$("#loginForm p").innerHTML = xmlhttp.responseText;
return false; //is this the correct way to do it?
}
});
return true; //not really sure about this
}
PHP MySQL
$q=$_POST["q"];
$s=$_POST["s"];
$con=mysqli_connect("localhost","root","","SocialNetwork");
$check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'";
$data=mysqli_query($con,$check);
$result=mysqli_fetch_array($data);
if ($s != $result)
{
echo "Password does not match";
}
jQuery object doesn't have a property innerHTML which is used on DOM element. Use method html() instead:
$("#loginForm p").html(response);
Or you could refer to DOM element like that:
$("#loginForm p")[0].innerHTML = response; // equivalent to .get(0)
Be aware as ajax is async by default, your login function here will always return true.
BTW, response here corresponds to the returned value from server, not the jqXHR object (xhr object wrapped inside a jquery object).
UPDATE
function login(form)
{
$email = $("#eMailTxt").val();
$pass = $("#passWordTxt").val();
$.ajax({
url:'loginCheck.php',
type:'POST',
data:{q:$email,s:$pass},
success:function(response){
if(response === "Password does not match") {
$("#loginForm p").html(response);
return false;
}
//if password match, submit form
form.submit();
}
});
//we always return false here to avoid form submiting before ajax request is done
return false;
}
In HTML:
<form action="login.php" method="post" onSubmit="return login(this)" >
HTML
<form action="login.php" method="post" class="js-my-form">
<input type="text" name="record[email]" id="eMailTxt" placeholder="Email Address" />
<input type="password" name="record[password]" id="passWordTxt" placeholder="password" />
<br />
<p><!--wanna show password does not match here--></p>
<input type="submit" value="Login" id="submitBtn" class="Btn" />
</form>
jQuery
$(document).ready(function () {
$('.js-my-form').submit(function () {
var data = $(this).serialize();
var action = $(this).attr('action');
var methodType = $(this).attr('method');
$.ajax({
url: action,
type: methodType,
data: data,
beforeSend: function () {
//Maybe Some Ajax Loader
},
success: function (response) {
// success
},
error: function (errorResponse) {}
});
return false; //Send form async
});
});
PHP
if (isset($_POST['record']) {
//Your PHP Code
} else {
header("HTTP/1.0 404 Not Found"); // Trow Error for JS
echo 'invalid data';
}
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request)
therefore
success:function(response){
$("#loginForm p").html(response);
}
Also seeing your query you are susceptible to sql injection
I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.
I have a small commenting system that I have modified and try implement into the site. It's in 'ajax'. When the jQuery with HTML is embedded into the page the commenting system works fine - i.e. when the user clicks on a submit button the code returns 'false', stops the page from refreshing and submits data. BUT when I implemented the code within my site and placed it in a seperate .js file the code for some reason doesn't work properly. I mean - the page after the onclick refreshes. Why is that so ? The code is not changed at all - when on its own, it works but not in the index.php site when implemented. I tried to change input type to 'button' and call a function from onclick - the page doesn't refresh but also doesn't insert the input..I'm running out of ideas as to why it is that so. Here's the code:
$(document).ready(function () {
$(".submit").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name=' + name + '&email=' + email + '&comment_area=' + comment_area;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if (name == '' || !emailReg.test(emailaddressVal) || comment == '') {
alert('Please enter valid data and type in message'); return false;
}
else {
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function (html) {
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
} return false;
});
});
//END
//COM LIST
//HTML / PHP
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#"
enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> &
nbsp;comment or <a href="index.php" id="cancel"
onmousedown="$('.slider').hide();$('#com_list').show();"><u>cancel</u></a>
</form>
</div>
//comments.php
if($_POST) {
$name=$_POST['name'];
$email=$_POST['email'];
$comment_area=$_POST['comment_area'];
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$insert = mysqli_query($connect,"INSERT INTO comments (name,email,comment,com_date)
VALUES ('$name','$email','$comment_area',curdate())");
}
////////////////
Thanks for any suggestions..
aha!
there is an error in your js:
in my console i'm getting "comment is not defined "
if(name=='' || !emailReg.test(emailaddressVal) || comment=='')
and earlier you have:
var comment_area = $("#comment_area").val(); //<--
change this to comment and it'll get past that at least.
EDIT: a little background. when firefox hits an error, sometimes it'll swallow it, and just stop running any javascript after that error, so your return false and or prevent default code isn't fire, so it's still going to post the form and refresh the page.
Change this line:
$(".submit").click(function () {
To this:
$("#comment_form").submit(function () {
The submit event gets triggered on the <form> element, not on the submit button.
Keep your damn code clean, so you can understand what you are cooking...
This will work for you:
$(document).ready(function(){
$("#comment_form").submit(function(e){
e.preventDefault(); // stop refresh
var name = $("#name").val();
var email = $("#email").val();
var comment_area = $("#comment_area").val();
var dataString = 'name='+ name + '&email=' + email + '&comment_area=' + comment_area+'&submit_comment=true';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(name=='' || !emailReg.test(emailaddressVal) || comment==''){
alert('Please enter valid data and type in message');
} else{
$.ajax({
type: "POST",
url: "comments.php",
data: dataString,
cache: false,
success: function(html){
$("#com_list").append(html);
$("#com_list").fadeIn("slow");
$("#flash").fadeOut('fast');
}
});
}
});
$('#cancel').click(function(e){
e.preventDefault();
$('.slider').hide();
$('#com_list').show();
});
});
Here is some more clean code...
<div class="slider">
<form id="comment_form" name="comment_form" method="post" action="#" enctype="multipart/form-data">
<input type="text" id="name" name="name" maxlength="16"/> Name<br /><br/>
<input type="text" id="email" name="email"/> Email (will not show)<br /><br/>
<textarea id="comment_area" name="comment_area" maxlength="1000"></textarea><br /><br/>
<input type="submit" class="submit" name="submit_comment" value="submit"/> comment or <u>cancel</u>
</form>
</div>
Here is some other clean and SECURE code
<?php
if(isset($_POST['submit_comment'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$comment_area = mysql_real_escape_string($_POST['comment_area']);
//$lowercase = strtolower($email);
//$image = md5( $lowercase );
$query = 'INSERT INTO comments (name,email,comment,com_date) '.
"VALUES ('$name','$email','$comment_area',CURDATE())";
$insert = mysqli_query($connect, $query);
}
?>