mercredi 8 avril 2015

Return success/failure variable with ajax from php script

Vote count:


I'm a really new coder and struggling with a task I'm now working on and trying out for days.

I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:

I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:

<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>

<span id="result"></span>

Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?


if ($_POST['email']) {

if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";

After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).

The insertion into the DB works fine, also the validation.

But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.

This is the jquery script:

$("#sub").submit(function (){
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
error: function(error) {

I try to display the value of the error and message variable in the php script within the #result span.

Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.

Thank you a lot in advance.

asked 1 min ago

Return success/failure variable with ajax from php script

Aucun commentaire:

Enregistrer un commentaire