I "finished" my commenting system but one problem left.
After I write a comment and then reload the page, then the comment gets posted again..
Ive googled now 2~ hours and cant find some help
code:
<script type="text/javascript">
function toggle_comment(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
$(function() {
$(".submit").click(function() {
var comment = $("#comment").val();
var dataString = 'comment=' + comment;
if(comment=='')
{
alert('Please enter at least 30 characters');
return false
}
else
{
$.post("pages/comment.php", $("#postcommentform").serialize(), function(data) { });
}
});
});
$(function() {
$(".login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username=' + username + '&password=' + password;
if(username=='' || password=='')
{
alert('Login is incorrect');
return false
}
else
{
$.post("pages/login.php", $("#postlogin").serialize(), function(data) { });
}
});
});
</SCRIPT>
<a class="sitelinksblue" onclick="toggle_comment('commentfield');" style="font-family: Verdana, Geneva, sans-serif;font-size:12px;font-weight:bolder;">+ Kommentar abgeben für Englisch Für Anfänger</a>
<BR></BR>
<?php
if(isset($_POST['submitcomment']) && $_POST['submitcomment']=="Submit") {
if((checkComment($_POST['comment']) && strlen($_POST['comment'])>=10 && strlen($_POST['comment'])<=1500)) {
$sqlCmd = "INSERT INTO topmovies.comments
(username,comment,date)
VALUES
('".mysql_real_escape_string($_SESSION['user_username'])."','".mysql_real_escape_string($_POST['comment']);."','".$sqlZeit."')";
$sqlQry = mysql_query($sqlCmd,$sqlHp);
?>
<?PHP
if (!$sqlQry) {
die('Invalid query: ' . mysql_error());
}else { echo'Comment Added!'; }
}else{ echo'Error! Please enter a comment with 30 or more and 1500 or less characters';}
} else { }
?>
<div id="commentfield" style="display:none">
<?PHP
if (isset($_SESSION['user_username'])){
if($getAdmin->status=='BANN'){
echo $lang['BANN'];
exit();
}else{
?>
<form id="postcommentform" method="POST" action="">
<p>Dein Name: <?PHP echo $_SESSION['user_username']; ?></p>
<textarea class="textareacom" name="comment" id="comment" rows="5" cols="20" maxlength="1500" value=""></textarea><br />
<input name="submitcomment" id="submit" type="submit" class="submit" value="Submit" />
</form>
<?PHP
}
}else{
?>
<FORM id="postlogin" action="" method="POST">
<p style="font-weight:bolder;">Um Kommentare schreiben zu können musst du dich zuerst einloggen</p>
<TABLE>
<TR>
<TD align="left"><font face="Arial" color="#000000"><?php echo $lang['REGISTER_USERNAME']; ?></TD>
<TD align="left"><input type="text" name="username"/></TD>
</TR>
<TR>
<TD align="left"><font face="Arial" color="#000000"><?php echo $lang['REGISTER_PASSWORD']; ?></TD>
<TD align="left"><input type="password" name="password"/></TD>
</TR>
<TR>
<TD></TD>
<TD align="left"><input type="submit" id="login" value="login" name="submit" /></TD>
</TR>
</TABLE>
<?php echo $lang['LOGIN_REGISTER']; ?> | <?php echo $lang['FORGOT_PW']; ?>
<BR></BR>
</FORM>
<?PHP
}
?>
</div>
<?php
$sql=mysql_query("select * from topmovies.comments ORDER BY date DESC");
while($row=mysql_fetch_array($sql))
{
$username=$row['username'];
$comment=$row['comment'];
$date=$row['date'];
$name=$row['name'];
?>
<div id="comments" name="comments">
<div class="comments" style="padding-top:5px;">
<BR>
<table width="746px" style="display:inline;" border="0" cellspacing="0" cellpadding="0">
<tr>
<td rowspan="4" valign="top" width="154px" style="padding-right:19px;"><img style="display: block; padding-top:10px;" src="http://img.movie4k.to/img/user_top.gif" height="8px"/>
<span class="test"><?php echo $username; ?><br />
<br />
<font size=1><?PHP echo date("d-m-Y", strtotime($date))?></br>
<?PHP echo date("H:i", strtotime($date))?></font></span>
<img style="display: block; background-color: #AFAFAF; padding-left:10px; padding-right:10px;" src="http://img.movie4k.to/userpics/476090.gif" width=40 height=50/>
<img style="display: block;" src="http://img.movie4k.to/img/user_bottom.gif" height="8px"/></td>
<td colspan="2" valign="bottom" height="8px"><img style="display: block; padding-top:10px;" src="http://img.movie4k.to/img/comment_top2.gif" height="8px"/></td>
</tr>
<tr>
<td rowspan="2" width="522px" class="comment" valign="top" bgcolor="#E3E3E3" style="padding-left:10px; padding-right:17px;">
<?php echo $comment; ?>
</td>
<td width="85px" valign="top" bgcolor="#E3E3E3" style="font-size:19px;">
<div style="min-height:50px;"></div>
</td>
</tr>
<tr>
<td bgcolor="#E3E3E3" valign="bottom"></td>
</tr>
<tr>
<td colspan="2" valign="top" height="8px"><img style="display: block;" src="http://img.movie4k.to/img/comment_bottom2.gif" height="8px"/></td>
</tr>
</table>
</div>
</div>
<BR />
<?php
}
?>
Does anyone see there a mistake what is wrong?
I tryed 1 thing, but then it dont show the echo "comment added!"
After the user submits the form, and after the POST data is read by the php code, you could redir to another page. That could solve it.
if you don't want to do that, you could compare the post with others to see if it has the same content, very close time-stamp, and same user. I wouldn't recommend that though.
Instead of doing
echo'Comment Added!';
You could redirect the user to the same page, thus removing the POST, with a 'flag' which tells the app a comment had just been added.
eg:
header('Location: myPage.php?commentAdded=true'); //myPage is current page
then somewhere else in the page:
if(isset($_GET['commentAdded'])){
echo'Comment Added!';
}
Related
Well, I searched the whole Internet the last days to find a way to attach an unique ID and/or name to a GENERATED form inside a Bootstrap-Modal and I never succeeded...
I know I'm making mistakes in the code, but I ran out of ideas, I don't know what to use.
*Edit: I'm using Bootstrap 3, I created a table, having a live search field using JavaScript. The table rows are displayed from a database using a query. The last column of the row pops up a Bootstrap-Modal inside which a form is located, now here is the problem! I managed to assign a unique ID to each Modal and each Modal popup button, but the form! From here everything is mist.
Here is the code:
<div id="fm-<?php echo $row['PacientID']; ?>" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
<b>
Fișa medicală #<?php echo $row['PacientID']; ?>: <?php echo $row['Name'].' '.$row['Surname']; ?>
</b>
</h4>
<?php
if (isset ($entranceSuccess))
{
?>
<div class="alert alert-success text-center">
<?php echo $entranceSuccess; ?>
</div>
<?php
}
?>
<?php
if (isset ($entranceError))
{
?>
<div class="alert alert-danger text-center">
<?php echo $entranceError; ?>
</div>
<?php
}
?>
</div>
<form data-toggle="validator" id="entranceForm" role="form" method="POST">
<div class="modal-body">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center">Data Intrării</th>
<th class="text-center">Medic Stomatolog</th>
<th class="text-center">Tratament</th>
<th class="text-center">Achitat</th>
</tr>
</thead>
<tbody>
<?php
$intrari = "SELECT * FROM intrari";
$intrariResults = $db -> query($intrari);
while ($row2 = $intrariResults -> fetch_assoc())
{
if ($row2['Pacient'] == $row['PacientID'])
{
?>
<tr class="text-center">
<th scope="row" class="text-center">
<?php echo $row2['EntranceDate'];?>
</th>
<td>
<?php
if ($row2['Medic'] == 1)
{
echo 'Dr. Carmen Pădurean';
}
else if ($row2['Medic'] == 2)
{
echo 'Dr. Claudiu Șuc';
}
else if ($row2['Medic'] == 3)
{
echo 'Dr. Mihaela Toncean';
}
else if ($row2['Medic'] == 4)
{
echo 'Dr. Alexandra Cenan';
}
else
{
echo 'MEDICUL STOMATOLOG NU A FOST DEFINIT!';
}
?>
</td>
<td>
<?php echo $row2['Treatment'];?>
</td>
<td>
<?php echo $row2['Achitat'];?>
</td>
</tr>
<?php
}
}
?>
<tr>
<th scope="row" class="text-center">
<div class="form-group">
<div class="input-group date entranceDateField">
<input type="text" class="form-control" id="entranceDate" name="entranceDate">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</th>
<td>
<div class="form-group">
<select class="form-control" id="medic" name="medic">
<option value="1">Dr. Carmen Pădurean</option>
<option value="2">Dr. Claudiu Șuc</option>
<option value="3">Dr. Mihaela Toncean</option>
<option value="4">Dr. Alexandra Cenan</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="treatment" name="treatment">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="achitat" name="achitat">
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="addEntrance" name="addEntrance-<?php echo $row['PacientID'];?>">
<span class='glyphicon glyphicon-plus'></span> Adaugă Intrare
</button>
<?php
if (isset ($_POST['addEntrance-<?php echo $row[PacientID]; ?>']))
{
$entranceDate = $_POST['entranceDate'];
$pacient = $row['PacientID'];
$medic = $_POST['medic'];
$treatment = $_POST['treatment'];
$achitat = $_POST['achitat'];
$insertEntrance = "INSERT INTO intrari (EntranceDate, Pacient, Medic, Treatment, Achitat)
VALUES ('$entranceDate', '$pacient', '$medic', '$treatment', '$achitat')";
if (mysqli_query ($db, $insertEntrance))
{
$entranceSuccess = "Pacientul a fost adăugat în baza de date cu succes!";
}
else
{
$entranceError = "A apărut o eroare nedefinită! Suna-l pe Andrei (0755 696 200) și dictează-i: \"Error code: " . mysqli_error ($db) . "\"";
}
}
?>
</div>
</form>
</div>
</div>
By looking at your code, I see you are putting Modal HTML inside loop and by assigning unique id's to modal selector id="fm-<?php echo $row['PacientID']; ?>" trying to create multiple modals with unique id(s), it will cause the page to load slow and running queries inside each unique modal fetching the records from database when even you don't need fetched records on page load, it's not a good practice,
so let's go one step backward and remove the Modal from while loop and put it outside and remove <?php echo $row['PacientID']; ?> from Modal id selector.
<div id="fm" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
//Modal-Header, Modal-Body, Modal-Footer Comes Here
</div>
</div>
</div>
Now as you stated The last column of the row pops up a Bootstrap-Modal
Assuming you are triggering the modal with default behaviour with data attributes data-toggle="modal" data-target="#fm" and you have other information in other columns of rows like <?php echo $row['Name'].' '.$row['Surname']; ?> so you must have something like
<tr>
<td><?php echo $row['PacientID']; ?></td>
<td><?php echo $row['Name'].' '.$row['Surname']; ?></td>
<td><button type="button" class="btn btn-info" data-toggle="modal" data-target="#fm">Open Modal</button></td>
</tr>
Now Let's pass the pacientid and name to modal, Add data-attribute data-pacient to name col and to modal trigger button so above table col's will be
<tr>
<td><?php echo $row['PacientID']; ?></td>
<td><span class="pacientname" data-pacient="<?php echo $row['PacientID']; ?>"><?php echo $row['Name'].' '.$row['Surname']; ?></span></td>
<td><button type="button" data-pacient="<?php echo $row['PacientID']; ?>" class="btn btn-info" data-toggle="modal" data-target="#fm">Open Modal</button></td>
</tr>
With bootstrap modal event listener, you can pass the information to modal when modal about to show or shown
$(document).ready(function(){ //Dom Ready
$('#fm').on('show.bs.modal', function (e) { //Show event listener
var id = $(e.relatedTarget).data('pacient'); //Fetch val from modal data-attribute
var name = $('.pacientname[data-pacient="' + id +'"]').html(); //fetch val from selector `pacientname` data-attribute with match the val of modal button data-attribute
$(".pid").html(id); //selector inside modal header to pass id
$(".pname").html(name); //selector inside modal header to pass name
$("#addEntrance").val(id); //Passing id to hidden input in form, explained below
//Ajax method comes here which explains below
});
});
Modal-Header
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="pid"></span> <span class="pname"></span></h4>
</div>
Fiddle Example to pass information to modal
Now about the query you are running inside modal, it can be done via Ajax method and display the information in modal. As we already have the required variable var id = $(e.relatedTarget).data('pacient'); can use it to fetch the required information via Ajax method
var dataString = 'id='+ id;
alert(dataString);
$.ajax({
type: "POST",
url: "file.php", //Create this file and handle query in it.
data: dataString,
cache: false,
success: function (data) {
$("#morecontent > tbody.showHere").html(data); //show fetched information from database
}
});
and file.php will be
<?php
//Database Connection Here
if(isset($_POST["id"])) {
$id = $_POST["id"]; //escape the string
$queryIntrari = "SELECT * FROM intrari WHERE Pacient = '$id'";
$intrariResults = $db -> query($queryIntrari);
while ($row2 = $intrariResults -> fetch_assoc()){
?>
<tr class="text-center">
<th scope="row" class="text-center">
<?php echo $row2['EntranceDate'];?>
</th>
<td>
<?php
if ($row2['Medic'] == 1)
{
echo 'Dr. Carmen Pădurean';
}
else if ($row2['Medic'] == 2)
{
echo 'Dr. Claudiu Șuc';
}
else if ($row2['Medic'] == 3)
{
echo 'Dr. Mihaela Toncean';
}
else if ($row2['Medic'] == 4)
{
echo 'Dr. Alexandra Cenan';
}
else
{
echo 'MEDICUL STOMATOLOG NU A FOST DEFINIT!';
}
?>
</td>
<td><?php echo $row2['Treatment'];?></td>
<td><?php echo $row2['Achitat'];?></td>
</tr>
<?php } } ?>
and the Modal-body, Modal-Footer with form and information fetched from database using Ajax will be like
<table class="table table-hover table-bordered" id="morecontent">
<form data-toggle="validator" id="entranceForm" role="form" method="POST">
<input type="hidden" id="addEntrance" name="addEntrance" value="">
<div class="modal-body">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center">Data Intrării</th>
<th class="text-center">Medic Stomatolog</th>
<th class="text-center">Tratament</th>
<th class="text-center">Achitat</th>
</tr>
</thead>
<tbody class="showHere">
//Information Fetched from Database Using Ajax will show Here
</tbody>
<tbody>
<tr>
<th scope="row" class="text-center">
<div class="form-group">
<div class="input-group date entranceDateField">
<input type="text" class="form-control" id="entranceDate" name="entranceDate">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</th>
<td>
<div class="form-group">
<select class="form-control" id="medic" name="medic">
<option value="1">Dr. Carmen Pădurean</option>
<option value="2">Dr. Claudiu Șuc</option>
<option value="3">Dr. Mihaela Toncean</option>
<option value="4">Dr. Alexandra Cenan</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="treatment" name="treatment">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="achitat" name="achitat">
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">
<span class='glyphicon glyphicon-plus'></span> Adaugă Intrare
</button>
</div>
</form>
Note: Created a hidden input in <form> above, passed the value <?php echo $row['PacientID']; ?> to the hidden input when modal show, Post this hidden input along with other inputs when submitted the form in modal to insert or update values into database
an example here
Mission accomplished and hope you figure it out how to pass and get information in modal
Note: You can submit the modal form either the way you are doing or can also do it with Ajax and show success or error message inside modal without closing it and leaving the page but that's another story to tell some other time.
Happy Coding.
i have this form called news and events, I want that when the form is successfully saved, the table form will hide then the add another button will appear. Im using session set userdata so that when the form is successfully saved the add another button will appear then the table form will hide. my code runs well but the problem is, after it successfully send the add another button will not work here's my controller below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class News_and_events extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('admin_model', 'am');
}
public function index(){
if($this->session->userdata('logged_in')){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
redirect('login', 'refresh');
}
}
public function add(){
if($this->session->userdata('logged_in')){
$this->form_validation->set_rules('date', 'Date', 'trim|required|xss_clean');
$this->form_validation->set_rules('event', 'Event', 'trim|required|xss_clean');
$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'Date' => $this->input->post('date'),
'Event' => $this->input->post('event'),
'Description' => $this->input->post('description')
);
$this->am->saveData($array);
$this->session->set_userdata('add_another', $array);
redirect('news_and_events', 'refresh');
}
}else{
redirect('homepage', 'refresh');
}
}
}
and my views
<div class="container" >
<br />
<br />
<br />
<ul id="nav">
<li><h4>Home</h4></li>
<li><h4>News and Events</h4></li>
<li><h4>Activities</h4></li>
</ul>
<div class="starter-template">
<h1>News And Events</h1>
<?php if($this->session->set_userdata('add_another')):?>
<div id="add_another" style="float:left;">
<input type="button" value="Add Another" class="btn btn-primary" />
</div>
<?php else: ?>
<form action="<?php echo base_url().'news-and-events/add'?>" method="post">
<?php echo validation_errors('<div class="error">', '</div>');?>
<table class="table-striped">
<tr>
<td>Date: </td>
<td><input type="text" id="datepicker" name="date" value="<?php echo set_value('date');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td >Event: </td>
<td ><input type="text" name="event" value="<?php echo set_value('event');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="20%">Description: </td>
<td><textarea cols="30" rows="5" name="description" ><?php echo set_value('description');?></textarea></td>
</tr>
<tr>
<td width="20%"> </td>
<td><input type="submit" value="Add" class="btn btn-success" /></td>
</tr>
</table>
</form>
<?php endif; ?>
<br />
<br />
<table class="table" >
<tr>
<th>Date</th>
<th width="51%">Event</th>
<th>Description</th>
<th>Options</th>
</tr>
<?php foreach($allData as $allData): ?>
<tr>
<td><?php echo $allData->Date; ?></td>
<td><?php echo $allData->Event; ?></td>
<td></td>
<td></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div><!-- /.container -->
<script>
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate),
dateFormat: "yy-mm-dd"
});
</script>
in my views file ive added there the if else statement $this->session->set_userdata('add') just below the h1 tag which is news and events this will trigger the statement when the form is successfully saved!
can someone help me figured this out? or how to do this correctly?
any help is much appreciated! thanks!
istead of this line
<?php if($this->session->set_userdata('add_another')):?>
use this
<?php if($this->session->userdata('add_another')):?>
and in your controller before loading the view add this line
$this->session->set_userdata('add_another',1);
I am facing a problem for my form.
It cannot receive well when i set abc#xxxx.co.id as receiver. All message is correct, just it will stat with "Content-type: text/html; charset=utf-8 " and come with table format.
It should look tidy.
Content-type: text/html; charset=utf-8
To: crm#merekmu.co.id
From: <hl.tam#webnic.cc>
Message-Id: <20130618031715.7DA4712406D9#gemilang-pandi.localdomain>
Date: Tue, 18 Jun 2013 10:17:15 +0700 (WIT)
<html>
<head>
<title>Merekmu “LIKE and WIN” Contest Submission</title>
</head>
<body>
<h2>Merekmu “LIKE and WIN” Contest Submission</h2>
<table width='95%' cellpadding='0' cellspacing='11'>
However, this form work well if i use another email as receiver(123#xxxx.com). Use same code, i just change email.
I made some testing as below:
email 1:abc#xxxx.co.id
email 2:123#xxxx.com
web 1:www.456.com
web 2:www.abc.co.id
Test 1: set email abc#xxxx.co.id as receiver at www.abc.co.id - messy message receive
Test 2: set email 123#xxxx.com as receiber at www.abc.co.id - work well and show tidy message
Test 3: set email abc#xxxx.co.id as receiver at www.456.com - work well and show tidy message
I have no idea with what problem is it?
<?php
$firstName= $_POST['firstName'];
$lastName= $_POST['lastName'];
$email= $_POST['email'];
$fbUrl= $_POST['fbUrl'];
$blog= $_POST['blog'];
// subject
$subject = $name;
// message
$message = "
<html>
<head>
<title>Merekmu “LIKE and WIN” Contest Submission</title>
</head>
<body>
<h2>Merekmu “LIKE and WIN” Contest Submission</h2>
<table width='95%' cellpadding='0' cellspacing='11'>
<tr>
<td width='189'> First Name:</td>
<td>$firstName</td>
</tr>
<tr>
<td width='189'> Last Name:</td>
<td>$lastName</td>
</tr>
<tr>
<td width='189'> Email:</td>
<td>$email</td>
</tr>
<tr>
<td width='189'> Facebook profile URL:</td>
<td>$fbUrl</td>
</tr>
<tr>
<td width='189'> Blog:</td>
<td>$blog</td>
</tr>
</tr>
</table>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
// Additional headers
$headers .= "To:crm#merekmu.co.id" . "\r\n";
$headers .= "From:".$name."<".$email.">\r\n";
$subject .= "Merekmu “LIKE and WIN” Contest Submission ";
//$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
//$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
if(mail($toemail, $subject, $message, $headers)) {
echo '';
} else {
echo '';
}
?>
valindation
$(document).ready(function() {
$('form#contactForm').submit(function() {
$('form#contactForm .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Lapangan tidak boleh kosong.</div>');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Silakan masukkan email yang valid.</div>');
hasError = true;
}
}
});
if(!hasError) {
$('form#contactForm li.submit_btn').fadeOut('normal', function() {
$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contactForm').slideUp("fast", function() {
$(this).before('<p class="thanks">Formulir telah dikirimkan.</p>');
});
});
}
return false;
});
});
HTML
<form action="submit.php" id="contactForm" method="post">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top" colspan="2" align="center"> <div class="title"> Merekmu “LIKE and WIN” Contest Submission </div></td>
</tr>
<tr>
<td valign="top" width="200" class="form-left"><label for="contactName"><strong>First Name:</strong> <span class="require">*</span></label></td>
<td valign="top">
<input type="text" name="firstName" id="firstName" value="" class="requiredField" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="contactName"><strong>Last Name:</strong> <span class="require">*</span></label></td>
<td valign="top">
<input type="text" name="lastName" id="lastName" value="" class="requiredField" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="email"><strong>Email:</strong> <span class="require">*</span></label></td>
<td valign="top">
<input type="text" name="email" id="email" value="" class="requiredField email" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="tel"><strong>Facebook profile URL:</strong> <span class="require">*</span></label>
</td>
<td valign="top">
<input type="text" name="fbUrl" id="fbUrl" value="" class="requiredField" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="tel"><strong>Blog:</strong> </label>
</td>
<td valign="top">
<input type="text" name="blog" id="blog" value="" /></td>
</tr>
<tr>
<td valign="top" colspan="2" align="center"> <input class="submit_btn" type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
<script type="text/javascript">
$(document).ready(function($) {
$('#searchicon').click(function(){
$('#searchicon.toappear').toggle();
$('#searchicon2.appear').toggle();
$('#extraSearch').slideToggle('fast');
});
$('#searchicon2').click(function(){
$('#searchicon.toappear').toggle();
$('#searchicon2.appear').toggle();
$('#extraSearch').slideToggle('fast');
});
$('input[name=estimate]').click(function(){
if (this.checked) {
$("input.groupestimate").removeAttr("disabled");
} else {
$("input.groupestimate").attr("checked", false);
$("input.groupestimate").attr("disabled", true);
}
});
$("input.groupgatepass").attr("disabled", true);
$('input[name=gatepass]').click(function(){
if (this.checked) {
$("input.groupgatepass").removeAttr("disabled");
} else {
$("input.groupgatepass").attr("checked", false);
$("input.groupgatepass").attr("disabled", true);
}
});
/*
$('input.groupestimate').click(function() {
if(this.checked) {
$form = $('#globalSearch form');
if($('#globalSearch form[ACTION*="'+this.value+'"]'))
var data = new Object();
data.field = this.value;
var dataString = $.toJSON(data);
$.post('json.php',
{data: dataString},
function(res){
var obj = $.evalJSON(res);
$form.attr('ACTION',$form.attr('action')+''+obj.query);
}
);
}
});*/
$('#globalSearch form').submit(function() {
if($('input.groupheader[type=checkbox]:checked').length > 1) {
alert('Please check only Estimate or Gatepass');
return false;
}
var data = new Object();
$('input.groupheader[type=checkbox]:checked').each(function(){
data.header = this.value;
});
data.fields = new Array();
$header = 'input.group'+data.header;
$($header+'[type=checkbox]:checked').each(function(){
data.fields.push(this.value);
});
var dataString = $.toJSON(data);
$.post('json.php',
{data: dataString},
function(res){
var obj = $.evalJSON(res);
$('input[name=query]').val(obj.query);
}
);
alert($('input[name=query]').val()); //alerts nothing or the old value :(
return false;
});
});
</script>
-------------HTML PART-------------------
<form action="?<?php echo http_build_query(cloneGet(array("server-page"=>$GLOBALS["setting"]["current_folder"], "currpage"=>"0","OrderBy"=>"","ByDirect"=>"","search_flg"=>"-1")));?>" method="post" id="" name="">
<div id="extraSearch">
<table class="stripe" width="100%" id="extraTableList">
<tbody>
<tr class="striped">
<th style="cursor:pointer;text-align:left;"><input type="checkbox" name="estimate" value="estimate" checked="checked" class="groupheader">Estimates</th>
<th style="cursor:pointer;text-align:left;"><input type="checkbox" name="gatepass" value="gatepass" class="groupheader">Gatepass</th>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate1" value="customer" class="groupestimate">Customer</td>
<td class="int"><input type="checkbox" name="gatepass1" value="old_serial" class="groupgatepass">Old Serial</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate2" value="serial_no" class="groupestimate">Serial No</td>
<td class="int"><input type="checkbox" name="gatepass2" value="type" class="groupgatepass">Type</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate3" value="invoice_no" class="groupestimate">Invoice No</td>
<td class="int"><input type="checkbox" name="gatepass3" value="type_id" class="groupgatepass">Type ID</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate4" value="salesman" class="groupestimate">Salesman</td>
<td class="int"><input type="checkbox" name="gatepass4" value="loader" class="groupgatepass">Loader</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate5" value="estimate_no" class="groupestimate">Estimate No</td>
<td class="int"><input type="checkbox" name="gatepass5" value="total" class="groupgatepass">Total</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate6" value="status" class="groupestimate">Status</td>
<td class="int"> </td>
</tr>
</tbody>
</table>
</div>
<img id="searchicon" src="___images/search-arrow.png" class="toappear" alt="Extra search" title="Extra search"/>
<img id="searchicon2" src="___images/search-arrow.png" class="appear" alt="Extra search" title="Extra search"/>
<input type="text" value="<?php echo $_REQUEST['quicksearch'];?>" id="s" name="quicksearch">
<input type="hidden" value="" id="query" name="query" temp="">
<input type="submit" value="Search" id="b">
<?php if( $_REQUEST['quicksearch'] ) { ?>
<a id="c" href="?<?php echo http_build_query(cloneGet(array("quicksearch"=>"","search_flg"=>"-1")));?>">Cancel</a>
<?php } ?>
</form>
As you can see, before it submits the values I want to insert a string into the 'query' input element value attribute. It works perfectly when doing it inside the callback of $.post but after checking it using alert() outside the $.post its empty.
Is $.post always like that?or am I missing something?
when you are using $.post it is making an async request. The reason alert will contain nothing or the old value is because it is triggered before the $.post can complete its request. When the alert is placed inside of the $.post callback it will have the data you want because it is called after the $.post has completed
I've been searching a bit for a jquery plugin that could help me to edit an entire form in place without having to write markup for both the form and displaying the data. Where you can just click "edit" and then the form fields would appear instead of the text, and then save and the form fields would turn into text again.
Does anyone know of one?
Here's the plugin in its crudest form:
(function( $ ){
var YesNo = new Array();
YesNo["true"] = "Yes";
YesNo["false"] = "No";
$.fn.inline = function() {
this.each(function(){
if ($(this).is('table')) {
$(this).find('input, select, textarea').not('[type=button],[type=submit]').each(function(){
if($(this).attr("type")=="checkbox"){
$(this).parent().append("<span class=\"editable\">"+YesNo[$(this).attr('checked')]+"</span>");
$(this).hide();
//$(this).append("<span>"+$(this).val()+"</span>");
$(this).bind('blur',function(){
var t = YesNo[$(this).attr('checked')];
$(this).hide().next().show().text(t);
});
}
else{
$(this).parent().append("<span class=\"editable\">"+$(this).val()+"</span>");
$(this).hide();
//$(this).append("<span>"+$(this).val()+"</span>");
$(this).bind('blur',function(){
var t = $(this).val();
$(this).hide().next().show().text(t);
});
}
});
$(this).find('td').live('dblclick', function(){
$(this).children('.editable').hide().prev().show().focus();
});
}
});
};
})( jQuery );
Call to plugin:
<script type="text/javascript">
$().ready(function () {
$('#dataform').inline();
});
</script>
And the supporting example markup:
<table id="dataform">
<tr>
<td class="label">First Name</td>
<td><input type="text" value="Robin" /> </td>
<td class="label">Last Name</td>
<td><input type="text" value="Maben" /> </td>
</tr>
<tr>
<td class="label">City</td>
<td><input type="text" value="Bangalore" /> </td>
<td class="label">Country</td>
<td><input type="checkbox" checked="checked" /> </td>
</tr>
<tr>
<td class="styleLabel">Status</td>
<td class="styleControl">
<select id="Select1" class="styleDrop">
<option>Active</option>
<option>Inavtive</option>
<option>Pending</option>
</select></td>
</tr>
<tr>
<td>Description</td><td><textarea>Hello World</textarea></td>
</tr>
<tr>
<td>
<input type = "button" value="Click" />
<input type = "submit" />
</td>
</tr>
</table>