Google reCaptcha validate using jquery AJAX - php

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>

Related

send csrf_token with a ajax request

I need help to send the token with ajax request. He always say: "invalid".
What Mistake do I make?
world.php:
<form name="theform" id="suchform" method="POST">
<p><input type="text" class="find_person search_btn" placeholder="Person Suchen" tabindex="1"></p>
<p><input type="hidden" class="csrf_token" value="<?= echo $_SESSION['csrf_token']; ?>"></p>
</form>
<div id="output">
</div>
<script>
$('#suchform').on('input', function(event) {
event.preventDefault();
var name = $('#suchform').find('.find_person').val();
var token = $('#suchform').find('.csrf_token').val();
$.ajax({
type: 'POST',
url: 'show_user.php',
data: {find_person:name, csrf_token:token},
success: function(data) {
$('#output').html(data);
}
})
})
</script>
show_user.php
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
echo $_POST['csrf_token'] . '<br>' . $_SESSION['csrf_token']. '<BR>';
exit("invalid");
}
connect.php
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));

jquery ajax contact form redirects to contact.php instead of catching php echo and executing sucess function

I have a contact form php+jquery+HTML.the form div is hidden in index.HTML,until contact button is presses.Jquery works,Ajax call posts needed data to php,which echoes a response.The problem is when php echoes,instead of remaining on same page without refreshing,browser redirects to contact.php,where the echo is showed correctly.I think the Ajax part won't catch the response from server,although syntax is the same in all tutorials.please assist.
html part:
HTML
<div id = 'contact_form'>
<div id = 'result'></div>
<form id="contactform" action="js/contact.php" method="POST" enctype="multipart/form-data">
<div class="row">
<input id="name" class="input" name="name" type="text" required = 'true' value="" size="30" placeholder='Nome'/>
</div>
<div class="row">
<input id="email" class="input" name="email" type="text" required = 'true' value="" size="30" placeholder = 'Email'/>
</div>
<div class="row">
<textarea id="message" class="input" name="message" rows="7" cols="50" required = 'true' placeholder = 'Messagio'></textarea>
</div>
<input id="submit_button" class = 'myButton' type="submit" value="Manda messagio" />
</form>
</div>
</div>
JS
$('#submit_btn').click(function(){
var user_name = $("input#name").val();
if (user_name == "") {
$("input#name").focus().addClass('active');
return false;
}
var user_email = $("input#email").val();
if (!$("input#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("input#email").focus().addClass('active');
return false;
}
var msg = $("textarea#message").val();
if (message == "") {
$("textarea#message").focus().addClass('active');
return false;
}
var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function(d) {
console.log(d);
}
});
return false;
});
PHP
<?php
$toEmail = "x#gmail.com";
$subject = "dal tuo sito ";
$mailHeaders = "From: " . $_POST["name"] . "<". $_POST["email"] .">\r\n";
if(mail($toEmail,$subject,$_POST["message"], $mailHeaders)) {
echo "Mail Sent";
} else {
echo "Problem in Sending Mail";
}
?>
If you want to keep the same button you can change your js.
$('#submit_btn').click(function(e){
e.preventDefault();
//YOUR CODE HERE
}
Because you used a submit type input, I recommend you change the submit input for a link like button. And also remove the action attr from the form:
HTML
Send
JS
<script>
$('#btn').on("click", function(){
//Your ajax here
//var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: {name: user_name, email: user_email, message: msg}
}).done(function(response){
console.log(response);
});
});
</script>

Insert records to mysql database with php using Ajax

