Submit button stay in form after click - javascript

enter image description hereI want to stay in Form view after a click on submit button
I have a navigation bar with buttons:
<div class="bar blueGrey">
<button class="bar-item button tablink orange" onclick="openNavBarChoise(event,'HomePage')">Home</button>
<button class="bar-item button tablink" onclick="openNavBarChoise(event,'CVsPage')">CV</button>
<button class="bar-item button tablink" onclick="openNavBarChoise(event,'ContactPage')">Contact</button>
</div>
Javascript code:
function openNavBarChoise(evt, choiceName) {
var i, x, tablinks;
x = document.getElementsByClassName('choice');
for (i = 0; i < x.length; i++) {
x[i].style.display = 'none';
}
tablinks = document.getElementsByClassName('tablink');
for (i = 0; i < x.length; i++) {
tablinks[i].className = tablinks[i].className.replace(' orange', '');
}
document.getElementById(choiceName).style.display = 'block';
evt.currentTarget.className += ' orange';
}
when someone click on button Contact go to Contact Form. I want stay in this Form after click on submit, but this code return to HomePage.
<!--/*************** Begin Contact Page ***************/-->
<div id="ContactPage" class="container border choice" style="display:none">
<div class="panelChristos00">
<div class="ImgFPanel">
<img class="ImgPP" id="imgJob" src="Icons\contactSupport.png" alt="contactSupport" width="80px">
</div>
<div id="ergasia" class="firstLine">
<h2>Form</h2>
</div>
<div class="container">
<form id="form0" method="post" >
<div class="requiredM00">
<p style="color:red"><?php echo $requiredMessage;?></p><p style="color:blue"><?php echo $completeMessage;?></p>
</div>
<label for="name">Name <span class="error" style="color:red">*<?php echo $nameErr;?></span></label>
<input type="text" name="name" value="<?php echo $name;?>">
<label for="email">Email <span class="error" style="color:red">* <?php echo $emailErr;?></span></label>
<input type="text" name="email" value="<?php echo $email;?>">
<label for="phone">Phone <span class="error" style="color:blue"> <?php echo $phoneErr;?></span></label>
<input type="text" name="phone" value="<?php echo $phone;?>">
<label for="subject">Message <span class="error" style="color:red">*<?php echo $subjectErr;?></span></label>
<textarea id="subject" name="subject" style="height:200px" ><?php echo $subject; ?></textarea>
<input type="submit" value="Send">
</form>
</div>
</div>
</div>

by default form submit button submit the form to itself to stop this use evt.preventdefault() on form submit button

you could do this it will take you to new tab like you wanted
<form action="your file name">
<input type="text">
<input onclick="e.preventDefault()" type="submit" formtarget="_blank">
</form>

You wanna stay at the contact form and still send the form, right? you need to use ajax to be able to do that.
Attach event handler (on submit) to the form and preventDefault the event to prevent its default behaviour (like going back to the homepage)
var form_el = document.getElementById("form0");
form_el.addEventListener("submit", function(e) {
e.preventDefault(); // this will prevent the page from going back to homepage
var form = new FormData(this);
var XHR = new XMLHttpRequest();
XHR.open("POST", "server.php", true);
// response handler
XHR.onload = function () {
// do something with the response
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText);
}
};
XHR.send(form);
});

Related

XMLHttpRequest PHP Chats

