php include causing jquery submit function to not work - php

I'm trying to submit a form. The form is in html I'm using jquery to pass the form to a php page for processing and json_encode to pass back the results to display to the user. If I try to add an incude xxx.php on the php page that jquery is submitting to it kills the whole thing.
Here is how it lays out:
This is the main layout page and includes the form as you can see
<form id="jq_forgot_password" class="forgot_password" action="" method="post" name="password_form">
<?PHP include 'widgets/recover_pass.php'; ?>
</form>
This is the content of the form itself:
<!-- Password Recovery Form-->
<div class="form_text">
<p>
<label for="email">Email:</label>
<input type="email" id="recover_email" name="recover_email" placeholder="Enter your email address" class="field_boarder" value="" size="25px" maxlength="255"/> </p>
<div class="login_button_container">
<input name="login_button" type="submit" class="login_button" value="Submit"/>
</div>
</div>
This is the jquery script that is posting the form data and preventing the default submit button from refreshing the page:
// Forgot Password Validation and Post Function
$(function(){
$("#jq_forgot_password").submit(function(e){
e.preventDefault();
$.post("widgets/recover_pass_process.php", $("#jq_forgot_password").serialize(),
function(data){
if(data.email_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html("<div'> Sorry you must enter a valid e-mail address. Try again.</div>");
} else {
$('div.message_error').hide();
$('form#jq_forgot_password').hide();
$('div.message_success').fadeIn();
$('div.message_success').html("<div'>You're Password has been sent to" + data.email + ". Thank you </div>");
}
}, "json");
});
});
This is the php file that the jquery submit function is submitting to:
<?php
$email_check = '';
$return_arr = array();
if(filter_var($_POST['recover_email'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
$return_arr["email"] = $_POST['recover_email'];
echo json_encode($return_arr);
?>
This all works fine BUT if I add an include statement at the top of the recover_pass_process.php like this:
<?php
include 'func/user.func.php';
$email_check = '';
$return_arr = array();
if(filter_var($_POST['recover_email'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
$return_arr["email"] = $_POST['recover_email'];
echo json_encode($return_arr);
?>
Then it all comes to a screeching halt even if the included file has nothing in it. Just the fact that I'm trying to include another file kills it.
What am I doing wrong??? Thank you in advance!!

$("#jq_forgot_password").live("submit",function(e){
e.preventDefault();
$.post("widgets/recover_pass_process.php", $("#jq_forgot_password").serialize(),
function(data){
if(data.email_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html("<div'> Sorry you must enter a valid e-mail address. Try again.</div>");
} else {
$('div.message_error').hide();
$('form#jq_forgot_password').hide();
$('div.message_success').fadeIn();
$('div.message_success').html("<div'>You're Password has been sent to" + data.email + ". Thank you </div>");
}
}, "json");
});
try this..

Related

Sending a form in the modal window

sorry that I start this topic. I know that there were a lot of topics in this matter. But still I can not deal with it, because I need the success / failure messages to be displayed as below:
<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="save-test-form" value="Save">
</form>
/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$_SESSION['success_msg'] = 'All is well.';
}else{
$_SESSION['error_msg'] = 'Enter the email.';
}
}else{
$_SESSION['error_msg'] = 'Enter the name.';
}
}
?>
And jquery?
My point is to submit this form without reloading the page (because it's in the modal window) and I have to display success / failure messages in the form (also without reloading the page). I do not know how to do it.
I will be grateful for the help and explanation of how to do it step by step.
Your PHP script is executed on page reload, so when using Ajax you must manually show messages from server:
// PHP
$response = [];
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$response['success'] = 'All is well.';
}else{
$response['error_msg'] = 'Enter the email.';
}
}else{
$response['error_msg'] = 'Enter the name.';
}
echo json_encode($response); // Format array as json and output it
die(); // No other output, just JSON
}
// jQuery
$.ajax({
url: '',
method: 'POST',
dataType: 'json',
data: {},
success: function (response) {
if (typeof response.success !== 'undefined') {
$('#responseMessage').text(response.success);
} else {
$('#responseMessage').text(response.error_msg);
}
}
})

How to submit the form without leaving the main index.php using external php file?

So, here is my html form code:
<form id="login_form" action="login.php" method="POST">
<h2>Already a member? Sign in!</h2>
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="password"></p>
<input type="submit" name="login_submit" value="Sign In">
</form>
I included the external "login.php" file top of the page, and this is how it looks like:
<?php
include 'config.php';
if (isset($_POST["login_submit"]))
{
$username = $_POST["username"];
$password = $_POST["password"];
$query = "SELECT username, hashed_password FROM users WHERE username = '$username';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rows_num = mysqli_num_rows($result);
if ($rows_num == 0) {
echo "This user doesn't exist!";
}
else {
$password_match = password_verify($password, $row['hashed_password']);
if (!$password_match) {
echo "The passwords do not match.";
}
else {
header("Location: index.php");
echo "Welcome ".$username."!";
}
}
}
?>
So, the logging system works well, but after press Sign in, it redirects to login.php and depending on the entered datas, it shows the result of the log in. How to do that, the login.php is just running in the background after hitting the submit button on index.php, and the result of the login appears under the login form insetad of login.php?
I know it's a horribly easy thing, but I just can't do that.
Thank you for the help! :)
jQuery Ajax
If I understand your question correctly you want to submit the form without navigating away from the page you are on. To do this you use javascript to make an xhr request or more commonly refereed to as an ajax request.
jQuery is not required to do this, but it makes it much easier.
On Submit Event
$( "#login_form" ).submit(function( event ) {
event.preventDefault();
var formdata = $( this ).serializeArray();
$.ajax({
type:"POST",
url:"login.php",
data: formdata,
success: function() {
// do something?
}
});
});

