what does $('form#'+id) represent in the following js code? - javascript

In the following code, there is such javascript function sendPushNotification(id) in which there is such line var data = $('form#'+id).serialize() , what does $('form#'+id) mean? there is no form below that has the id "form#"+id ...
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>

It selects a form element with an id of the value of the variable id. Assuming it is valid in that there are no duplicate IDs and id will never be the id of something not a form, it can also be written as simply $('#' + id).

Related

Send Email and Insert from the same form

I have a page where I have this form that sends the data in an email.
I want that when I click the submit button, other than sending the data through email, I want to send the data in a page where I have an INSERT script.
Here's the code of my page:
<!doctype html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';
session_start();
if (!empty($_SESSION['_contact_form_error'])) {
$error = $_SESSION['_contact_form_error'];
unset($_SESSION['_contact_form_error']);
}
if (!empty($_SESSION['_contact_form_success'])) {
$success = true;
unset($_SESSION['_contact_form_success']);
}
?>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Appointmenta</title>
<!-- reCAPTCHA Javascript -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card mt-5">
<div class="card-body">
<h1 class="card-title">
Add an Appointment
</h1>
<?php
if (!empty($success)) {
?>
<div class="alert alert-success">Message sent successfully.</div>
<?php
}
?>
<?php
if (!empty($error)) {
?>
<div class="alert alert-danger"><?= $error ?></div>
<?php
}
?>
<?php $Field1= $_POST['Field1']; ?>
<?php $Field2= $_POST['Field2']; ?>
<?php $Field3= $_POST['Field3']; ?>
<?php $Field4= $_POST['Field4']; ?>
<?php $Field5= $_POST['Field5']; ?>
<?php $Field6= $_POST['Field6']; ?>
<?php $Field7= $_POST['Field7']; ?>
<?php $Field8= $_POST['Field8']; ?>
<?php $Field9= $_POST['Field9']; ?>
<form id="target" method="post">
<div class="form-group">
<label for="name">Field 1</label>
<input type="text" name="Field1" id="Field1" class="form-control"
value="<?php echo $Field1?>">
</div>
<div class="form-group">
<label for="subject">Field 2</label>
<input type="text" name="Field2" id="Field2" class="form-control"
value="<?php echo $Field2?>">
</div>
<div class="form-group">
<label for="email">Field 3</label>
<input type="text" name="Field3" id="Field3" class="form-control"
value="<?php echo $Field3?>">
</div>
<div class="form-group">
<label for="subject">Field 4</label>
<input type="text" name="Field4" id="Field4" class="form-control"
value="<?php echo $Field4?>">
</div>
<div class="form-group">
<label for="subject">Field 5</label>
<input type="text" name="Field5" id="Field5" class="form-control"
value="<?php echo $Field5?>">
</div>
<div class="form-group">
<label for="subject">Field 6</label>
<input type="text" name="Field6" id="Field6" class="form-control"
value="<?php echo $Field6?>">
</div>
<div class="form-group">
<label for="subject">Field 7</label>
<input type="text" name="Field7" id="Field7" class="form-control"
value="<?php echo $Field7?>">
</div>
<div class="form-group">
<label for="subject">Field 8</label>
<input type="text" name="Field8" id="Field8" class="form-control"
value="<?php echo $Field8?>">
</div>
<div class="form-group">
<label for="message">Field 9</label>
<input type="text" name="Field9" id="Field9" class="form-control"
value="<?php echo $Field9?>">
</div>
<div class="form-group text-center">
<div align="center" class="g-recaptcha" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>"></div>
</div>
<button "name="submit" class="btn btn-primary btn-block"> Send Email</button>
</form>
<form action="../list.php">
<p><br></p>
<button class="btn btn-primary btn-block">Return home.</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="Javascript">
<!--
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
data: $( this ).serialize()
});
});
-->
</script>
When I click on 'Send Email' nothing happens.
**I want to click 'Send Email' and see the message 'Message sent successfully'. At the same time I want that same data to be sent to appointment.php, which inserts the data into a table. I'd prefer that 'appointment.php' doesn't even open, I want to stay on index.php when I click 'Send Email'**
Code of submit.php
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';
session_start();
// Basic check to make sure the form was submitted.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "The form must be submitted with POST data.";
exit();
}
require "appointment.php";
// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
echo "Please complete the CAPTCHA.";
}
$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
$error = $errors[0];
$recaptchaErrorMapping = [
'missing-input-secret' => 'No reCAPTCHA secret key was submitted.',
'invalid-input-secret' => 'The submitted reCAPTCHA secret key was invalid.',
'missing-input-response' => 'No reCAPTCHA response was submitted.',
'invalid-input-response' => 'The submitted reCAPTCHA response was invalid.',
'bad-request' => 'An unknown error occurred while trying to validate your response.',
'timeout-or-duplicate' => 'The request is no longer valid. Please try again.',
];
$errorMessage = $recaptchaErrorMapping[$error];
echo "Please retry the CAPTCHA: ".$errorMessage;
}
// Everything seems OK, time to send the email.
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = CONTACTFORM_PHPMAILER_DEBUG_LEVEL;
$mail->isSMTP();
$mail->Host = CONTACTFORM_SMTP_HOSTNAME;
$mail->SMTPAuth = true;
$mail->Username = CONTACTFORM_SMTP_USERNAME;
$mail->Password = CONTACTFORM_SMTP_PASSWORD;
$mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
$mail->Port = CONTACTFORM_SMTP_PORT;
// Recipients
$mail->setFrom(CONTACTFORM_FROM_ADDRESS, CONTACTFORM_FROM_NAME);
//$mail->addAddress(CONTACTFORM_TO_ADDRESS, CONTACTFORM_TO_NAME);
//$mail->addAddress(CONTACTFORM2_TO_ADDRESS, CONTACTFORM2_TO_NAME);
$mail->addAddress(CONTACTFORM3_TO_ADDRESS, CONTACTFORM3_TO_NAME);
//$mail->addAddress(CONTACTFORM4_TO_ADDRESS, CONTACTFORM4_TO_NAME);
//$mail->addReplyTo("marketing#lgp-italia.it");
// Content
$mail->Subject = "Appointment at ".$_POST['Field1'];
$mail->Body = <<<EOT
Appointment at: {$_POST['Field1']}, {$_POST['Field2']}
{$_POST['Field3']}
{$_POST['Field4']}
{$_POST['Field5']}
{$_POST['Field6']}
{$_POST['Field7']}
EOT;
$mail->send();
} catch (Exception $e) {
echo "An error occurred while trying to send your message: ". $mail->ErrorInfo;
}
Code of appointment.php
<?php
if (isset($_POST['submit'])) {
require "../../../security/config.php";
require "../../../security/common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$new_call = array(
"Field1" => $_POST['Field1'],
[...]
);
echo var_dump("1");
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"db.appointments",
implode(", ", array_keys($new_call)),
":" . implode(", :", array_keys($new_call))
);
echo var_dump("2");
$statement = $connection->prepare($sql);
$statement->execute($new_call);
echo var_dump("3");
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
echo var_dump("4");
}
echo var_dump("5");
?>

