Reload PHP code after Ajax - javascript

i am still learning here folks, so excuse my code if its messy.
I have 3 separate pages as follow:
AccountView.php---Where the data is shown:
<div class="panel-body">
<div id="opentasks">
<!-- view Open tasks -->
<?php $task= new acct; echo $task->accountActiveTasks()?>
</div>
<!-- end view open tasks -->
<!-- start adding quick task -->
<div class="chat-form">
<!-- <form method="post" action="addTask.php"> -->
<div class="input-cont ">
<input type="text" class="form-control col-lg-12" placeholder="Add a quick Task..." name ="quicktask" id="quicktask">
</div>
<div class="form-group">
<div class="pull-right chat-features">
<a href="javascript:;">
<i class="icon-camera"></i>
</a>
<a href="javascript:;">
<i class="icon-link"></i>
</a>
<input type="submit" class="btn btn-danger" name="AddTask" value="Add" onclick="add_quick_task()">
<input type="hidden" name="acct" id="acct" value="<?php echo $_REQUEST['acctname']?>">
<input type="hidden" name="user" id="user" value="<?php $username = $_SESSION['username']; echo $username?>">
</div>
</div>
tasks.js --> graps one input from AccountView.php
function add_quick_task(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("microsodt.XMLHTTP");
}
var acct = document.getElementById('acct').value;
var quicktask = document.getElementById('quicktask').value;
// var taskstatus = 'Active';
var user = document.getElementById('user').value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4) {
document.getElementById('panel-body').innerHTML = xmlhttp.responseText;
}
}
url = "addTask.php?acct="+acct+"&quicktask="+quicktask+"&user="+user;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
account_functions.php ---Where the PHP function gets the data from mysql
public function accountActiveTasks(){
$varacctname = $_REQUEST['acctname'];
$varViewActiveTasks = mysql_query("SELECT * from tasks WHERE taskresource='$varacctname' && taskstatus='Active'");
while ($rows= mysql_fetch_array($varViewActiveTasks)) {
$this->accttask = $rows['tasktitle'];
$this->acctTaskStatus = $rows['taskstatus'];
$this->acctTaskOwner = $rows['taskowner'];
echo "<div class=\"timeline-messages\">
<div class=\"msg-time-chat\">
<img class=\"avatar\" src=\"img/chat-avatar.jpg\" alt=\"\">
<div class=\"message-body msg-in\">
<span class=\"arrow\"></span>
<div class=\"text\">
<p class=\"attribution\">$this->acctTaskOwner at 1:55pm, 13th April 2013</p>
<p> $this->accttask</p>
</div>
</div>
</div>
<!-- /comment -->
</div>";
}
My goal is that every time the tasks.js runs, the php code in AccountView.php is refreshed. sort of like appending the data. Currently the data gets pushed to the mysql table but i have to refresh to see it. I would like for it to show automatically on success.

Try it
window.location.reload();

What is panel-body that is a class.In the response you are adding response to it i think your intention is to have id="panel-body"
If you want to append the response to the "panel-body" Div you may use this jquery statement
if (xmlhttp.readyState==4) {
$('#panel-body').append(xmlhttp.responseText);
}

Related

Server Side Validation Show Success or Error message inline

I built a form for my class (private access only) where every one submit a form with some information. The information like Full name of the course, Subject, Select options for the list of teachers and a checkboxes for available class rooms. Some might like big or small rooms and available accessories for study. I did an effort for designing and built a form in bootstrap and php. Forms looks Okay and the validation is inline till I need to include one more feature in it. Every time when i submit a form it gets loaded. I mean, the form works with the php and html validation but the whole page gets loaded everytime i click the submit. I google it and know the this goal should be achieve by Ajax. I watched youtube videos and follow other questions here but got nothing. Inline validation or show the success message on the same page still not working. I want is when the user submit the form it will show the alert-success message on the samepage without refreshing or the error message inline if any errors there with server side validation. Codes easily available on internet.
html:
<?php
include('ajaxreturn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- 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://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<body>
<form id="submit" onsubmit="submitForm(); return false;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="Name">Name</label>
<input class="form-control" id="name" type="text" name="name" value= "<?php if (isset($_POST["name"])) echo htmlspecialchars($_POST["name"]) ?>">
<span class="text-danger"><?php echo $name_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="subject">Subject</label>
<input class="form-control form-control" type="text" name="subject" id="subject" value= "<?php if (isset($_POST["subject"])) echo htmlspecialchars($_POST["subject"]) ?>">
<span class="text-danger"><?php echo $subject_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control pt-0 pb-0" id="category">
<option>...</option>
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-1
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classroom_error;?></span>
</div>
div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-2
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classrooms_error;?></span>
</div>
<div class="row">
<button id="submit" name="submit" value="submit" type="submit" class="btn btn-success">submit</button>
<span class="text-danger"> Wrong!</span>
<span class="text-success"> Thanks!</span>
</div>
</form>
<!-- Optional JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- <script src="main.js"></script> -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
php:
<?php
// Form Variables
$name = "";
$subject = "";
$category = "";
$classroom="";
//Error Variables
$name_error ="";
$subject_error = "";
$category_error = "";
$classroom_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Your Name";
} else {
$name = validation($_POST["name"]);
// Function calling and checking the letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Your name must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["subject"])) {
$subject_error = "Your Subject";
} else {
$website = validation($_POST["subject"]);
// Function calling and checking the letters and whitespace
if ((!preg_match("/^[a-zA-Z ]*$]/", $subject)) {
$subject_error = "Subjets must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["category"])) {
$category_error = "Please select categoy";
} else {
$category = validation($_POST["category"]);
}
if (empty($_POST["classroom"])) {
$classroom_error = "Select the Class Room";
} else {
$classroom = validation($_POST["classroom"]);
}
}
function validation($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Ajax:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "name", _("name").value );
formdata.append( "subject", _("subject").value );
formdata.append( "category", _("category").value );
formdata.append( "classroom", _("classroom").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "ajaxreturn.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("submit").innerHTML = '<h2>Thanks '+_("name").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
Error:
ajaxform.php?name=&website=&submit=submit:78 Uncaught TypeError: Cannot read property 'value' of null
at submitForm (ajaxform.php?name=&website=&submit=submit:78)
at HTMLButtonElement.onclick (ajaxform.php?name=&website=&submit=submit:58)
submitForm # ajaxform.php?name=&website=&submit=submit:78
onclick # ajaxform.php?name=&website=&submit=submit:58
ajaxform.php?name=&website=&submit=submit:78
formdata.append( "category", _("category").value );
onclick # ajaxform.php?name=&website=&submit=submit:58
<button name="submit" id="submit" onclick="submitForm()" value="submit" type="submit" class="btn btn-success">submit</button>
Category with Select options Tag
<option value=1>1</option>
<option value=1>1</option>
<option value=1>1</option><option value=1>1</option>
Trying changing the ajax inside to this.
if (this.status == 200 && this.readyState == 4) {
this.responseText;
The rest of your code above looks right. I have never seen xmlhttprequest used having a variable name inside, Usually it looks like
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "ajaxreturn.php", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
I dont know enough php to take a look at your server side validation. I use NodeJs for all of that. Did you console log your this.responseText to see what variable your server is sending back. Also don't have your submit button submit, that is also your problem, have it run the onSubmit function. So...
<button id="submit" name="submit" onclick="submitForm()" class="btn btn-success">submit</button>
and take the onSubmit off of your form tag. I believe this will fix your issues.
When you submit the form, thats what opens a new page, when you just run the function with ajax, that won't make the browser open a new page. It just happens in the background.

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

How to create a forum with posts and replies for each post

I have a forum page with users' posts. I need to make a reply text area where a user can reply to any post. the problem is whenever a post is replied to, my JS script is unable to detect the specific post that the reply belongs to.
Here is the php snippet that generates a list of the posts and creates a reply form.
echo'
<div id="div'.$post_id.'"></div>
<form name="form'.$post_id.'">'; echo'
<div class="row">
<div class="col-sm-1">
<img src="" width="70" height="70" class="img img-responsive" alt="Your profile picture.">
</div>
<div class="col-sm-4">
<textarea placeholder="Your reply" name="user_reply" class="form-control" maxlength="250" rows="3" required></textarea>
<input type="hidden" name="user_id" value="'.$userId .'">
<input type="hidden" name="time" value="'.$time .'">
<input type="hidden" name="date" value="'.$date .'">
</div>
<div class="col-sm-1">
<button name="data" type="button" onclick="sendReply(\' '.$post_id.' \');">Reply</button>
</div>
</div>
</form>
</div>';
Now here is the JS script that I think should pick the user's reply and send the values to reply.php file
<script>
function sendReply(id){
x='document.form'+id;
post_id = id;
user_id = x.user_id.value;
reply = x.user_reply.value;
date = x.date.value;
time = x.time.value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("div"+id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'reply.php?reply='+reply+'&post_id='+post_id+'&user_id='+user_id+'&time='+time+'&date='+date, true);
xmlhttp.send();
}
</script>
Finally here is the error I am getting in the browser console when I click the reply button
(index):121 Uncaught TypeError: Cannot read property 'value' of undefinedsendReply
# (index):121onclick
# VM161:211
This part is the problem:
x='document.form'+id;
post_id = id;
user_id = x.user_id.value;
Here you're creating a variable x that contains a string, but then you try to access it as if it was an object.
Instead, try this:
x = document['form' + id]

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