I have an ajax form which gets data with PHP post method. Instead of using the alert function of Javascript, I called bootstrap success message. But problem it doesn't show longer last only for less than a second. How to show its length until the user manually closed it as it's dismissable.
Coding Part:
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
$("#ajax-ip-success").show();
location.href = "./admin-security.php";
}
else alert("Fail! DataBase Error");
}
});
}
<?php
//--AJAX PART CALLING
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
<div class="alert alert-success alert-dismissable fade in" style="display: none;" id="ajax-ip-success">
×
<strong>Success!</strong> IP added successfully.
</div>
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
You can set Timeout for location redirect
setTimeout(function(){
location.href = "./admin-security.php";
},2000);
Related
Thanks in advance for reading.
I converted my static HTML page to Wordpress, after the contact-form stopped working. I think it has something to do with the linking in the form.js and handler.php. See ** in handler.php and form.js. Help me out !!! :)
Live version: 050management.nl
Form HTML
<div class="row">
<div class="col-md-7">
<div class="input-group">
<input type="text" class="form-control" type="text" name="Name" id="name" placeholder="Uw naam..." required data-error="Voer uw naam in">
</div>
</div>
</div>
<div class="row">
<div class="col-md-7 pt-2">
<div class="input-group">
<input type="text" class="form-control" type="email" name="Email" id="email" placeholder="Uw e-mailadres..." required data-error="Voer uw e-mailadres in">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-2">
<div class="input-group">
<textarea name="Message" id="message" class="form-control" cols="30" rows="5" placeholder="Uw bericht..." data-error="Stel uw vraag"></textarea>
</div>
</div>
</div>
<div class="input-group pt-2">
<div class="g-recaptcha" data-sitekey="6LddA2oUAAAAAHmFtwEkS68c4_UUi3hGpd7AZyOo"></div>
</div>
<div class="row">
<div class="col-md-9 pt-2">
<div class="input-group">
<input type="submit" class="contact-submit" value="Verzenden">
</div>
</div>
</div>
</form>
<div id="success_message" style="display:none">
<h4>Dank voor uw bericht.</h4>
<p>
We zullen spoedig contact met u opnemen.
</p>
</div>
<div id="error_message"
style="width:100%; height:100%; display:none; ">
<h4>Er ging iets mis...</h4>
<p>Mail ons of bel ons rechtsreeks. Dank u wel.
</div>
</div>
.........
<script src="<?php echo get_template_directory_uri().'/js/form.js' ?>"></script>
form.js (url: /js/form.js)
$(function()
{
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_message ul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label = $btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
}
});
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
$.ajax({
type: "POST",
**url: 'handler.php',**
data: $form.serialize(),
success: after_form_submitted,
dataType: 'json'
});
});
});
handler.php (url: handler.php) same folder as index.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
**require_once '/vendor/autoload.php';**
use FormGuide\Handlx\FormHandler;
$pp = new FormHandler();
$validator = $pp->getValidator();
$validator->fields(['Name','Email'])->areRequired()->maxLength(50);
$validator->field('Email')->isEmail();
$validator->field('Message')->maxLength(6000);
$pp->requireReCaptcha();
$pp->getReCaptcha()->initSecretKey('REMAINS SECRET :)');
$pp->sendEmailTo('info#050management.nl');
echo $pp->process($_POST);
In WordPress things are done a little differently.
You can post data from client to server through ajax with setting a right action.
specify a global variable ajaxurl inside head tag or anywhere before your form handling:
<script>
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
When you submit the data you can do it like this:
$.post( ajaxurl, {
action: 'handle_form',
form_data: $form.serialize()
}, function(data) {
// logic after receiving a response
}, 'json'
);
On the server side in functions.php:
function handle_form_ajax_handler() {
$form_data = $_POST['form_data'];
// logic with $form_data
wp_die();
}
add_action('wp_ajax_handle_form', 'handle_form_ajax_handler'); // add action for logged users
add_action( 'wp_ajax_nopriv_handle_form', 'handle_form_ajax_handler' ); // add action for unlogged users
i'm making a download button on my website that opens a modal with a request for password and then if the password is right should take the user to the real download. This is my javascript:
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
alert('Submitted')
}/*,
error: function() {
alert('Failure');
}*/
});
}
and this is my php:
<?php
function redirect() {
$data = $_POST["postData"];
if($data == is_null()) {
echo "Error";
} else {
echo "<script>window.open('http://www.google.com/" + $data + "', '_self')</script>";
}
}
?>
I'm using echo with a js script in php to try different methods to redirect since header() doesn't work. I'm sure the php is correctly called because i've added a row to create a file when the function is called, and the file is correctly generated.
Please, i need your help and don't kill me if i've made some "noobie" errors.
Edit:
This is the html of the modal:
<div class="modal fade bs-modal-sm" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-mediom">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Download mondo RedCraft</h4>
</div>
<div class="modal-body">
<p>Per scaricare il mondo della redcraft inserisci la password che trovi nel video di presentazione del download!</p>
<div class="control-group">
<label class="control-label" for="userid">Password:</label>
<div class="controls">
<input id="passwd" required="" name="passwordinput" type="input" class="form-control input-medium">
</div>
</div>
<div class="control-group">
<label class="control-label" for="confirmsignup"></label>
<div class="controls">
<button id="confirm" onClick="submit()" name="confirmsignup" class="btn btn-primary" data-dismiss="modal">Conferma</button>
</div>
</div>
</div>
</div>
</div>
</div>
just add one div in your html
<div id="outputredirect"></div>
and add below line in your ajax success or replace with your alert
if(redirect == "Error"){
alert(redirect);
} else {
jQuery('#outputredirect').html(redirect);
}
Your javascript code should redirect to the url returned by the php script :
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
location.href(redirect);
}/*,
error: function() {
alert('Failure');
}*/
});
}
This is my code for a form. I am asking user to input email and password and checking if user is registered or not. If he is registered then I alert success:
<form role="form" class="legacy-form" action="" method="POST" id="myform1">
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="email" name="email" id="loginemail" class="form-control" placeholder="Email Address" required>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="password" name="password" id="loginpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="row" style="padding:15px">
<div class="col-xs-6 col-sm-3 col-md-3 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-primary" id="loginbtn">
</div>
</div>
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="form-group">
<input type="submit" value="Cancel" class="btn btn-danger" data-dismiss="modal">
</div>
</div>
</div>
</form>
This is the php code wherein the connection is placed in another file 'init.php'
<?php
include('init.php');
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result) {
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
echo json_encode(array("server_response"=>$response));
} else {
echo "error";
}
mysqli_close($con);
}
?>
this is my js file. On printing info in console I get Connection sucess{"server_response":[{"Count":"1","name":"sagar"}]}
$("#loginbtn").click(function(e) {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
check_for_user(loginemail, loginpassword);
function check_for_user(loginemail, loginpassword) {
console.log("in check_for_user");
var i = 0;
console.log(i);
i++;
var c = "";
var x = "1";
var user = "";
var formdata = {
loginemail: loginemail,
loginpassword: loginpassword
}
$.ajax({
url: 'getData.php',
type: "POST",
data: formdata,
dataType: 'text',
success: handle_success,
error: handle_error
});
function handle_success(info) {
console.log(info);
var obj = jQuery.parseJSON(info);
console.log(obj);
$(obj.server_response).each(info, function(index, value) {
user = value.name;
c = value.Count;
});
console.log(c);
console.log(user);
if (x == c) {
alert("Welcome");
//document.location='online.html';
} else {
alert("Enter valid username and password");
}
}
function handle_error() {
alert("error");
}
}
});
The flow of the code is like when the #loginbtn is clicked it posts loginemail and loginpassword on php and then it checks in database whether there is an identical entry in database, if yes it alerts "welcome". I have searched a lot on StackOverflow I found that it says there is error in either parsing JSON or in decoding it.
It looks like you are echoing "Connection success" in init.php although we can't see that.
A json response should have no other content in response ... just the json.
The following is the jquery script for my otp.
<Script>
$(document).ready(function(){
$('#otp_submit').click(function(){
var otp_insert=$('#otp_insert').val();
$.ajax({
url:'smsverify.php',
type:'POST',
data:{otp_insert:otp_insert},
/* beforeSend: function(){
$('.image_loading').show();
},
complete: function(){
$('.image_loading').hide();
},*/
success: function(data){
if(data.success==1){
$('.hide2show').show();
$('html, body').animate({ scrollTop: $('.hide2show').offset().top }, 'slow');
}
else
{
$('.result').html(data);
}
},
error: function() {
console.error('Failed to process ajax !');
}
});
});
});
</Script><!-- Send Otp To the mobile number using ajax -->
This is the script which send data to smsverify.php and now this is my smsverify.php script
<?php
session_start();
$otp_password=$_POST['otp_insert'];
echo $otp_password;
if($_SESSION['otpkey']==$otp_password) {
echo "OTP is granted using session";
} else {
echo "otp is not granted not session";
}
?>
This is php script to validate sms otp which send by user.
actually script works fine , but when it returns the data .it is only showing the echo message. not showing the .hide2show class which is contain remaining registration form.
<div class="row">
<h4 class=""> <Strong> Primary Details : </Strong></h4>
<div class="col-md-3">
<label> Your Email - </label>
</div>
<div class="col-md-6">
<input type="text" name="email_user" id="email_user" placeholder="Enter Your Email" class="form-control">
<span id="error" style="display:none;color:red;">Wrong Email Id , Kindly Enter valid E-mail Id</span><i class="fa fa-file-text-o errspan"></i>
</div>
</div><!-- end of emaiol row--><label></label>
<div class="row">
<div class="col-md-3">
<label> Your Mobile Number - </label>
</div>
<div class="col-md-6">
<input type="text" name="mobile_user" id="mobile_user" placeholder="Enter Your Mobile Number ( 10 Numbers Allowed Only)" class="form-control" required title=" Wrong Mobile Number , Only 10 Digits Allowed" onkeypress='return isNumberKey(event)' maxlength="10"><i class="fa fa-lg fa-mobile-phone errspan" ></i> <span id="error_mob" style="display:none;color:red;">Wrong Mobile Number Kindly Enter Valid Number</span>
</div>
<div class="col-md-3">
<input type="button" name="otp_send" id="otp_send" class="btn btn-info btn-block" Value="Send OTP" disabled="disabled">
</div>
</div><!-- end of emaiol row--><label></label>
<img src="../assets/img/289.gif" class="image_loading" style="display:none;">
<div class="row hide4otp" style="display:none;">
<div class="col-md-3">
<label> One Time Password - </label>
</div>
<div class="col-md-6">
<input type="text" name="otp_insert" id="otp_insert" placeholder="Enter One Time Password" class="form-control" maxlength="5" ><span id="error_otp" style="display:none;color:red;">Wrong OTP , Kinldy Enter a Valid OTO Which You Have Received On Your Mobile</span>
</div>
<div class="col-md-3">
<input type="button" name="otp_submit" id="otp_submit" class="btn btn-danger btn-block" Value="Press Me !!" disabled="disabled">
</div>
</div><!-- end of emaiol row--><label></label>
<div class="row hide2show">
<h4 class=""> <Strong> Property Information : </Strong></h4>
<div class="col-md-3">
<strong>Property For : </strong>
</div>
<div class="col-md-6">
<select name="proerty_for" id="proerty_for" class="form-control" >
<option value="Sale"> For Sale</option>
<option value="Rent"> For Rent</option>
</select>
</div>
</div><!-- end of Property_for--><label></label>
This is html code for your relevnce
data.success is accessing the the success property of the object data . However, you are not returning an object from your PHP. Modify your PHP to return an object in JSON.
<?php
session_start();
$otp_password=$_POST['otp_insert'];
$response = array();
if($_SESSION['otpkey']==$otp_password) {
$response['success'] = 1;
$response['message'] = "OTP is granted using session";
} else {
$response['success'] = 0;
$response['message'] = "OTP is not granted using session";
}
echo json_encode($response);
Try following code ,it may work for you
<?php
session_start();
$otp_password=$_POST['otp_insert'];
if($_SESSION['otpkey']==$otp_password) {
echo "1";
} else {
echo "0";
}
?>
and in your ajax response check with
if(data=='1'){
// your code
}
success: function(data){
var result = $.trim(data);
if(result=="OTP is granted using session") {
$('.hide2show').show();
$('html, body').animate({ scrollTop: $('.hide2show').offset().top }, 'slow');
}
else
{
$('.hide2show').hide();
$('#error_otp_valid').show();
console.log('Wrong OTP , Please try again Later');
}
},
error: function() {
console.log('Failed to process ajax !');
}
This is my Ajax success part. thanks everyone . it helps me alot. i also learn a new things of console and trim function in jquery.
I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.
i have used codeigniter framework.
my function is working properly but when alert popup and press ok page is reloaded. i want to disable
my form code:
<form class="modal-content" name="form2" action="<?= $this->config->base_url();?>home/register_user" method="post" onSubmit="return ValidateRegister()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Create your account</h4>
</div>
<div class="page-content vertical-align-middle" style="display:block;">
<div class="form-group has-error">
<label class="control-label" for="inputTokenfieldError-tokenfield"> <?php echo validation_errors(); ?></label>
</div>
<div class="form-group form-material floating">
<input type="text" class="form-control " id="inputName" name="username" value="<?php echo set_value('username'); ?>" autocomplete="off">
<label class="floating-label">Username</label>
</div>
<div class="form-group form-material floating">
<input type="email" class="form-control " id="my_email" name="email" value="<?php echo set_value('email'); ?>" autocomplete="off">
<label class="floating-label">Email</label>
</div>
<div class="form-group form-material floating">
<input type="password" class="form-control " id="inputPassword" name="password" autocomplete="off">
<label class="floating-label">Password</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Join Now - It's Free</button>
</div>
</form>
my javascript function:
function checkRegistrations()
{
var email = $('#my_email').val();
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
// alert(data);
if(data==1)
{
//event.preventDefault();
alert('Email already registered');
return false;
window.location.reload(false);
}
else{
return true;
}
}
})
}
Just add an id to the submit button, say #submitbutton.
and use the .prop() method of jQuery to set the disabled attribute of the button.
$("#submitbutton").prop("disabled", true);
IMP: This will only work if you are keeping the same page on ajax success, But if you are reloading the page then you need to check it on php side whether this form has been submitted in this current $_SESSION.
So inside your php ajax handler, you can do the check as follows.
session_start();
if(!empty($_POST) && empty($_SESSION['post'])) {
$_SESSION['post'] = true;
... do your code
unset($_SESSION['post']);
}else{
// send the json encoded error message
}
And on the html form just add a hidden input with the name post and set value to 1 or something whatever you deem fit, so once the form is submitted, the post key will be set inside the $_SESSION SuperGlobal Array, and if the same form is submitted twice by the same user then php wont accept it.
You are returning true/false from inside an annon. function i.e. success handler. But parent function is not returning true/false.
Modify your code like this :
function checkRegistrations()
{
var email = $('#my_email').val();
var isValid = true;
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
if(data==1)
{
alert('Email already registered');
isValid = false;
}
}
});
return isValid;
}