I have this chat room on my website, where the user types their message into a textbox and when they press enter (or the send button), jQuery takes the data from the textbox, disables the textbox, sends the data to the file send.php where it is then processed and put into the database, and then it should clear and undisable the textbox once it successfully runs through the PHP script. What is happening is the data is being submitted and it runs through the script (sends the data to the database successfully) but the jQuery is not clearing and undisabling the textbox.
Can someone explain to me what is wrong?
jQuery:
$('#formSend').on('submit', function (e) {
e.preventDefault();
var textArea = document.getElementById('styled');
if( textArea.value != "" ) {
var formData = $('form').serialize();
$('.expand').prop("disabled", true)
$.ajax({
type: 'post',
url: 'send.php',
data: formData,
dataType: "json",
success: function (formData) { //put data in parentheses when coming back
alert("Success");
$(".expand").val('');
$('.expand').prop("disabled", false);
if( formData["banned"] == 1 ) {
var rel = confirm("You have been banned.");
if (rel) {
location.reload();
}
else {
location.reload();
}
}
}
});
}
else {
alert("Your message must be longer than 1 (one) character.");
$('#styled').focus();
}
});
send.php:
<?php
include("../config.php");
session_start();
$msg = strip_tags( $_POST['msg'], '<b></b>' );
if( $msg == "" ) {
exit("There is no message.");
}
$username = $_SESSION['USER'];
$date = new DateTime();
$formattedDate = $date->format('Y-m-d H:i:s');
$stmt = $db->prepare("SELECT id, username FROM users WHERE username = :username");
$stmt->execute(array(":username" => $username));
$row = $stmt->fetch();
$userID = $row['id'];
$checkBanned = $db->prepare('SELECT banned FROM users WHERE username = :username');
$checkBanned->execute(array(
':username' => $username
));
$banned = $checkBanned->fetch();
if( $banned['banned'] == "yes" ) {
$return = array('banned' => 1);
echo json_encode($return);
exit;
}
try {
$stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)');
$stmt->execute(array(
':userID' => $userID,
':msg' => $msg,
':date' => $formattedDate
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Here is the form too, if needed.
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
I think the problem is you have not sent any responce if user is not banned and message is stored successfully.
If "success" is not being alerted then that is the problem.
Try this,
try { $stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)'); $stmt->execute(array( ':userID' => $userID, ':msg' => $msg, ':date' => $formattedDate ));
$output = "success";
} catch(PDOException $e) { $output = $e->getMessage(); }
finally{
echo json_encode($output);
}
I see you are refreshing the page afterwards, that could make the form to autocomplete to the previous value, try this:
<form autocomplete="off" action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
If you dont want to reload the page (which should actually happen, if you dont prevent the submit event from beeing triggered in the ajax callback by event.preventDefault()) you have to reset the form by doing something like $('#formSend').reset();
Furthermore, there is no disabled='false', you need to remove the attribute: $('.expand').removeAttr('disabled');.
By the way, it is good habit to save selector you need more than one time ;)
Have you tried something like:
$('.expand').removeAttr("disabled");
Related
I have a registration form using php, I'm checking the inputs with a validations and control the submitting form using ajax.
Everything works fine, except, after clicking submit button, Ajax loads the success result, in same registration form, and also not reload the page and redirect.
I want to reload and redirect register.php page to register.php?action=joined using Ajax form submit.
Before Ajax register.php have its own statement, if the registration succsessful ($_GET['action'] == 'joined')* its redirect and destroy the registration form and show success form.*
Please refer on the codes. Can someone help me how to figure this out.
registercontrol.php
<?php
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn = 'Your name must be alphabetical characters';
echo '<p>'.$infofn.'</p>';
}
}
// If form has been submitted process it
if(isset($_POST['submit']) && $_POST['submit'] == 'register')
{
// Create the activasion code
$activasion = md5(uniqid(rand(),true));
try
{
// Insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (fullname) VALUES (:fullname, :email, :active)');
$stmt->execute(array(
':fullname' => $fullname,
':email' => $email,
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
// Send email
$to = $_POST['email'];
$subject = "Verify Your Account";
$body = "<p>Thank you for registering on the demo site.</p>
<p>Hello ".$fullname.", Please click this link to activate your account: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
// Redirect to index page
header('Location: register.php?action=joined');
exit;
// Else catch the exception and show the error.
}
catch(PDOException $e)
{
$error[] = $e->getMessage();
}
}
?>
register.php and ajax validations
<script type="text/javascript">
$(document).ready(function() {
$("#fullname").keyup(function(event) {
event.preventDefault();
var fullname = $(this).val().trim();
if(fullname.length >= 1) {
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {fullname:fullname},
success: function(response) {
// Show response
$("#vfullname").html(response);
}
});
} else {
$("#vfullname").html("");
}
});
$('#submit').click(function(event) {
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result) {
$('.hidden').show();
$('#result').html(result);
})
});
});
</script>
<?php
// If action is joined show sucesss
if(isset($_GET['action']) && $_GET['action'] == 'joined')
{
echo '<div>
<p>Registration is successful, please check your email to activate your account.</p>
</div>';
}
else
{ ?>
<div>
<h1>Create an Account!</h1>
</div>
<form id="register-form" role="form" method="post"
action="registercontrol.php" autocomplete="off">
<input type="text" name="fullname" id="fullname" placeholder="Your name" value="" required>
<div id="vfullname"></div>
<input type="email" name="email" id="email" placeholder="Your Email" value="" required>
<input id="submit" type="submit" name="submit" value="Create Account">
<p class="hidden">Please check everything.</p>
<div id="result"></div>
</form>
<?php } ?>
Thank you.
Check the done block and perform your redirect with JavaScript:
$('#submit').click(function(event){
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result){
var url_to_redirect = "register.php?action=joined";
window.location.href = url_to_redirect;
})
});
I have a formA that posts and saves to the MYSQL DB
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <== first visable form ,Submitting the data into DB
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
I have a hidden form called PayForm that store some var with hidden input method and get the $input_amount as amount from FromA
It is noted that I haven't made the submit button .
This form is going to post to the EPayment Gateway .
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
...
</form>
Here is my idea workflow :
1)User press "Submit" button in FormA ==> info in FormA is going to store into DB .
2)JS is running . Force the PayForm to post automatically . Then, The user is directed to the Payment Gateway .
In short , the Submit button in FormA trigger both forms post
actions .
Here is my JS
<script type='text/javascript'>
var payFormDone = false;
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // THIS WILL TRIGGER THE NEXT CODE
$('#payForm').submit();
}
});
$("#payForm").submit(function(event) {
/* stop form from submitting normally */
//event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, {
merchantId: $('#merchantId').val(),
amount: $('#amount').val(),
orderRef: $('#orderRef').val(),
currCode: $('#currCode').val(),
mpsMode: $('#mpsMode').val(),
successUrl: $('#successUrl').val(),
failUrl: $('#failUrl').val(),
cancelUrl: $('#cancelUrl').val(),
payType: $('#payType').val(),
lang: $('#lang').val(),
payMethod: $('#payMethod').val(),
secureHash: $('#secureHash').val()
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#FormA').submit();
});
});
</script>
Now ,the idea is not working . It can only trigger second form action .
The first form action is not triggered .At least ,the data in FormA has not saved to the DB .
In short ,
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#payFormCcard').submit();
});
Is not working .I think !
update
This is how I post FormA to the server
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=big5");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Phone = $amount= $Purpose= $Ticket = "";
$CName_err = $Address_err = $Phone_err = $amount_err = $Purpose_err = $Ticket_err="";
// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
$input_CName = trim($_POST["CName"]);
if (empty($input_CName)) {
$CName_err = "Please enter a name.";
} elseif (!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z'-.\s ]+$/")))) {
$CName_err = 'Please enter a valid name.';
} else {
$CName = $input_CName;
}
......
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
Database::disconnect();
}
}
?>
you should not comment event.preventDefault(); from the second form. Currently what happens is it submitting it as default action which is post to url.
Inside posting.done() please remove/detach the onSubmit handler for FormA just before calling the $('#FormA').submit();
posting.done(function( data ) {
alert('success');
$('#FormA').off('submit');
$('#FormA').submit();
});
EDIT:
Okay, why not send the formA fields with AJAX inside its onSubmit handler and submit formB from the posting.done() handler ?
<script type='text/javascript'>
$('#formA').on('submit', function(e){
e.preventDefault();
/* Send the data using post with element id name and name2*/
var posting = $.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>", {
field1: $('#field1').val(),
.....
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
$('#FormB').submit();
}
});
</script>
The submit handler for FormA actually prevents the submission of the form. That's why data is not saved to db.
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // => HERE you are preventing the form from submitting
$('#payForm').submit();
}
});
Here you are in the submit handler for the form, but the call to preventDefault stops the submit for FormA and instead triggers the submit of payForm.
See https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Also instead of having that you trigger via javascript I'd probably send the first one normally. Then as response of the POST in the first form You might print a message to the user with something like: "You are being redirected to the payment gateway.. " and an hidden form with all the fields that is triggered automatically after x seconds. IMHO this approach is easier and more reliable.
So in the first html page I'll remove all your javascript code and leave only:
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
When the user clicks on the button he submits the data to the php page in POST. On the server the data is saved to DB and the server prints a message to the user and redirect to the payment gateway (via javascript this time). Something like:
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') {
.... save data to db
?>
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
<p>You are being redirected to the payment gateway. If the redirect takes too long</p>
<input type="submit" value"click here">
</form>
<script>
// submits the form after 5 seconds
setTimeout(function(){ $('#payForm').submit(); }, 5000);
</script>
<?php } // this ends the POST block ?>
If I correctly understand the question:
<script type='text/javascript'>
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
var $payForm = $("#payForm");
$.post( $payForm.attr('action'), $payForm.serialize(), function(data) {
alert('success');
// redirect to whereever you want
});
});
});
</script>
UPDATE:
case 2) redirecting to payment gateway:
<script type='text/javascript'>
$("#payForm").submit(function(e) {
alert('redirecting to payment gateway');
});
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
$("#payForm").submit();
});
});
</script>
NOTE: replace all your script with just this one, and check in browser if requests are made in the data posted - F12 (Developer tools) - Network tab.
Keep in mind that this code is written on a scratch so it may have some errors, but it shows the way.
I'm trying to post form data via AJAX.
When I remove the AJAX function and do a standard form POST method the data is being inserted into DB fine. When I console.log the serialized data of the form on submit it shows fine.
It's when the AJAX function is fired that the data seemingly disappears. The function fires as a success but no data is inserted and the formdata variable is seemingly empty. Can anyone shine any light on this?
Here's the code so far -
jQuery/AJAX -
$('#calendar-form').submit(function() {
var formdata = $(this).serialize();
console.log(formdata);
$.ajax({
url: "insert.php",
type: "POST",
data: formdata,
success: function() {
alert('success')
},
error: function() {
alert('ERROR');
}
});
return false;
});
HTML
<form id="calendar-form" action="" method="" accept-charset="utf-8">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type="hidden" name="site" id="site" value="<? echo $_SERVER['HTTP_HOST'] ?>">
<input class="submit" type="submit" name="submit" value="Submit">
</form>
PHP
try {
$bd = new PDO("mysql:host=localhost;dbname=;charset=utf8", "", "");
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Theres been an error while attempting to connect to the database';
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$site = $_POST['site'];
$sql = "INSERT INTO `users`(`name`, `email`, `site`) VALUES ('$name', '$email', '$site')";
try {
$query = $bd->prepare($sql);
$query->bindValue(':name', $name, PDO::PARAM_STR);
$query->bindValue(':email', $email, PDO::PARAM_STR);
$query->bindValue(':site', $site, PDO::PARAM_STR);
if($query->execute()){
echo "Success";
}else{
echo "Failure";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Note: I've removed DB details for this post but they're there in code.
Console
name=Benji&email=email%40email.com&site=localhost%3A8888 - scripts.min.js:9:117
Network
This is because jQuery's .serialize() does not include the submit button:
No submit button value is serialized since the form was not submitted using a button.
Check the console for the output of your console.log(formdata) - you'll see submit is missing. And since it is missing, the test you do on that value on the back end will fail:
if(isset($_POST['submit'])){
Exactly how to do solve this depends on what you're trying to do. If you just want to make sure the request was a POST (not a GET) you could use:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
If you want to do basic validation, you could explicitly check each of the expected values are present:
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['site'])) {
I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with
I use bellow html code to submit user email in my mailchimp account list using mailchimp API.
Form Code:
.....
<form id="signup-form" action="php/newsletter-subscribe.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<br>
<input type="submit" value="Go!" onclick="wating()" />
</form>
......
newsletter-subscribe PHP code:
require_once 'mailchimp/MailChimp.php';
use \DrewM\MailChimp\MailChimp;
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'xxxxxxxxxxxxxxxxxxxxx-xx'; // enter your MailChimp API Key
$mailchimp_list_id = 'xxxxxxxxxx'; // enter your MailChimp List ID
$subscriber_email = addslashes( trim( $_POST['email'] ) );
if( !isEmail($subscriber_email) ) {
echo '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = array();
$MailChimp = new MailChimp($mailchimp_api_key);
$result = $MailChimp->post("lists/$mailchimp_list_id/members", [
'email_address' => $subscriber_email,
'status' => 'subscribed',
]);
if($result == false) {
$array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>';
}
echo json_encode($array);
}
}
The problem is after i submit the form i get blank page without any error log and the email added to my mailchimp account without any error.
I try to change the echo javascript in line 22, 35 and 38 with another java script alert like alert("Text Here"); and it's work except i get the same thing blank page
How to solve this problem and echo the javascript alert in the same html form page without redirect to blank page?
First you are setting:
$array = array();
However later, you do:
if($result == false) {
$array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>';
}
echo json_encode($array);
In other words, you are changing array to a string.
Try to change the code to:
if($result == false) {
$array = array('<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>');
} else {
$array = array('<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>');
}
echo json_encode($array);
Also, I would avoid using <script type="text/javascript"> there and I would just return a proper json response. Then, you call this file with ajax (jquery), decode the json and show the alert.
Perhaps something like this will give you an idea:
http://labs.jonsuh.com/jquery-ajax-php-json/