This is a mailing list script. It works by itself without jquery but I am trying to adapt it to work with ajax. However, without success. When the $.sql part is commented out it returns the variables in the url string successfully. However, when I uncomment that part of the js file and introduce the PHP into things it simply refreshes the page with the email address still in the input box. By itself, the PHP works so I'm at a loss as to where I'm going wrong. Here's what I have... any help would be appreciated.
Form :
<form name="email_list" action="" id="maillist_form">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery :
$(function() {
$('#maillist_form').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $("#maillist_form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});
});
PHP :
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["sub"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add2.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
I won't put the include code in here because I'm assuming it is correct - unless the introduction of the jquery means this needs to be adapted as well.
Your AJAX is not catching back the result:
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block').html(response); //just an example method.
//Are you sure the selector is the same?
//Can also be $(this).html(response);
}
});
And as noted by gdoron, there's no "name" variable. Maybe you meant "email" and "sub", respectively?
PHP response, also, isn't echoed back. Just put:
echo $display_block;
You don't echo an data from the server, not trying to get data in the success callback, and the fadeIn callback just have a selector,.
You check for the wrong variable:
var email = $("input#email").val();
if (name == "") { // Didn't you mean email?
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") { // Didn't you mean sub?
$("input#sub").focus();
return false;
}
How can it work!?
Related
Updated:
Thanks for reading - My login form calls on login.php to check whether the user has entered a registered email address or not. If the address is registered, it echoes back "redirect", if it is not registered, it echoes "Email not registered". My current code only redirects to mydomain.com/# since the form action is set to #, because I'm using the ajax to submit the form.
How do I:
Redirect the user to page private.php if the php has echoed "redirect" - otherwise how do I display "Email not registered" within the form, if it echoes "Email not registered"? My login form contains a div to display the error if necessary.
ajax:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.post('login/login.php', {email: $('#email').val(), loginsubmit: 'yes'}, function(data)
{
if (data === "redirect")
{
window.location = "http://www.gathercat.com/login/private.php";
}
else {
$("#formResponse").html(data).fadeIn('100');
$('#email').val('');
}
, 'text');
return false;
}
});
});
</script>
PHP:
...
if($login_ok)
{
echo 'redirect';
}
else
{
echo 'That email address is not registered';
}
...
login form:
...
<form id="loginform" name="loginform" method="POST" class="login" action="#">
<input name="email" id="email" type="email" class="feedback-input" placeholder="My Email" required/>
<div id="formResponse" style="display: none;"></div>
<button type="submit" name="loginsubmit" class="loginbutton">Login</button>
...
Full PHP
<?php
$emailaddress = $_POST["email"];
?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retrieves the user's information from the database using
// their email.
$query = "
SELECT
email
FROM users
WHERE
email = :email
";
// The parameter values
$query_params = array(
':email' => $emailaddress
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query");
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the email
// they entered is not registered.
$row = $stmt->fetch();
if($row) {
$login_ok = true;
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
echo 'redirect';
}
else
{
// Tell the user they failed
echo 'That email address is not registered';
}
}
?>
I've rewritten the code for you as it likes like you had quite a few problems.
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: { email: $('#email').val(), loginsubmit: 'yes' },
success:function(response){
if(response == "redirect"){
window.location.replace("http://www.gathercat.com/login/private.php");
}
else{
$("#formResponse").html(response).fadeIn('100');
$('#email').val('');
}
}
})
});
});
This is untested but please let me know if you have any questions about how it works.
if ( formResponse === "redirect" ) ...
what is formResponse variable?
it should be data
if ( data == "redirect" ) ...
UPDATE:
may be this will help
$(document).ready(function () {
$("#loginform").submit(function (e) {
e.preventDefault();
$.post('login/login.php', {
email: $('#email').val(),
loginsubmit: 'yes'
}, function (data) {
if (data === "redirect") {
window.location = "http://www.gathercat.com/login/private.php";
} else {
$("#formResponse").html(data).fadeIn('100');
$('#email').val('');
}}, 'text');
// this does not matter
return false;
}
// add line below
return false;
});
});
Ok, I solved it!
I changed my ajax to:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
success:function(result){
if(result === "redirect"){
// window.location.replace("login/private.php");
window.location.replace("http://www.gathercat.com/login/private.php");
//alert(result);
}
else{
$("#formResponse").html(result).fadeIn('100');
$('#emailaddy').val('');
}
}
})
});
});
</script>
and removed some commented-out HTML within the bottom of my php file which was disrupting the "result" variable's content. Everything runs perfectly now. I added this answer so people could see the full code easily, but I'm giving massive credit to paddyfields for their help, thank you again. You too Lee, appreciate the support. Take care
I'm trying to get an error that says that the email exists already and I'm trying to use jquery. I'm using ajax and it does work, because when I use firebug and I go to the console it says that the email address exists but I would like that to appear on the page.
index.php
<div class="register-newsletter">
<form id="myForm">
<input type="email" name="email" id="email" value="enter email address" required>
<input type="image" value="SUBMIT" id="sub" src="images/register.jpg">
</form>
<a class="newsletter" href="javascript:void(0);">Add to e-mailing list</a>
This is my jquery
$("#email").click(function(){
if($.trim($(this).val() ) == "enter email address"){
$(this).val("");
}
})
$("#email").blur(function(){
if($.trim($(this).val() ) == ""){
$(this).val("enter email address");
}
})
$("#sub").click(function () {
var email = $.trim($("#email").val());
if(email == "" || !isValidEmailAddress(email)){
alert('enter valid email');
return false;
}
var ajaxid = ajax("ajax/userInfo.php","email="+encodeURIComponent(email));
$("#result").html($.trim(ajaxid));
});
$("#myForm").submit(function () {
return false;
});
function clearInput() {
$("#myForm :input").val('');
}
$('p').hide();
$('#myForm').hide();
$(".newsletter").click(function(){
$(".newsletter").hide();
$('#myForm').show();
});
$('#myForm').submit(function(){
$('#myForm').hide();
$('p').show();
});
and this is my userInfo.php
<?php
include("../config.php");
global $_NEWSLETTER_CUSTOMERS_TABLE;
$email = $_POST['email'];
//$email = html_entity_decode(str_replace("'", "\'", $_POST["email"]));
$query = mysql_query("SELECT * FROM $_NEWSLETTER_CUSTOMERS_TABLE WHERE `email` = '".$email."'");
if(mysql_num_rows($query) >0){
echo '<span class="exists">Email address arleady exists</span>';
} else {
if(mysql_query("INSERT INTO $_NEWSLETTER_CUSTOMERS_TABLE(email) VALUES('$email')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
}
You are attempting to append the data incorrectly. jQuery's ajax() method takes a function that will be called upon the success of the request, called success. At the moment, you are trying to append ajaxid, (which contains ajax()s return value, not the result of the request) to #result.
var ajaxid = ajax("ajax/userInfo.php","email="+encodeURIComponent(email));
$("#result").html($.trim(ajaxid));
Should be more like:
var ajaxid = ajax("ajax/userInfo.php", {
data:"email="+encodeURIComponent(email),
success:function(d){
$("#result").html($.trim(d));
}
});
Use jQuery.post() inside your click handler:
$.post('ajax/userInfo.php', { email: email }, function(data) {
alert(data.message);
}, 'json');
And in your PHP file instead of echo use:
$response = array();
$response['message'] = mysql_query("...") ? 'success' : 'fail';
return json_encode($response);
You must return the value, eg JSON
Your JS
$("#sub").click(function () {
$.ajax({
url : "ajax/userInfo.php",
dataType : "json",
error : function(request, error) {
alert("Erreur : responseText: "+request.responseText);
},
success : function(data) {
alert(data.email_exist);
$("#result").html(data.email_exist);
}
});
});
AND your PHP
if(mysql_num_rows($query) >0){
$result = array(
'email_exist' => 'Email address arleady exists'
);
}
json_encode($result);
I have a form with 5 fields.
Name
Last Name
Date of Birth
Occupation
Place of Birth
When user fills name and last name, I want the rest of the form to be filled from database without refreshing the page or user doing anything.
I am using php and jquery.
Here is my html page:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="name" id="name">
<input type="text" name="lastname" id="lastname">
<input type="text" name="occupation" id="occupation">
<input type="text" name="date_of_birth" id="date_of_birth">
<input type="text" name="place_of_birth" id="place_of_birth">
<script type="text/javascript">
$('#lastname').blur(function ()
{
var name = $("#name").val();
var lastname = $("#lastname").val();
$.ajax({
url: "get.php",
type: "POST",
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
if (data == "Error")
{
alert("error-1"+data);
}
else
{
var fields = data.split(",");
if (fields.length < 3)
{
alert("error-2"+data);
}
else
{
$("#occupation").val(fields[0]);
$("#date_of_birth").val(fields[1]);
$("#place_of_birth").val(fields[2]);
}
}
},
error: function(xhr, status, error)
{
alert("error-3"+data);
}
});
});
</script>
</body>
</html>
Here is the php page:
<?php
$name= $_REQUEST['name'];
$lastname= $_REQUEST['lastname'];
if($name == "mike" && $lastname = "brown")
{
echo "cook,1980-10-10,NYC";
}
?>
It works now.
-- Edit #1
Maybe this example can help you to understand how to use it:
$.ajax({
url: "phppage.php",
type: "POST", // Or get as you like
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
// As i said, here in "data" you have what the server returned
// You can return the last field delimited with a , and do something like:
if (data == "Error")
{
// If something went wrong in your Database or invalid "name" or "last name"
// You can return "Error" in the PHP page so the Javascript know something is wrong
// and handle this error
}
else
{
var fields = data.split(",");
if (fields.length < 3) {
// As above.
// Something went wrong or invalid response
}
else
{
// In fields array you have what server said.
// Here you can reload the page, change page do what you want
}
}
},
error: function(xhr, status, error)
{
// Error here
}
});
It pass name and lastname to the server and wait for a response like:
field1,field2,field3
The PHP page should be something like..
<?php
// Connect to the server
// Send query to the server
if ($isEverythingOK) {
echo $field1 . "," . $field2 . "," . $field3;
}
else {
echo "Error";
}
?>
Ajax - jQuery Ajax + PHP page
A php page where you pass the 5 fields, add it in the database and return something like "OK" if everything is OK or an error if something went wrong.
Example
$.ajax({
url : "URL to PHP page",
success : function (data) {
if (data === "OK") { /* all ok, here you can update the page to show the new field */ alert("OK"); }
else { /* Error */ alert("Error"); }
},
error : function (xhr, status, error) {
// Request error
alert("Error");
}
});
I have some validation code something like this -
if ($('#address').val()) {
if ($('#address').val().length > 60 || $('#address').val().length < 5) {
errorMessage += "Length of Your Address must be between 5 and 60.\n";
valid = false;
} else {
var rege = /^[a-zA-Z]([0-9a-z_\s])+$/i;
if(!rege.test($('#address').val())){
errorMessage += "Please enter Valid Address.\n";
valid = false;
} else {
var address = $('#address').val();
//alert ('My address is : ' + address);
}
}
} else {
errorMessage += "please enter your address\n";
valid = false;
}
My problem is how I get this value to php. My value have here - var address = $('#address').val();
I need to check this value again in PHP and need to echo the value on the same page.
I use it something like this -
if( !valid && errorMessage.length > 0){
alert(errorMessage);
} else {
$.ajax({
type: "POST", // HTTP method POST or GET
url: "demo2.php", //Where to make Ajax calls
data: {
myname: name,
myaddress: address,
myemail: email
}
});
}
demo2.php page is the same page which my form have.
Above of my page I tried to print $_POST array but nothing display there.
echo '<pre>', print_r( $_POST).'</pre>';
Hope someone will help me.
Thank you.
First put a check in demo2.php for if POST is set
if( isset($_POST['myaddress']) ) {
// your echo statement here
}
Then you just need to add some code to the jquery handle the response.
if( !valid && errorMessage.length > 0){
alert(errorMessage);
} else {
$.ajax({
type: "POST", // HTTP method POST or GET
url: "demo2.php", //Where to make Ajax calls
data: {
myname: name,
myaddress: address,
myemail: email
}
}).done(function(response) {
$('#address-display-div').html(response);
});
}
replacing #address-display-div with whatever selector you're going to display the address in.
Request page:
var request =$.ajax({
type: "POST",
url: "demo2.php",
data: {myname: name,myaddress: address,myemail: email}
dataType: "json",
success: function (a) {
alert(a[0]);
}
});
request.fail(function(jqXHR, textStatus){alert('Ajax Error: '+ textStatus);});
And in your php file:
<?php
if(isset($_POST['myname']) && isset($_POST['myaddress']) && isset($_POST['myemail'])){
[do your stuff]
echo json_encode(array(0=>'<pre>'.print_r( $_POST,true).'</pre>'));
}
else
echo json_encode(array(0=>'Missed Variable'));
exit();
?>
Otherwise can you also post your php page?
I have a form in which i want to do the validations. But there is a field which i want to validate writing a query. I dont want the form to postback because after postback all the values filled in the form are lost. Is there any way i can write a query without postback or if i have to postback how to retain the values ? Please help
If you use AJAX (jQuery), you can post an XML Request without refreshing the browser, if this is what you need.
For this, just create a form with some textfields and a submit button, give everything an ID and add an click-Listener for the button:
$('#submit-button').click(function() {
var name = $('#username').val();
$.ajax({
type: 'POST',
url: 'php_file_to_execute.php',
data: {username: name},
success: function(data) {
if(data == "1") {
document.write("Success");
} else {
document.write("Something went wrong");
}
}
});
});
If the user clicks on the button with the "submit-button"-ID, this function is called. Then you send the value of the textfield using POST to the php_file_to_execute.php. Inside this .php-File, you can validate the username and output theresult:
if($_POST['username'] != "Neha Raje") {
echo "0";
} else {
echo "1";
}
I hope that I could help you! :)
You might want to rephrase what you wrote, its a bit unclear. FYI I do it like this;
<form method="post">
Text 1: <input type="text" name="form[text1]" value="<?=$form["text1"]?>" size="5" /><br />
Text 2: <input type="text" name="form[text2]" value="<?=$form["text2"]?>" size="5" /><br />
<input type="submit" name="submit" value="Post Data" />
</form>
And when I am processing the data, it's like this;
<?php
if ($_POST["submit"]) {
$i = $_POST["form"];
if ($i["text1"] or ..... ) { $error = "Something is wrong."; }
if ($i["text2"] and ..... ) { $error = "Maybe right."; }
if (!$error) {
/*
* We should do something here, but if you don't want to return to the same
* form, you should definitely post a header() or something like that here.
*/
header ("Location: /"); exit;
}
//
}
if (!$_POST["form"] and !$_GET["id"]) {
} else {
$form = $_POST["form"];
}
?>
By this method, the values are not lost unless you set them to get lost.
Use jQuery's $.post() method as:
$('#my_submit_button').click(function(event){
event.preventDefault();
var username = $('#username').val();
$.post('validate.php', {username: username, my_submit_button: 1}, function(response){
console.log(response); //response contain either "true" or "false" bool value
});
});
In validate.php get the username from your form asynchronously as like this:
if(isset($_POST['my_submit_button']) && $_POST['my_submit_button'] == 1 && isset($_POST['username']) && $_POST['username'] != "") {
// now here you can check your validations with $_POST['username']
// after checking validations, return or echo appropriate boolean value like:
// if(some-condition) echo true;
// else echo false;
}
Note: Please consider knowing security-related vulnerabilities and other issues before using AJAX for executing database-altering scripts.