javascript php AJAX refresh part of a DIV - javascript

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>

Related

How to copy a file then rename it based on input field via buttonclick?

Good day experts!
I want to copy a file and rename it based on input value via button click. MY code is not working. There is no file being copied nor being renamed.
Here's my code:
<?php
error_reporting(0);
if($_POST['action'] == 'call_this') {
echo Success!;
};
$file = 'data.php';
$newfile = '$_GET['subject'].php';
echo copy($file, $newfile);
?>
<form action="<?php echo $newfile ?>" method="get">
<input type="text" name="subject" required>
<button type="submit">Change</button>
</form>
<script>
function change() {
$.ajax({
type: "POST",
url: 'data.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
</script>
i think this is what you looking for:
<html>
<body>
<form method="post" action="copy.php">
<input type="text" placeholder="new name" name="newFileName"/>
<input type="submit" value="Change"/>
</form>
</body>
</html>
copy.php :
<?php
$file = 'sample.txt';
$newfile = $_POST["newFileName"].'.txt';
if (!copy($file, $newfile)) {
echo "failed to copy";
}else {
echo "copy with new name";
}
?>

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
}
?>

How can i submit hidden values to php using AJAX

i am trying to send some values from html form to php page.
here in the form i have some values which are hidden.and one text field which its value has to be passed to php page.
index.php:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="friend-invite.php" method="get">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="submit" name="submit" value="Invite" class="btn btn-primary">
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
friend-invite.php:
<?php
include('_header.php');
$user_email = $_GET['friendemail'];
$invited_by = $_GET['invitename'];
$invite_link = $_GET['invite-url'];
$product_name = $_GET['invite-product-name'];
if (isset($user_email, $invited_by, $invite_link, $product_name)){
sendInvitation($user_email,$invited_by,$invite_link,$product_name);
} else {
echo "Are you trying to do something nasty??";
}
function sendInvitation($user_email,$invited_by,$invite_link,$product_name)
{
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->IsHTML(true);
} else {
$mail->IsMail();
}
$mail->From = EMAIL_VERIFICATION_FROM;
$mail->FromName = $invited_by;
$mail->AddAddress($user_email);
$mail->Subject = SHOP_INVITE;
$link = $invite_link;
$mail->Body = $invited_by." ".FRIEND_INVITE_PRODUCT."<a href='".$link."'>".$product_name."</a>";
if(!$mail->Send()) {
$this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
return false;
} else {
return true;
}
}
?>
AJAX function:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
the friend-invite.php page is getting the values that has been passed to it and check if the values has been set, if it has been set then it will call the php function sendInvitation() with the parameters. now all these things are happening pretty good.but i want to do it through AJAX. how can i do that.
You forgot to give your hidden fields an id:
echo '<input type="hidden" name="invitename" id="invitename" value="'.$_SESSION["user_name"].'">' ;
...
Change your index.php as:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="button" id="btn-submit" name="submit" value="Invite" class="btn btn-primary" />
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
And change AJAX function as:
$(function () {
$('#btn-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
We do not need a submit button in form if we using AJAX.
Dude you are simply making your code complex ... you are doing form submit + ajax submit .I think there you are going wrong.
Just try these:
Remove action="friend-invite.php" from your form tag and try . if this does not help than make your button input type button or use button tag. just try all these it should work.
If all this does not work than give id and name to your form ,,and use to submit as:
$(function() {
$("#form_id").on("submit", function(event) {
Try all these

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

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).

Categories

Resources