Preventing form from refreshing page Javascript - php

im quite bad at javascript, and i am trying to make a AJAX call, but i get my value from a form feild, and it just refreshes the page, cant even observe if the AJAX call is succesfull.
Here is my HTML:
<form class="form-horizontal" id="subscribe-form" name="subscribe-form" onSubmit="return subscribe();">
<fieldset>
<p>
Subscribe
</p>
<div class="input-prepend input-append">
<input name="subscribwEmail" class="span2" id="InputEmail" type="email" placeholder="Email">
<input type="submit" class="btn btn-inverse" />
</div>
</fieldset>
</form>
JS:
function subscribe() {
var emailForm = $('#subscribwEmail').val();
$('#subscribe-form').hide(); // hide email form
$('#subscribeDiv').prepend('<img id="process" src="http://www.mydomain.com/assets/img/process.gif" />')
$.ajax({
type: "POST",
url: "../../actions/ajax-subscribe.php",
data: {
email: emailForm
},
dataType: "json",
success: function (data) {
if (data[0] == 1) { // test if response was 1 or 2
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>Thank you for subscribing!</p>');
} else {
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>There was an error subscribing the email.</p>');
}
}
})
};
ajax-subscribe.php
<?php
include ('phpfunctions.php');
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('ERROR WITH SQL CONNECTION CONTACT ADMIN');
$email = cleanString($con, $email);
$query = "INSERT INTO `subscribers` (`email`, `ip`) VALUES ('$email', '$ip');";
if ($result = mysqli_query($con, $query)) {
echo json_encode(1); // all ok inserted
} else {
echo json_encode(0); // failed
}
?>

You do not cancel the click event so the form submits.
Add return false; to the end of your subscribe method.

You have to return false from your subscribe method
Also you can validate the email, if it is invalid, you can stop sending subscribe by return false
You can also disable your submit button. (formObj comes with subscribe parameter)
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
But you have to enable it if something goes wrong.

Related

Checking and submitting form via Ajax in boostrap modal

I have a login form in boostrap's modal window
<form method="post" id="loginForm" action="index.php">
<label for="email">Email:</label>
<input class="form-control" type="text" name="email" value="" id="emailLogin"/><br/>
<label for="password">Password:</label>
<input class="form-control" type="password" name="password" value="" id="passwordLogin"/><br/>
<div id="loginAlert" class="alert alert-danger" role="alert">Email or password incorrect</div> <!-- Hidden by default -->
<button type="submit" name="login" class="btn btn-primary" id="loginButton">Login</button>
<script src="checkLoginForm.js"></script></form>
I would like to check this form (if email and password are correct) before submitting it. If the function, which checks the email and password returns 1, there is something incorrect. Form should not submit in this case and it should just make the alert visible.
If everything is correct, it should submit.
Thing is: I can prevent the form from submitting, if the the email and password are incorrect, but I can't submit it, if they are correct. Here is the code from checkLoginForm.js
$(document).ready(function() {
$("#loginForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'include/ajax.php?action=checkLogin',
data: {
email: $("#emailLogin").val(),
password: $("#passwordLogin").val(),
},
success: function(result) {
console.log(result);
if(result == 0) {
} else {
$("#loginAlert").css({"display": "block"});
}
}
});
});
});
I have no idea what to do, when the result == 0. If I do $("loginForm").submit();, that does not submit the form (else part does work).
Thank you for your replies.
I would advice you to use a simple $.post, it's a shorthand way of using $.ajax for POST requests. Just check if the values provided are correct in your php file, if they are correct process that data and return true or redirect the user to another page else return false.
$(document).ready(function() {
$("#loginButton").on('click', function (e){
e.preventDefault();
var email = $("#emailLogin").val();
var passwd = $("#passwordLogin").val();
$.post('include/ajax.php?action=checkLogin', {email: email, password: passwd}, function (data) {
var res = $.parseJSON(data);
if (res.result == true) {
//you can redirect the or display a message to the user.
//redirect the user to another page
//$("#loginAlert").css({"display": "block"}).html("login successful");
}else {
$("#loginAlert").css({"display": "block"});
}
});
});
});
Then in your php file
if (isset($_GET['action']) && $_GET['action'] == 'checkLogin') {
$passwd = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
//validate inputs here
//get data from db
//then compare values
//if values match return true
//$db_mail and $db_passwd are from the db.
if ($email == $db_mail && $passwd == $db_passwd) {
//if the provided information is correct
//process it here, login the user.
//redirect if necessary.
// or return results to JS
echo json_encode(['result' => true]);
} else {
//if the information is wrong return false to JS
//and alert the user
echo json_encode(['result' => false]);
}
}

