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/
Related
In the username availability check I created two pages: register.php and registercontrol.php controlling it. I check the database connection its on work. Everything (all statements, insertin data into db) that was previously created on a single php page. But when ajax validates other inputs its duplicates the html content and shows the error inside of it instead of showing error messages in a just single html element.
So I seperated it into two pages but now ajax not shows any error and responds. Here is my work:
registercontrol.php
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username must be at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username already in use';
}
}
}
?>
register.php
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<form id="register-form" class="user" role="form" method="post" action="registercontrol.php" autocomplete="off">
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Username" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
</form>
we need to print the response in registercontrol.php so that we can get response in your register.php
Change your code as below
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
echo 'Your username must be at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
echo 'This username already in use';
}
}
}
?>
You need to return or echo something from registercontrol.php
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username must be at least 6 alphanumeric characters';
echo json_encode($infoun);
exit;
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username already in use';
echo json_encode($errorun);
exit;
}
echo $row[username];
exit;
}
}
?>
Form Submission Code
<form action="search.php" method="POST" id="form2">
<input type="text" name="Sr_no" required="true" placeholder="Enter Serial Number"><br>
<input type="submit" value="Check Status" name="ss">
</form>
My search.php
<?php
$connect=mysqli_connect("localhost","root", "" ,"mydatabase");
$Sr_no = $_POST["Sr_no"];
$status_check = "SELECT verified FROM r_concession_forms WHERE id = '$Sr_id' LIMIT 1";
$s_check = $connect->query($status_check);
$s_value = $row = $s_check->fetch_assoc();
if($s_value["verified"] == "0")
{
echo "<script>
alert('Not Issued/Verified');
window.location.href='index.php';
</script>" ;
}
elseif($s_value["verified"] == "1"){
echo "<script>
alert('Issued and Verified');
window.location.href='index.php';
</script>";
}
else{
echo "<script>
alert('No Such Form Exists');
window.location.href='index.php';
</script>";
}
?>
Output:
My Input first to check if that "id" exists in database
There is no alert box as expected, but the URL shows search.php, but no alert box displayed
After refreshing the page, the alert box starts working
The designing of page is by JavaScript
I think you are using a variable $Sr_id in the query which is not defined earlier. Also first check if the form is posted or not.
The code working fine when you refresh the page because, when you refresh the page there is no post data, so the query return empty value and it show "No such form exist". But when you post the page, the post value you given in query is wrong i guess.
<?php
if(!empty($_POST['ss'])) {
$connect=mysqli_connect("localhost","root", "" ,"mydatabase");
if(!empty($_POST['Sr_no'])) {
$Sr_no = $_POST["Sr_no"];
$status_check = 'select verified FROM r_concession_forms WHERE id = '.$Sr_no.' LIMIT 1';
$s_check = $connect->query($status_check);
$s_value = $row = $s_check->fetch_assoc();
if($s_value["verified"] == "0")
{
echo "<script>
alert('Not Issued/Verified');
window.location.href='index.php';
</script>" ;
}
elseif($s_value["verified"] == "1"){
echo "<script>
alert('Issued and Verified');
window.location.href='index.php';
</script>";
}
else{
echo "<script>
alert('No Such Form Exists');
window.location.href='index.php';
</script>";
}
}
}
?>
Also i personally don't prefer to use Script code inbetween PHP as you mentioned. Try to seperate the codes for better understanding.
I'm new to this and I have trouble understanding how all things works.
I have a php/html page and a login form in it. The login submit button executes a php file (let's say check_user.php) in which theoretically it checks the user and password i put in the form in a database. If it finds them I want the php file (check_user.php) to return to the main page the name of the user and his "class" (like supervisor, operator etc) in order to use them for further active change of main page content (like hide/show menus, enable/disbale elements etc). The problem is that the php returns with echo a text as I understand....How can I process this text to be stored in variables (one or more then one) to be usable in the main page? I understand how to pass variables to a php file, but i don't understand how to process the result of the php, except changing the content of an element in the mane page.
Maybe I need a callback function, I need to use JSON....
PS: I want to do this without $_SESSION
my code is here:
main page:
<div id="show2">
<?php
$userErr = $passErr = "";
$user = $pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"])) {
$userErr = "User name is required";
}
else {
$user = test_input($_POST["user"]);
if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
$userErr = "Only letters and white space allowed";
}
}
if (empty($_POST["pass"])) {
$passErr = "Password is required";
}
else {
$pass = test_input($_POST["pass"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>LOGIN INFORMATION:</h2>
<form method="post" action="check_user.php">
User: <input type="text" name="user" value="<?php echo $user;?>">
<span class="error">* <?php echo $userErr;?></span>
<br><br>
Password: <input type="password" name="pass" value="<?php echo $pass;?>">
<span class="error">* <?php echo $passErr;?></span>
<br><br>
<input type="submit" name="submit" value="Login">
</form>
</div>
check_user.php:
<?php
if ($_POST["user"] == "xxx" And $_POST["pass"] == "yyyy") {
$name = "John Legend"; /*here I assign value from database*/
$class = "Supervisor"; /*here I assign value from database*/
echo .... ; /*here I don't know what to echo. I want to echo $name and $class and use them as variables (not as text) in the main page*/
}
else {
echo "error";
}
?>
the implementation for database is not done, but the example still apply to any value I assign to the variables I want the php to echo
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");
I want to send an email. it gives me validation error 'fields are mandatory' when I click on email buttons and page get refreshed, even-though i entered correct email id. If i entered correct email id then also it gives error.
I don't know where i am going wrong. Can anybody tell me. Here is my php code:
function validation1()
{
document.getElementById("emailid").innerHTML="";
var emailpattern=/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
if(document.form1.email.value=="")
{
document.getElementById("emailid").innerHTML="fields are mandetory";
document.form1.email.focus();
return false;
}
else if(!emailpattern.test(document.form1.email.value))
{
document.getElementById("emailid").innerHTML="enter valid id";
document.form1.email.focus();
return false;
}
return true;
}
<?php include 'send-email.php';?>
<form name="form1" method="post">
<input type="submit" name="email" value="email" onclick="return validation1()" />
<input type="text" size="50" name="email" id="email" placeholder="*************" />
<span id="emailid"></span>
</form>
send-email.php code
<?php include 'connection.php'; ?>
<?php
if(isset($_POST['submit'])) {
#$email=$_POST["email"];
$email=strip_tags($_POST["email"]);
$email=mysqli_real_escape_string($con,trim($email));
$to="sa#vs.com";
$to=mysqli_real_escape_string($con,trim($to));
$headers="From:".$email;
$message="Interested in VAPT";
$subject="email id";
if(mail($to,$subject,$message,$headers))
{
$email="'".$email."'";
$sql="insert into email_to_admin values($email)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
mysqli_close($con);
}
?>
You have no if() statement to control when the mail is sent. As soon as the page load, you instantly mail. Use
if(isset($_POST['email'])) {}
if(isset($_POST["email"]) && isset($_POST["email"] !="" )
{
//send the email
}
Personally I would recommend also placing an antispam captcha, this way it will make sure that the new rendom value is not the same
And since you have another step which helps you, you may also mark the email address plus some other value like subject unique in the email_to_admin MySQL Table, if a record is inserted, you carry on
$sql="insert into email_to_admin values($email , $subject)";
.....................
$num = #mysql_affected_rows();
if($num > 0)
{
//semd the email
}
Try below for mail :-
if($_POST["email"]){ // Add this if condition so that your mail will be send when button gets clicked.
$to="sa#vs.com";
$to=mysqli_real_escape_string($con,trim($to));
$headers="From:".$email;
$message="Interested in VAPT";
$subject="email id";
if(mail($to,$subject,$message,$headers))
{
$email="'".$email."'";
$sql="insert into email_to_admin values($email)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
}