I am trying to create a system to display messages on 2 or more separate chats( with different messages stored in a db) on the same page. The chats each have ids to differentiate them and I have created a function to go through each chat in use and print the approprite messages for them but only 1 chat gets the messages.
The Code:
The HTML
<div class="full_wrap">
<div class="force-overflow"></div>
<div id="Sidenav" class="side">
<h2>Chat Settings & Info</h2>
<a id="closebtn" href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="authr">
<a>
<div class="authr_img"></div>​
</a>
<form action="mypage.php" method="post">
<div class="authr_name">
<button value="<?php echo $chat_authr ?>" name="userlink" class="subm_as_text"><?php echo $chat_authr; ?></button>
</div>
</form>
</div>
<div class="chat_info">
<div class="chat_descy">
<h2>Chat Description</h2>
<div class="descc">
<h3><?php echo $chat_description; ?></h3>
</div>
</div>
<div class="chat_fol"><h2>Chat users: <?php echo $num_users; ?></h2></div>
<div class="chat_back">
<h2> Change Chat Wallpaper</h2>
<form method="post" action="picture.php" enctype="multipart/form-data">
<input type="file" id="upload" class="custom-file-input" name="chat_wall">
<input type="submit" class="chat_wall_subm" value="Change"/>
</form>
</div>
</div>
<form method="post" action="chat.php" >
<!--<input type="submit" class="chat_leave" name="" value="Leave Chat">-->
<button class="chat_leave" name="chat_leave" value="<?php echo $chat_index; ?>" >Leave Chat</button>
</form>
</div>
<div class="mnav">
<span onclick="openNav()">☰</span>
<i class="material-icons" id="chat_un_small" onclick="chat_un_small()">arrow_upward</i>
<h1><?php echo $chat_title ?></h1>
</div>
<!--one ting-->
<div class="conceal_wrapper">
<div class="msgs" id="5e2dbe2be3b5927c588509edb1c46f7d">
</div>
<form method="post" id="form_5e2dbe2be3b5927c588509edb1c46f7d" class="comform">
<div class="wcom" >
<input maxlength="140" type = "text" id="5e2dbe2be3b5927c588509edb1c46f7d" class="comin" placeholder="My message..." name="sendmsg" autocapitalize="off" autocorrect="off"/>
<input class="hidden_index" type="text" value="5e2dbe2be3b5927c588509edb1c46f7d" name="chat_index"/>
</div>
</form>
</div>
<div class="chat_enlarge">
<div class="chat_enlarge_full" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_full()"></div>
<div class="chat_enlarge_standard" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_standard()"></div>
<div class="chat_enlarge_small" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_small()"></div>
</div>
</div>
<div class="full_wrap">
<div class="force-overflow"></div>
<div id="Sidenav" class="side">
<h2>Chat Settings & Info</h2>
<a id="closebtn" href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="authr">
<a>
<div class="authr_img"></div>​
</a>
<form action="mypage.php" method="post">
<div class="authr_name">
<button value="<?php echo $chat_authr ?>" name="userlink" class="subm_as_text"><?php echo $chat_authr; ?></button>
</div>
</form>
</div>
<div class="chat_info">
<div class="chat_descy">
<h2>Chat Description</h2>
<div class="descc">
<h3><?php echo $chat_description; ?></h3>
</div>
</div>
<div class="chat_fol"><h2>Chat users: <?php echo $num_users; ?></h2></div>
<div class="chat_back">
<h2> Change Chat Wallpaper</h2>
<form method="post" action="picture.php" enctype="multipart/form-data">
<input type="file" id="upload" class="custom-file-input" name="chat_wall">
<input type="submit" class="chat_wall_subm" value="Change"/>
</form>
</div>
</div>
<form method="post" action="chat.php" >
<!--<input type="submit" class="chat_leave" name="" value="Leave Chat">-->
<button class="chat_leave" name="chat_leave" value="<?php echo $chat_index; ?>" >Leave Chat</button>
</form>
</div>
<div class="mnav">
<span onclick="openNav()">☰</span>
<i class="material-icons" id="chat_un_small" onclick="chat_un_small()">arrow_upward</i>
<h1><?php echo $chat_title ?></h1>
</div>
<!--one ting-->
<div class="conceal_wrapper">
<div class="msgs" id="9503e253936e716f18d9c57b4f97d618">
</div>
<form method="post" id="form_9503e253936e716f18d9c57b4f97d618" class="comform">
<div class="wcom" >
<input maxlength="140" type = "text" id="9503e253936e716f18d9c57b4f97d618" class="comin" placeholder="My message..." name="sendmsg" autocapitalize="off" autocorrect="off"/>
<input class="hidden_index" type="text" value="9503e253936e716f18d9c57b4f97d618" name="chat_index"/>
</div>
</form>
</div>
<div class="chat_enlarge">
<div class="chat_enlarge_full" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_full()"></div>
<div class="chat_enlarge_standard" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_standard()"></div>
<div class="chat_enlarge_small" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_small()"></div>
</div>
</div>
So there are 2 chats separated by the full_wrap class. The msgs have different id for the chat index stored unique for each chat in the db
The Javascript:
$( document ).ready(function() {
chat_receivemsgs();
});
function chat_receivemsgs(){
var cusid_ele = document.getElementsByClassName('msgs');
if(cusid_ele.length == 0) {
console.log("hi");
} else {
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var item_id = item.id;
console.log(cusid_ele.length);
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var item_id = item.id;
console.log(item_id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("yes");
console.log(item_id);
// document.getElementById(item_id).innerHTML = this.responseText;
$("#"+item_id).html(this.responseText);
}else{
console.log("no");
console.log(item_id);
}
}
xmlhttp.open("GET","receivemsg.php?q="+item_id,true);
xmlhttp.send();
}
}
}
}
receivemsgs.php just selects all messages in the messages table with the index of the index given by item_id. The problem is as stated that only the chat with 9503e253936e716f18d9c57b4f97d618 id receives the messages.
I heard that the requests repeat 4 times but I am not an expert in this field. By using the console, I understood that it ignores the first chat and only generates the messages for 9503e253936e716f18d9c57b4f97d618.
Any help would appreciate.
Also if there is a better way to control more than one chat on the same page, I wold love to know how to.
Thank you for your time.
The problem lies in how you're using XMLHttpRequest.
See this snippet:
function Obj() {
}
Obj.prototype = {
callFunc: function() {
setTimeout(this.func, 1000);
}
};
function test() {
var ids = ['id1', 'id2'];
for (var i = 0 ; i < 2 ; ++i) {
var id = ids[i];
var obj = new Obj();
obj.func = function() {
console.log(id);
};
obj.callFunc();
}
}
test();
As you can see, the code prints "id2" twice to the console. That's similar to your problem.
What happens is that, in obj.func (in your code, that's xmlhttp.onreadystatechange), the id variable (respectively item_id) comes from the outer function. Its value when obj.func is assigned is not "saved". When the function finally gets executed, it will use the last known value for that variable.
So here's what happens:
i = 0
id = ids[0] = 'id1'
a new Obj is created (let's call it obj1) and assigned to obj
obj1.func is created
obj1.callFunc is called, it programs obj1.func to be called later
i = 1
id = ids[1] = 'id2'
a new Obj is created (let's call it obj2) and assigned to obj
obj2.func is created
obj2.callFunc is called, it programs obj2.func to be called later
obj1.func gets called, it prints the last value of id, that is "id2"
obj2.func gets called, it prints the last value of id, that is "id2"
There are a few ways around that behavior. You could retrieve item_id from PHP's output somehow. You could set item_id to a member of xmlhttp and use that in your function (xmlhttp.item_id = item_id; then inside the function this.item_id). Or you could use bind. With the latter solution, your code becomes:
xmlhttp.onreadystatechange = function(this_item_id) {
if (this.readyState == 4 && this.status == 200) {
console.log("yes");
console.log(this_item_id);
// document.getElementById(this_item_id).innerHTML = this.responseText;
$("#"+this_item_id).html(this.responseText);
}else{
console.log("no");
console.log(this_item_id);
}
}.bind(xmlhttp, item_id);
xmlhttp.open("GET","receivemsg.php?q="+item_id,true);
xmlhttp.send();
By the way, I don't understand why you're iterating twice on cusid_ele (you have two nested loops).

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

jquery fadeIn and fadeOut not working before click

i have one form like this.
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
and i call one .js file for it is.
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#phone').val();
var message = $('#message').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#phone_error').fadeIn(500);
}else{
$('#phone_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
// If there is no validation error, next to process the mail function
if(error == false){
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("contact-post.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#mail_success').fadeIn(500);
}else{
//Display the error message
$('#mail_fail').fadeIn(500);
// Enable the submit button again
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
and one contact-post.php file is.
<?php
include('config.php');
if (isset($_POST['submit'])) {
$name=$_POST['name'];
$mail=$_POST['email'];
$phone=$_POST['phone'];
$msg=$_POST['message'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
test_input($name);
$query="INSERT INTO `inquiry` (id,name,contact,email,query) values ('','$name','$phone','$mail','$msg')";
$qur=mysql_query($query);
if ($qur) {
echo 'sent';
}
else {
echo 'failed';
}
}
?>
my problem is when i refresh page it's displaying like this.
i want that all message should not display before clicking submit button.please help me.
Update (adding snippet) :
.error , .success
{
display:none;
}
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
You can do one of the following :
Set the error and success classes display to none, since they will be displayed using the fadeIn function.
.error , .success
{
display:none;
}
Or
You can hide the <div>s with jQuery on load as follows :
$(document).ready(function(){
$('.error , .success').hide();
.....
});
I guess the first solution would be a better approach since the elements will not view at all since CSS loads before JS (assuming that this is the order you are loading your files with), while in the second approach the elements will be visible until jQuery loads and hides them.
Add a style as below to hide the error/success messages.
#mail_fail, #mail_success{
display : none;
}

How do I keep a login modal from closing after the submit button is hit?

I am currently working on a PHP website. When the user clicks login a JQuery Modal pops up and asks the user to login. After the submit button is clicked the box closes and the user is either logged in or invalid username/password is echo'd into the login modal but the box still closes. When you hit log in the modal pops up again with invalid username. I want the modal to stay open if the user does not log in correctly. Thank you!
<form action="" method="POST">
<div class="modal-header">
<h4>Login</h4>
</div>
<div class="modal-body row">
<?php
if(isset($_POST['login'])){
$user_login = strip_tags(#$_POST['user_name']);
$password_login = strip_tags(#$_POST['user_password']);
$password_login = md5($password_login);
$sql = mysql_query("SELECT * FROM users WHERE email='$user_login' AND password='$password_login' LIMIT 1");
$userCount = mysql_num_rows($sql);
if($userCount == 1){
while($row = mysql_fetch_array($sql)){
$user_id = $row["id"];
$user_fname = $row["first_name"];
$user_lname = $row["last_name"];
$user_membersince = $row["date"];
}
$_SESSION['user_email'] = $user_login;
$_SESSION['user_fname'] = $user_fname;
$_SESSION['user_lname'] = $user_lname;
$_SESSION['user_membersince'] = $user_membersince;
}else {
echo("invalid username/password");
}
}
?>
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" name="user_name" placeholder="email address">
</div>
<div class="col-sm-12">
<input type="text" class="form-control" type="password" name="user_password" placeholder="password">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class = "btn btn-warning" value="login"name="login">Login</button><a class = "btn btn-warning" data-dismiss = "modal">Cancel</a>
</div>
</form>
</div>
</div>
</div>
You can use ajax metod on click submit button.
$.ajax({
type: 'POST',
url: url,
data: $('#bob').serialize(),
success: success,
dataType: dataType
});

Image not send using javascript when submit form no refresh page

I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).

Categories

Resources