How to do coding of this Code With Using Ajax.Please Help.
I am Bignner here and i have written this code it's working but i want to use with ajax this because don't want to reload the page...?
PHP File
//Code For Making Form And getting Data…..
<html>
<body>
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form action="Form_Data.php" method="post">
ID: <input type="text" name="ID"><br><br>
NAME: <input type="text" name="NAME"><br><br>
PASSWORD: <input type="text" name="PASSWORD"><br><br>
CREDITS: <input type="text" name="CREDITS"><br><br>
E_mail: <input type="text" name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" name="MODIFIED_ON"><br><br>
<input type="submit">
</form>
</body>
</html>
//code for taking data from form data.
<html>
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
mysql_close($conn);
?>
</html>
I have Tried Yet ... Is Blewo...
file for html and ajax
<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form onsubmit="return false" method="post">
ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NMAE" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="Email_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send">
</div>
<script>
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
//make the postdata
var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&REDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
});
$.ajax({
url : "Form_Data.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
</script>
</form>
</body>
</div>
</html>
code for query...
<html>
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
mysql_close($conn);
?>
</html>
I have Solved It ... How To Use Ajax and MYSQL...
PHP CODE
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
// $retval=mysql_query($query,$conn);
if ($query_run)
{
echo 'It is working';
}
mysql_close($conn);
?>
HTML FILE....
<html>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</HEAD>
<body>
<div id="status_text">
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
ID: <input type="text" id="ID" name="ID"><br><br>
NAME: <input type="text" id="NAME" name="NAME"><br><br>
PASSWORD: <input type="text" id= "PASSWORD"name="PASSWORD"><br><br>
CREDITS: <input type="text" Id= "CREDITS"name="CREDITS"><br><br>
Email_ID: <input type="text" id="EMAIL_ID"name="EMAIL_ID"><br><br>
CREATED_ON:<input type="text" id="CREATED_ON" name="CREATED_ON"><br><br>
MODIFIED_ON:<input type="text" id="MODIFIED_ON" name="MODIFIED_ON"><br><br>
<input type="submit" id="btn_submit" name="submit" value="Send"/>
</div>
<script>
<!--
//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;
}
}
} }
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
// make the postdata
// var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&CREDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
// alert(postData);
var myData={"ID":ID,"NAME":NAME,"PASSWORD":PASSWORD,"CREDITS":CREDITS,"EMAIL_ID":EMAIL_ID,"CREATED_ON":CREATED_ON,"MODIFIED_ON":MODIFIED_ON};
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : myData,
success: function(data,status,xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
});
</script>
</body>
</div>
</html>
change your script because your ajax was outside the click function
//on the click of the submit button
$("#btn_submit").click(function(){
//get the form values
var ID = $('#ID').val();
var NAME = $('#NAME').val();
var PASSWORD = $('#PASSWORD').val();
var CREDITS = $('#CREDITS').val();
var EMAIL_ID = $('#EMAIL_ID').val();
var CREATED_ON = $('#CREATED_ON').val();
var MODIFIED_ON = $('#MODIFIED_ON').val();
//make the postdata
var postData = '&ID='+ID+'&NAME='+NAME+'&PASSWORD='+PASSWORD+'&REDITS'+CREDITS+'&EMAIL_ID'+EMAIL_ID+'&CREATED_ON'+CREATED_ON+'&MODIFIED_ON'+MODIFIED_ON;
//call your .php script in the background,
//when it returns it will call the success function if the request was successful or
//the error one if there was an issue (like a 404, 500 or any other error status)
$.ajax({
url : "Form_Data.php",
type: "POST",
data : postData,
success: function(data,status, xhr)
{
//if success then just output the text to the status div then clear the form inputs to prepare for new data
$("#status_text").html(data);
$('#ID').val();
$('#NAME').val('');
$('#PASSWORD').val('');
$('#EMAIL_ID').val('');
$('#CREATED_ON').val('');
$('#MODIFIED_ON').val('');
}
});
});
</script>
and change your php code to this
<?php
include 'connnect.php';
mysql_set_charset('utf8');
//query for insert data into tables
if(isset($_POST['NAME'])){
$ID = $_POST['ID'];
$NAME =$_POST['NAME'];
$EMAIL_ID =$_POST['EMAIL_ID'];
$PASSWORD =$_POST['PASSWORD'];
$CREDITS =$_POST['CREDITS'];
$CREATED_ON=$_POST['CREATED_ON'];
$MODIFIED_ON=$_POST['MODIFIED_ON'];
$query = "INSERT INTO `user_table`
(`ID`,`NAME`,`EMAIL_ID`,`PASSWORD`,`CREDITS`,`CREATED_ON`,`MODIFIED_ON`)
VALUES
('$ID','$NAME','$EMAIL_ID','$PASSWORD','$CREDITS','$CREATED_ON','$MODIFIED_ON')";
$query_run= mysql_query($query);
$retval=mysql_query($query,$conn);
if ($query_run)
{ echo 'It is working';
}
}
mysql_close($conn);
?>
In this code I'm just submitting your two input fields, the rest you can add by yourself. Try this:
<html>
<body>
Fill -ID,NAME,EMAIL_ID,PASSWORD,CREDITS,
<form action="Form_Data.php" method="post">
NAME: <input id="name" type="text" name="NAME"><br><br>
PASSWORD: <input id="password" type="text" name="PASSWORD"><br><br>
<input type="submit" id="submit">
</form>
</body>
</html>
$("#submit").click(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "your_php_path.php",
data: 'name=' + name+ '&password=' + password,
success: function(result) {
alert(result);
}
});
});

jquery ajax loaded form submit sets serialized data into url

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>

Page refreshes on submit click with ajax

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);
}
?>

Categories