Pop-up message after submitting a form with php

I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

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.

Inserting values into database with php, ajax and jQuery

I'm struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...
sign_up.php
<?php
include 'connect.php';
include 'header.php';
echo '<h2>Register</h2>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<br/>';
echo '
<div class="container">
<form id="submit" method="post" action="">
<fieldset>
<legend> Enter Information </legend>
<br/>
<label for="user_name">Your username: </label>
<br/>
<input id="user_name" class="text" name="user_name" size="20" type="text">
<br/>
<br/>
<label for="user_pass">Your password: </label>
<br/>
<input id="user_pass" class="text" name="user_pass" size="20" type="password">
<br/>
<br/>
<label for="user_pass_check">Confirm password: </label>
<br/>
<input id="user_pass_check" class="text" name="user_pass_check" size="20" type="password">
<br/>
<br/>
<label for="user_email">Email: </label>
<br/>
<input id="user_email" class="text" name="user_email" size="20" type="email">
<br/>
<br/>
<button class="button positive" type="submit"> <img src="like.png" alt=""> Register </button>
</fieldset>
</form>
<div class="success" style="display: none;"> You are now a registered user!</div>
</div>';
}
else {
$errors = array();
//Checks the errors
if(isset($_POST['user_name']) == NULL)
{
//if the user name is larger than 30 characters
$errors[] = 'Please enter your username.';
}
//Checks the password
if(isset($_POST['user_pass']) == NULL)
{
$errors[] = 'Please enter your password.';
}
else
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
if(!empty($errors)) //Checks for empty fields
{
echo 'Please check that all the fields are filled in.<br /><br />';
echo '<ul>';
foreach($errors as $key => $value) //walk through the array so all the errors get displayed
{
echo '<li>' . $value . '</li>'; //this generates a list with errors
}
echo '</ul>';
}
}
?>
in my header.php (which I include in every page) I included addMembers.js
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var user_name = $('#user_name').val();
var user_email = $('#user_email').val();
var user_pass= $('#user_pass').val();
//$user_name = $('#user_name').val();
//$user_email = $('#user_email').val();
//$password = $('#password').val();
alert(user_name);
$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name +"&user_email="+ user_email +"$user_pass=" + user_pass,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
//alert("ji");
return false;
});
});
and then my ajax.php that gets the data and must insert it into the database but it doesn't! :(
<?php
include 'connect.php';
include 'header.php';
// CLIENT INFORMATION
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
mysql_query("INSERT INTO
users(`user_name`, `user_pass`, `user_email` , `user_date` , `user_level`)
VALUES('$user_name', '$user_pass', '$user_email', NOW() , 0)" OR trigger_error(mysql_error()));
?>
PLEASE help...
Thanks a lot!
Joe
There are a bit of things not right here:
html:
Give a type="submit" to your button:
<button type="submit" class="...>...</button>
jQuery:
Don't use attr() to get a form value, but use val(). Also, note how you built your query string. You might also want to use serialize(), which shortens your code a bit:
$("form#submit").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
success: function(){
$(this).hide();
$('div.success').fadeIn();
}
});
return false;
});
PHP:
You didn't show your ajax.php, what is it doing?
Why do you make a check in sign_up.php, if you're calling ajax?
Also, this piece of code:
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'That user name is allready taken.';
}
is misleading, ctype_alnum() does check if username has only alphabetical characters or numbers, what's this thing about a username being already taken?
Mysql:
you dint' provide your INSERT query, so noone can tell if that's failing too or not
UPDATE:
Your query has more columns than values.
Also, what is htmlspecialchars() good to here? to avoid SQL injections you need to use mysql_real_escape_string(). Escaping html before entering the database is useless
Make sure you have an open connection when calling mysql_real_escape_string().
Should be:
mysql_query("INSERT INTO users
(`user_name`,`user_pass`,`user_email`,`user_date`,`user_level`)
VALUES ('$user_name','$password','$user_email','missingvalue','missingvalue')"
) OR trigger_error(mysql_error());
$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name + "&user_email=" + user_email + "&password=" + password,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
show the ajax.php, besides earlyer comments like : ' $('#user_name').val();','ampersant before user_email'... seems ok...

Categories