So basically I need to submit this quick-interest-slider form without page reload - https://loancalc.000webhostapp.com , this isn't my code, i'm not too experienced with wordpress or php.
After adding this $('.qis-form').on('submit'... code the slider continues to reload the page once i've clicked "apply now".
I don't know exactly what in the code I should be working with but i'm told the functions are...
qis-loop (validates and processes the form), qis_process_form also processes the form and sends email.
function qis_loop($atts) {
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
qis_process_form
function qis_process_form($values) {
global $post;
$content='';
$register = qis_get_stored_register($values['formname']);
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$qis_messages = get_option('qis_messages');
$application = qis_get_stored_application_messages();
if(!is_array($qis_messages)) $qis_messages = array();
$ip=$_SERVER['REMOTE_ADDR'];
$url = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
$page = get_the_title();
if (empty($page)) $page = 'Unknown Page';
$period = $values['loan-period'] == 1 ? $settings['singleperiodlabel'] : $settings['periodlabel'];
if (!$period) $period = $settings['period'];
$values['loan-amount'] = $settings['currency'].$values['loan-amount'];
$values['loan-period'] = $values['loan-period'].' '.$period;
$radio = explode(',',$register['radiolist']);
$values['yourradio'] = $radio[$values['radiooption']];
for ($i=1;$i<=3;$i++) {
if ($values['check'.$i]) $checks .= $register['check'.$i] . '<br>';
}
if ($checks) $values['yourchecks'] .= substr($checks, 0, -4);
$values['sentdate'] = date_i18n('d M Y');
$values['timestamp'] = time();
if ($register['storedata']) {
$newmessage = array();
$arr = array(
'reference',
'yourname',
'youremail',
'yourtelephone',
'yourmessage',
'yourchecks',
'yourradio',
'yourdropdown',
'yourconsent',
'loan-amount',
'loan-period',
'confirmation',
'formname',
'sentdate',
'timestamp'
);
foreach ($arr as $item) {
if ($values[$item] != $register[$item]) $newmessage[$item] = $values[$item];
}
$qis_messages[] = $newmessage;
update_option('qis_messages',$qis_messages);
}
if (!$auto['notification']) {
qis_send_notification ($values);
}
if (($auto['enable'] || $values['qis-copy']) && !$application['enable']) {
qis_send_confirmation ($auto,$values,$content,$register);
}
if ($register['qis_redirect_url']) {
$location = $register['qis_redirect_url'];
echo "<meta http-equiv='refresh' content='0;url=$location' />";
exit;
}}
The data is validated in qis_verify_application
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
If it passes validation the form is then processed in qis_process_application.
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
I have made an ajax call here
jQuery('.qis-form').on('submit', function(event){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
After hunting down your html, you will want to call it on the APPLY click NOT form submit.
jQuery(document).on('click','.toggle-qis a', function(event){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
return false;
});
I have this function where on onkeyup it verifies the mobile number whether it exists in the database already or not now the issue is even if the response is "true" it will always show as false
PHP
elseif ($action == 'check_mobile_phone')
{
$mobile = trim($_GET['mobile']);
$mobile = json_str_iconv($mobile);
if (mobile_register($mobile))
{
echo 'false';
}
else
{
echo 'true';
}
}
Ajax Call
function checkMobilePhone(mobile)
{
if (mobile == '')
{
error.find('#mobile_notice_text').html('Mobile number cant be empty.');
submit_disabled = true;
}
else if (!Utils.isMobile(mobile))
{
error.find('#mobile_notice_text').html('Please enter mobile number in local format.');
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_mobile_phone', 'mobile=' + mobile, check_mobile_callback , 'GET', 'TEXT', true, true );
}
Response
function check_mobile_callback(result)
{
var logform = $('form[name="formUser"]');
var error = logform.find('#mobile_notice');
if ( result === "true" )
{
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
error.find('#mobile_notice_text').html('Phone number already exists.');
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function mobile_register($mobile)
{
$res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['db']->table('users') .
" WHERE mobile_phone = '$mobile'");
return $res;
}
I have a simple registration form. What I want to achieve is when the output from PHP is success then do something. Else do something else. Both in AJAX. I hope you can help me because I am totally new in jQuery and AJAX
This is part of my PHP for this form:
if ($kontrolaMenoPocet != 0) {
$error[] = "<p class='text_chyba'>Takéto meno už existuje!</p>";
}
if ($pocetZnakovNick > 15) {
$error[] = "Nick môže mať maximálne 15 znakov!";
}
if ($kontrolaEmailPocet != 0) {
$error[] = "<p class='text_chyba'>Takýto E-mail sa už používa</p>";
}
if ($pocetZnakovHeslo != 0 AND $pocetZnakovHeslo < 6) {
$error[] = "Heslo musí mať minimálne 6 znakov";
}elseif ($pocetZnakovHeslo == 0) {
echo "";
}
if ($heslo != $hesloZnova) {
$error[] = "Hesla sa nezhodujú";
}
if (empty($error)) {
//writte into database
}
if (isset($error)) {
if (empty($error)) {
echo "Success";
}else{
foreach ($error as $chyba) {
echo $chyba;
}
}
}
And this is my jQuery with AJAX:
if (nick == '' || email == '' || heslo == '' || hesloZnova == '') {
$('.registracia_form .nick, .email, .password, .password_again').addClass('inputError');
} else {
$.ajax({
method: 'post',
url: 'PHP/register.php',
data: data,
}).done(function(data) {
console.log("success");
}).fail(function() {
console.log("error");
}).always(function() {
console.log("complete");
});
}
Change your .done() callback to:
.done(function(data) {
console.log(data);
if (data === 'Success') {
// do something
} else {
// do something else
}
})
In PHP, when there is error, use http_response_code function to set status code other than 200 so the fail function in ajax will be called.
after success my page wont reload but it just close the window
this is my jQuery script
jQuery("#edit").dialog({
modal: true,
resizable: false,
draggable: false,
autoOpen: false,
width: 400,
buttons: [
{
text: "Ok",
click: function() {
var message = "";
var id = jQuery.trim(jQuery("#id").val());
var fname = jQuery.trim(jQuery("#firstname").val());
var lname = jQuery.trim(jQuery("#lastname").val());
var email = jQuery.trim(jQuery("#email").val());
var telephone = jQuery.trim(jQuery("#telephone").val());
var mobile = jQuery.trim(jQuery("#mobile").val());
var address = jQuery.trim(jQuery("#address").val());
var bdate = jQuery.trim(jQuery("#bdate").val());
if (fname == "") {message += "Please enter firstname\n"};
if (lname == "") {message += "Please enter lastname\n"};
if (email == "") {
message += "Please enter email\n"
}
else{
if(!ValidateEmail(email)){
message += "Please enter valid email address.\n"
}
}
if (telephone == "") {message += "Please enter telephone\n"};
if (mobile == "") {message += "Please enter mobile\n"};
if (address == "") {message += "Please enter address\n"};
if (bdate == "") {message += "Please enter birthdate"};
if (message != "")
{
alert(message);
return false;
}
else
{
jQuery.ajax({
type: "POST",
dataType: "json",
url: "update.php",
async:true,
data: {
"id": id,
"firstname": fname,
"lastname": lname,
"email": email,
"telephone": telephone,
"mobile": mobile,
"address": address,
"bdate": bdate
},
sucess: function(){
window.location.reload(true);
}
});
}
}
},
{
text: "Cancel",
click: function() {
jQuery(this).dialog( "close" );
}
}
]
});
and here is my PHP
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$bdate = date("Y-m-d",strtotime($_POST['bdate']));
$sql = "UPDATE user SET
firstname='$firstname', lastname='$lastname', email='$email', telephone='$telephone', mobile='$mobile', address='$address', bdate='$bdate' WHERE id=$id";
$result = mysql_query($sql);
if($result){
echo json_encode(array(
"success" => true,
));
}
i tried also this but doesnt reload the page
sucess: function(data){
if(data.success == true){
window.location.reload(true);
}
}
also i changed the window.location.reload into location.reload and i tried also removing the true in it
I have a PHP file receiving data from Ajax but after receiving the data I am sending a success message from php using json_encode, but the message error is hit is being alerted even though the SQL query is successful. This process worked well for localhost but when I uploaded it in main server there is an error.
Here Is my JS file:
$(function() {
$("#userReg_btn").click(function(e) {
//user registration in
var array = [];
var flag = false;
var firstName = $("#uFn").val();
var lastName = $("#uLn").val();
var email = $("#uEa").val();
var pass = $("#uPn").val();
var mobile = $("#uMn").val();
var nID = $("#uNm").val();
var age = $("#uAn").val();
var prof = $("#uPc").val();
if (firstName == "" || lastName == "" || email == "" || pass == "" || mobile == "" || nID == "" || age == "" || prof == "") {
e.preventDefault();
alert("Please provide some input");
flag = false;
} else if (mobile.length != 11 || nID.length != 17) {
e.preventDefault();
alert("Please provide correct input");
flag = false;
} else {
array.push(firstName);
array.push(lastName);
array.push(email);
array.push(pass);
array.push(mobile);
array.push(nID);
array.push(age);
array.push(prof);
alert(array);
console.log(array);
flag = true;
}
if (flag == true) {
$.ajax({
url: "http://demoname.co/CustomerRegistration.php",
data: {
firstName: array[0],
lastName: array[1],
email: array[2],
pass: array[3],
mobile: array[4],
nID: array[5],
age: array[6],
prof: array[7]
},
type: "POST",
dataType: "json",
success: function(suc) {
alert("in success");
alert(suc);
console.log("success");
},
error: function(err) {
alert("error is hit");
alert(err);
console.log(err);
}
});
} else {
alert("Form error");
}
alert("USer Reg");
});
Here is my PHP file:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
// The JSON standard MIME header.
header('Content-type: application/json');
$con=mysql_connect("localhost","username", "password");
mysql_select_db("database name",$con);
$fname = $_POST['firstName'];
$lname=$_POST['lastName'];
$username=$_POST['email'];
$password=$_POST['pass'];
$phone=$_POST['mobile'];
$nid=$_POST['nID'];
$age=$_POST['age'];
$profession=$_POST['prof'];
$query="INSERT INTO customerregistration(FirstName,LastName,Username,password,PhoneNumber,NID,Age,Profession) VALUES('$fname','$lname','$username','$password','$phone','$nid','$age','$profession');";
if(mysql_query($query))
{
$suc= 'success';
echo json_encode($suc);
}
else
{
echo mysql_error();
}
?>