PHP+JQuery+AJAX Form not getting resubmitted with different values

This is embarrassing but I cant seem to figure out why my form wont repost after changing the values.
To be clearer, I have this password recovery form in which user enters the email address. The form is processed in PHP through AJAX and a validation/success message is displayed on the form page.
The issue here is that if the user has entered an invalid email address, it displays the error message but if the user then corrects the email address and tries to submit again, it doesn't process the input unless if the page is explicitly refreshed (in which case it shows the resubmission warning which is very annoying). Is there some property that sets the form and needs to be 'un-set' through code? How can I improve this experience? I have posted the code below.
<form id="pwd_rec_form" method="post" action="">
<div class="row">
<div class="large-6 columns">
<input type="email" required placeholder="Email ID" name="email"/>
</div>
</div>
<div id="val_msg" class="row"></div>
<div class="row">
<div class="large-6 columns">
<input id="submit_button" type="submit" value="Send" class="button"/>
</div>
</div>
<div class="row">
<div class="large-6 columns">
Back to login page
</div>
</div>
</form>
<script>
$(function()
{
$("#pwd_rec_form").submit(function()
{
var formdata = $(this).serializeArray();
var hideMsg = function() {$("#val_msg").hide()};
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "recover-password.php",
data: formdata,
success: function(res)
{
$('#val_msg').html(res);
setTimeout(hideMsg, 5000);
}
});
$("#pwd_rec_form").trigger("reset");
return false;
});
});
</script>
PHP :
<?php
include 'db-connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$conn = getDBConnection();
// Check connection
if (mysqli_connect_errno())
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_connect_error() . '
</div>'
);
exit();
}
$eID = mysqli_real_escape_string($conn, trim(strip_tags($_POST['email'])));
$query = 'SELECT password FROM member_login WHERE email_id = "' . $eID . '";';
$result = mysqli_query($conn, $query);
if($result == FALSE)
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_error($conn) . '
</div>'
);
}
else
{
if(mysqli_num_rows($result) == 0) // User not found.
{
echo('<small class="error">This email address is not registered with us.</small>');
}
else
{
$pswd = mysqli_fetch_assoc($result);
//mail the pswd
echo(' <div data-alert class="alert-box success">
Your password has been successfully sent to your registered email address.
</div>'
);
/* free result set */
mysqli_free_result($result);
}
}
mysqli_close($conn);
}
?>
I think your problem is that you have a submit button, which automatically submits the form and refreshes the page, so your javascript doesn't get used. Try making your submit button a type="button" and then changing your jQuery to $("#pwd_rec_form").click(function() and see if that works.
You could hook the form submit, or if you wanted you can hook the click event of the submit button, prevent the default action and instead do your javascript code. Here is an example hooking the "submit_button" click event:
$(document).ready(function() {
$("#submit_button").click(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
Alternative you can do this:
$(document).ready(function() {
$(form).submit(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
The code above just hooks the form on the submit request, prevents the default action, and then you slap your ajax code in there.
I appreciate your help guys. I knew it was something silly. Turns out the form was getting processed but the validation/success messages were not being displayed as the div element that I was hiding using javascript during the first submission needed to be shown again for the second attempt!
Could you try this :
<script>
$(document).ready(function(){
$('#pwd_rec_form').on('submit', function(e){
e.preventDefault();
// insert AJAX call
});
It worked for me, the event is trigged on each click.
Best regards,

How to use a php ajax form in a color box?

I have a login form in (login.php). It call a separate sample.php via ajax, and sample.php returns it the value and the Javascript will show the relevant message depending on the php return value. It works perfectly fine in a normal webpage. But when I display the form in color box (in test.php). The javascript/jquery failed to run. I have research abit about this by using ajaxform, but how exactly do i do it? Please advise me some keywords for me to research further :(, i am stucked.
test.php:
$(".ajax").colorbox();
<a href="" class=ajax>Login</a>
This is my ajax function:
function login()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "http://utourpia.me/php/login_submit.php",
data: $('#loginForm').serialize(),
dataType: "json",
success: function(msg){
if(!(msg.status))
{
error(1,msg.txt);
}
else location.replace(msg.txt);
hideshow('loading',0);
}
});
}
This is my jQuery:
$('#loginForm').submit(function(e) {
login();
e.preventDefault();
});
This is my form:
<form id=loginForm method=post action="">
<label for=email class=email>Email:</label>
<input name=email type=text size=20 maxlength=40/>
<label for="password" class="password">Password:</label>
<input name="password" type="password" size="20" maxlength="40" />
<input class="login" type="submit" name="submit" value="Login" />
</form>
<div id="error"></div>
login_submit.php
<?php
require_once('../lib/connections/db.php');
include('../lib/functions/functions.php');
session_start();
$location_id = $_SESSION['location_id'];
$email = $_POST['email'];
$query = mysql_query('SELECT username FROM users WHERE email = "'.secureInput($email).'"') or die (mysql_error());
if(mysql_num_rows($query) == 1)
{
$row = mysql_fetch_assoc($query);
$username = $row['username'];
}
$returnURL1 = 'http://utourpia.me/php/places.php?id='.$location_id.'&username='.$username;
$returnURL2 = 'http://utourpia.me/php/myprofile.php?username='.$username;
$returnURL3 = 'http://utourpia.me';
$returnURL4 = 'http://utourpia.me/php/dreamtrip.php';
//For login
// we check if everything is filled in and perform checks
if(!$_POST['email'] || !$_POST['password'])
{
die(msg(0,"Email and / or password fields empty!"));
}
else
{
$res = login($_POST['email'],$_POST['password'],$username);
if ($res == 1){
die(msg(0,"Email and / or password incorrect!"));
}
if ($res == 2){
die(msg(0,"Sorry! Your account has been suspended!"));
}
if ($res == 3){
die(msg(0,"Sorry! Your account has not been activated. Please check your email's inbox or spam folder for a link to activate your account."));
}
if ($res == 99){
if ($_SESSION['login_submit']=="places.php")
{
echo(msg(1,$returnURL1));
}
else if ($_SESSION['login_submit']=="myprofile.php")
{
echo(msg(1,$returnURL2));
}
else if ($_SESSION['login_submit']=="home.php")
{
echo(msg(1,$returnURL3));
}
else if ($_SESSION['login_submit']=="dreamtrip.php")
{
echo(msg(1,$returnURL4));
}
}
}
function msg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
First thing you need to change in the form tag:
Wright only above code. because you have given the method and URL that's why it refresh the page.
Replace your jquery code $('#loginForm').submit(function(e) { this code replace by $('.login').click(function(e) {.
Why are you using the replace method in the ajax success function is gives the error. remove else part.
location object does't have the replace method. if you want to redirect to user on success then use the location.href="your link";.
Make these changes and then check.

validate a form before submit the data

I'm trying to validate a form before posting the data. Basically the form asks for a code. After the user clicks the submit button, the javascript below checks if the code only contains numbers and has a length of 6 digit. If the code is valid, then an ajax call is made calling the page verifybkcd.php, which runs a query and checks if the input code has associated with an account. Somehow the form is always submitted no matter what code I put.It seemed the ajax call has never been made because none of the alerts inside the call had been triggered. (I'm sure the path of the file verifybkcd.php is correct). Any ideas?
$(document).ready(function(){
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
$("#recovform").submit(function(e){
alert("alert on submit");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
alert("alert inside post");
if(data !=''){
alert("alert on code exists");
e.preventDefault();
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
alert("alert on valid");
$("#err-box").text("");
}
});
});
}
else{
$("#err-box").text("Please enter a valid book code above");
e.preventDefault();
}
});
The following is taken from the php file which has the form
<div id="container">
<?php
if($_SERVER['QUERY_STRING']==''){
?>
<div class="title"><h1>Forgot your password?</h1></div>
<div class="description"><p>To reset your password, enter the book code that you used when you registered your account.</p></div>
<form id="recovform" name="recovform" method="post" action="recovery.php?verifyuser" >
<div id="bkbox">
<label for="bkcode">Book Code:</label>
<input id="bkcode" name="bkcode" type="text" />
<input id="bksubmit" name="submit" type="submit" value="Submit"/>
</div>
<div id="err-box"></div>
</form>
<?php
}
else if($_SERVER['QUERY_STRING']=='verifyuser'){
?>
<div class="title"><h1>verify user</h1></div>
<div class="description"><p>emails below</p></div>
<?php
}
else{
echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=../err/404.php'>";
}
?>
</div>
BTW, I'm sure there's nothing wrong with verifybkcd.php file. I've tested it with different codes. It will only return a string when there're no accounts associated with the input code.
Problem solved. I replaced the name of the submit button with something else. Then it worked like magic. Also I've made a little change on the javascript as follows. It seems jquery won't submit the form if you name the submit button "submit". BTW I aslo changed the type of the submit button to "button" instead of "submit"
$(document).ready(function(){
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
if(data !=''){
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
$("#err-box").text("");
$("#recovform").trigger("submit");
}
});
}
else{
$("#err-box").text("Please enter a valid book code above");
}
});
});
First place if you dont want to submit the form then you should return false in the submit button click handler. Check if this below condition satisfied or not.
$(document).ready(function(){
//This is to prevent the form to be submitted
$("#recovform").submit(function(e){
e.preventDefault();
});
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
//$("#recovform").submit(function(e){
//alert("alert on submit");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
alert("alert inside post");
if(data !=''){
//alert("alert on code exists");
//e.preventDefault();
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
//alert("alert on valid");
$("#err-box").text("");
$("#recovform").unbind('submit').submit();
}
});
//});
}
else{
$("#err-box").text("Please enter a valid book code above");
return false;
}
});
in your example, you are missing:
})
at the end to close your $(document).ready in the javascript.

Categories