This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
Can anyone tell me why this bit of code isn't working?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
</body>
</html>
When I push submit nothing happens. In the receiving php file I'm using $_POST['time'] and $_POST['date'] to put the data in a mysql query but it's just not getting the data. Any suggestions? I'm assuming it's something to do with the submit button but I can't figure it out
The form is submitting after the ajax request.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('click', function (event) {
// using this page stop being refreshing
event.preventDefault();
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}
echo $time."<br>";
echo $date;
}
?>
JS Code
$("#submit").click(function() {
//get input field values
var name = $('#name').val();
var email = $('#email').val();
var message = $('#comment').val();
var flag = true;
/********validate all our form fields***********/
/* Name field validation */
if(name==""){
$('#name').css('border-color','red');
flag = false;
}
/* email field validation */
if(email==""){
$('#email').css('border-color','red');
flag = false;
}
/* message field validation */
if(message=="") {
$('#comment').css('border-color','red');
flag = false;
}
/********Validation end here ****/
/* If all are ok then we send ajax request to email_send.php *******/
if(flag)
{
$.ajax({
type: 'post',
url: "email_send.php",
dataType: 'json',
data: 'username='+name+'&useremail='+email+'&message='+message,
beforeSend: function() {
$('#submit').attr('disabled', true);
$('#submit').after('<span class="wait"> <img src="image/loading.gif" alt="" /></span>');
},
complete: function() {
$('#submit').attr('disabled', false);
$('.wait').remove();
},
success: function(data)
{
if(data.type == 'error')
{
output = '<div class="error">'+data.text+'</div>';
}else{
output = '<div class="success">'+data.text+'</div>';
$('input[type=text]').val('');
$('#contactform textarea').val('');
}
$("#result").hide().html(output).slideDown();
}
});
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() {
$("#contactform input, #contactform textarea").css('border-color','');
$("#result").slideUp();
});
HTML Form
<div class="cover">
<div id="result"></div>
<div id="contactform">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="Yourname" type="text">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="admin#admin.com" type="text">
<p class="contact"><label for="comment">Your Message</label></p>
<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
PHP Code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
$output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
$output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if (strlen($message) < 5) { //check emtpy message
$output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
die($output);
}
$to = "info#wearecoders.net"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
'Reply-To: ' . $useremail . '' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to, $subject, $message . ' -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
$output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
die($output);
} else {
$output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
die($output);
}
This page has a simpler example
http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/
Here is a nice plugin for jQuery that submits forms via ajax:
http://malsup.com/jquery/form/
its as simple as:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('form was submitted');
});
});
</script>
It uses the forms action for the post location.
Not that you can't achieve this with your own code but this plugin has worked very nicely for me!
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
type="button"
should be
type="submit"
In event handling, pass the object of event to the function and then add statement i.e.
event.preventDefault();
This will pass data to webpage without refreshing it.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="msg"></div>
<form method="post" class="frm" id="form1" onsubmit="">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
<!--><span class="sp"><?php// echo $f_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
<!--><span class="sp"><?php// echo $l_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
<!--><span class="sp"><?php// echo $e_err;?></span><!-->
</div>
<div class="form-group">
<input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
<!--><span class="sp"><?php //echo $m_err;?></span><!-->
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
<!--><span class="sp"><?php //echo $p_err;?></span><!-->
</div>
<div class="radio">
<input type="radio" value="male" name="gender" id="gender" checked>male<br>
<input type="radio" value="female" name="gender" id="gender">female<br>
<input type="radio" value="other" name="gender" id="gender">other<br>
<!--><span class="sp"> <?php //echo $r_err;?></span><!-->
</div>
<div class="checkbox">
<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
<!--><span class="sp"> <?php //echo $c_err;?></span><!-->
</div>
<input type="submit" class="btn btn-warning" name="submit" id="submit">
</form>enter code here
</div>
<div class="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(function () {
$(".submit").click(function (event) {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time=' + time + '&date=' + date;
console.log(dataString);
if (time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#data").html(data);
}
});
}
event.preventDefault();
});
});
</script>
<form action="post.php" method="POST">
<input id="time" value=""><br>
<input id="date" value=""><br>
<input name="submit" type="button" value="Submit" class="submit">
</form>
<div id="data"></div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
<?php
print_r($_POST);
if ($_POST['date']) {
$date = $_POST['date'];
$time = $_POST['time'];
echo '<h1>' . $date . '---' . $time . '</h1>';
}
else {
}
?>
Related
I have written a code by watching some tutorial. What it does is, if one writes a message, it adds it to database without reloading. The problem is it doesnt show me the updated database. It shows the database that was at the time of loading. What function should i add in function() to be able to that. I dont have much knowledge of javascript so if you can add it in the code it will me really helpful. Thanks
<html>
<?include_once('database.php')?>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'home.php',
data: $('form').serialize(),
success: function () {
$('#comment').val('');
}
});
});
});
</script>
</head>
<!--body-->
<body>
<?php
if(isset($_GET["new_message"]))
{
$new_message = $_GET["new_message"];
$sql="INSERT INTO Messages(id, message, time, me) VALUES ('$session_usernumber', '$new_message',now(),'1')";
if(!mysqli_query($con,$sql))
{
echo"can not";
}
}
?>
</body>
<?php
$message_query="SELECT * FROM Messages Where id='$session_usernumber'";
$result = $con->query($message_query);
if ($result->num_rows > 0) {
while($row= $result->fetch_assoc())
{
echo $row['message'];
}
}
else
{
echo"Oops! You don't have any message";
}
?>
<div class="footer">
<form class="search_footer" name="sentMessage" id="contactForm" novalidate >
<input id='comment' autocomplete="off" autofocus="autofocus" type="text" name="new_message" placeholder="Type your message here.." required="required" class="textbox">
<input value="Send message" name="submit" type="submit" class="button">
</form>
</html>
Try this snippet, i think the problem is because your form doesn't send the message data to the database.
<div class="footer">
<form class="search_footer" name="sentMessage" id="contactForm" novalidate >
<input id='comment' autocomplete="off" autofocus="autofocus" type="text" name="new_message" placeholder="Type your message here.." required="required" class="textbox">
<input value="Send message" name="submit" type="submit" class="button">
</form>
</html>
<script>
$(document).ready(function(){
$.ajax({
url:'getmessages.php',type:'GET',success: function(message){console.log(message);}
});
$('form').on('submit', function (e) {
e.preventDefault();
var data = $('#comment').val();
$.ajax({
type: 'POST',
url: 'home.php',
data: {new_message: data},
success: function(response) {
console.log(response);
}
});
});
});
</script>
home.php file:
<?php
if(isset($_POST["new_message"]))
{
$new_message = $_POST["new_message"];
$sql="INSERT INTO Messages(id, message, time, me) VALUES ('$session_usernumber', '$new_message',now(),'1')";
if(!mysqli_query($con,$sql))
{
echo"can not";
}
getmessages.php
<?php
$message_query="SELECT * FROM Messages Where id='$session_usernumber'";
$result = $con->query($message_query);
if ($result->num_rows > 0) {
while($row= $result->fetch_assoc())
{
echo $row['message'];
}
}
else
{
echo"Oops! You don't have any message";
}
?>
Many apologies if the answer to my question is obvious.
I am trying to incorporate the Google reCaptcha into my website.
This is the javascript in the HEAD of my page:
var onSubmit = function(token) {
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
The reCaptcha is visible and working.
The above code gives me the result of 'success:' BUT is not processing the form using the call to the php file.
All other scripts on the page are working fine.
Here is the contact.php code:
I've made those changes to my code. No change in the result however. Here is the code for the php file:
<?php
//contact form submission code
//Validate data on the form
// define variables and set to empty values
$name = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = contact_input($_POST["name"]);
$email = contact_input($_POST["email"]);
$message = contact_input($_POST["message"]);
}
function contact_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// put your email address here
$youremail = 'my#email.co.uk';
// prepare a "pretty" version of the message
// Important: if you added any form fields to the HTML, you will need to add them here also
$body = "Contact Form from Wilderness Canoe website just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['email'] && !preg_match( "/.+#.+\..+/i", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers );
}
?>
and the code for the form:
<form id="form" method="post" action="assets/php/contact.php" onsubmit="return validate();">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-account mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="name"> Full Name</label>
<input class="mdl-textfield__input " type="text" id="name" required name="name">
<!--error msg ><span class="mdl-textfield__error">Only alphabet and no spaces, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-email mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="email">Your Email</label>
<input class="mdl-textfield__input " type="text" id="email" required name="email">
<!--error msg ><span class="mdl-textfield__error">Valid email only, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-comment-text mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="message">Your Message/Comment</label>
<textarea class="mdl-textfield__input " type="text" rows= "1" max-rows="4" id="message" name="message"></textarea>
</div>
<!-- antispam --><p class="antispam">Leave this empty: <input type="text" name="url" /></p>
<!-- RECAPTCHA -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div class="clear"><button type="submit" value="Send" name="submit" id="mc-embedded-contact" class="send">Submit</button></div>
</form>
The complete javascript:
<script type="text/javascript">
var onSubmit = function(token) {
var formData = $("#form").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
var onloadCallback = function() {
grecaptcha.render('mc-embedded-contact', {
'sitekey' : '6Ldbfg8UAAAAAAaWVBiyo4uGfDqtfcnu33SpOj6P',
'callback' : onSubmit
});
};
</script>
Your ajax request doesnt send any form data in your code. You should add your form data like this:
var onSubmit = function(token) {
var formData = $("#yourFormId").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}
I want to have an account signup page where I check if the is email already used. If so the PHP should send a message saying so, else there should be an insert statement. What I have now is an html form which gets submitted via javascript to php, this all works, but i cant't get any error messages to work. How can i use an server (PHP) response in my javascript?
Server:
<?php
require 'config.php';
require 'resources/password.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$verifyemail = mysqli_real_escape_string($_POST['email']);
$numberofrowsquery = "select * from `users` where `user_email`='$email'";
$numberofrows=mysqli_query($con,"select * from `users` where `user_email`='$email'");
//$exitst = mysqli_num_rows($numberofrows);
if($numberofrows->num_rows)
{
//echo "exist";
echo json_encode(array(
'status' => 'exist',
'message'=> 'exist message'
));
}
else
{
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10));
$query = "INSERT INTO users(user_email, username, user_voornaam,user_achternaam,user_password,user_hash) VALUES ('$email', '$username', '$name','$lastname','$password','$hash')";
$succes = mysqli_query($con,$query);
if($succes){
//echo "success";
echo json_encode(array(
'status' => 'success',
'message'=> 'success message'
));
}
else{
//echo"failed";
echo json_encode(array(
'status' => 'failed',
'message'=> 'failed message'
));
}
}
mysqli_close($con);
//echo "Uw account is succesvol geregistreerd.";
?>
HTML / Javascript:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ajax example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="message"></div>
<form id="myform" action="http://stopfoodwaste.stefspakman.com/app/signup.php">
<input type="text" name="name" required/>
<input type="text" name="lastname" required/>
<input type="text" name="username" required/>
<input type="text" name="email" required/>
<input type="password" name="password" required/>
<input type="submit" value="submit"/>
</form>
<div id="response"></div>
<script>
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
if(data.status === "success"){
$("#message").hide();
$("#response").html(data);
alert("succes");
location.reload();
}
else if(data.status === "exist"){
$("#message").hide();
alert("Dit emailadress is reeds in gebruik, probeer in te loggen of gebruik een ander mailadres.");
}
else if(data.status === "failed"){
alert("Something Went wrong");
}
}
});
});
});
</script>
</body>
</html>
Anyone some suggestions?
Replace your submit button with simple button and form submit event to button click event. Since you used the submit button, it always submits to action php file.
Update you HTML code like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ajax example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="message"></div>
<form id="myform" action="http://stopfoodwaste.stefspakman.com/app/signup.php">
<input type="text" name="name" required/>
<input type="text" name="lastname" required/>
<input type="text" name="username" required/>
<input type="text" name="email" required/>
<input type="password" name="password" required/>
<input type="button" id="submitBtn" value="submit"/>
</form>
<div id="response"></div>
<script>
$(function() {
$("#submitBtn").on("click", function(e) {
e.preventDefault();
$.ajax({
url: 'http://stopfoodwaste.stefspakman.com/app/signup.php',
type: 'POST',
data: $('#myform').serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
if(data.status === "success"){
$("#message").hide();
$("#response").html(data);
alert("succes");
location.reload();
}
else if(data.status === "exist"){
$("#message").hide();
alert("Dit emailadress is reeds in gebruik, probeer in te loggen of gebruik een ander mailadres.");
}
else if(data.status === "failed"){
alert("Something Went wrong");
}
}
});
});
});
</script>
</body>
</html>
i am trying to send some values from html form to php page.
here in the form i have some values which are hidden.and one text field which its value has to be passed to php page.
index.php:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="friend-invite.php" method="get">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="submit" name="submit" value="Invite" class="btn btn-primary">
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
friend-invite.php:
<?php
include('_header.php');
$user_email = $_GET['friendemail'];
$invited_by = $_GET['invitename'];
$invite_link = $_GET['invite-url'];
$product_name = $_GET['invite-product-name'];
if (isset($user_email, $invited_by, $invite_link, $product_name)){
sendInvitation($user_email,$invited_by,$invite_link,$product_name);
} else {
echo "Are you trying to do something nasty??";
}
function sendInvitation($user_email,$invited_by,$invite_link,$product_name)
{
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->IsHTML(true);
} else {
$mail->IsMail();
}
$mail->From = EMAIL_VERIFICATION_FROM;
$mail->FromName = $invited_by;
$mail->AddAddress($user_email);
$mail->Subject = SHOP_INVITE;
$link = $invite_link;
$mail->Body = $invited_by." ".FRIEND_INVITE_PRODUCT."<a href='".$link."'>".$product_name."</a>";
if(!$mail->Send()) {
$this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
return false;
} else {
return true;
}
}
?>
AJAX function:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
the friend-invite.php page is getting the values that has been passed to it and check if the values has been set, if it has been set then it will call the php function sendInvitation() with the parameters. now all these things are happening pretty good.but i want to do it through AJAX. how can i do that.
You forgot to give your hidden fields an id:
echo '<input type="hidden" name="invitename" id="invitename" value="'.$_SESSION["user_name"].'">' ;
...
Change your index.php as:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="button" id="btn-submit" name="submit" value="Invite" class="btn btn-primary" />
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
And change AJAX function as:
$(function () {
$('#btn-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
We do not need a submit button in form if we using AJAX.
Dude you are simply making your code complex ... you are doing form submit + ajax submit .I think there you are going wrong.
Just try these:
Remove action="friend-invite.php" from your form tag and try . if this does not help than make your button input type button or use button tag. just try all these it should work.
If all this does not work than give id and name to your form ,,and use to submit as:
$(function() {
$("#form_id").on("submit", function(event) {
Try all these