javascript php AJAX refresh part of a DIV

I was trying to refresh the sidebar class "login" only when a user clicked on the button, however, I am not being able to access the login.php when the user makes the click. When I click on it it's doing nothing and it's refreshing the entire page too.
For what I could understand AJAX needs to be used to refresh only that DIV and the console.log is not being triggered. What I am doing wrong here?
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form action="" method="post">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#login_button").click("login.php", function() {
console.log("login_button clicked");
});
})
</script>
<?php
}
else {
echo '<p>User is logged in</p>';
echo '<form action="" method="post">';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#logout_button").click("logout.php", function() {
console.log("logout_button clicked");
});
})
</script>
<?php
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
</body>
Thanks in advance
Your page is refreshing because of action="" on your form tags.
Also you don't need method="POST" on form tag if you are using AJAX to do so. Just remove it!
You may efficiently use ajax request in your scenario.
A suggestion: you could separate your js code out of the PHP code.
so your code will look like this -
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form id="loginForm">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
} else {
echo '<p>User is logged in</p>';
echo '<form>';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
<script type="text/javascript">
$("#login_button").click(function () {
var data = $("#loginForm").serialize();
$.ajax({
type: "POST",
url: 'login.php',
data: data,
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("login_button clicked");
});
$("#logout_button").click(function () {
$.ajax({
type: "POST",
url: 'logout.php',
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("logout_button clicked");
});
</script>
</body>

Email input is not taking email address as valid input in newsletter subscribe box

I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.

submitting a form through ajax for each ID

please guys, have some posts which i outputted from my database and now i want to make a comment form for each post and the form will be submitted through ajax method, but my problem is
the ajax method works for only the first outputted post and the form inserts into the database the mysqli_num_rows($query). ie if mysqli_num_rows($query) is =5, the form inserts into 5 rows in the database.
the remaining outputted forms reloads the page when the submit button is clicked.
This is what I want to achieve:
I want each form to be submitted without reloading.
I want the form to be inserted in only one row for each.
Here is my code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>
Change the input type="submit" to type="button" and make ajax on click of button.
For eg.:
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="button" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $("#my-form").serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
Above code will post the data without refreshing the page.
try this code
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form-"<?php echo $id; ?>>
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form-<?php echo $id; ?>').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>

copy text to textarea and submit all form in php

i have 20 user in my database and have 20 form in my site . this code show 20 form and i should send message every day to 20 user and want copy too all text area and submit them . i want have a form for send too all .
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
tihs code create 20 form with 20 id and :
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
Ok just i want 1 form too send too all , no more.

Categories

Resources