Alright, so I have a basic form on my page:
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
and the javascript is:
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
<?php
$Chat = mysql_real_escape_string(strip_tags($_POST['Chat']));
$Go = mysql_real_escape_string($_POST['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
?>
});
</script>
I just need it to stop from refreshing when someone submits. I've read a few different posts on here with the same problem, but none seemed to work for me.
$('#formId').submit(function () {
/do your stuff
return false;
});
Returning false will prevent page reloading.
You need to separate the php code to your script. PHP is executed server side, js/jquery is executed client side. Try this code if it will help you.
<?php
if(isset($_POST['Go'])){
$Chat = mysql_real_escape_string(strip_tags($_POST['Chat']));
$Go = mysql_real_escape_string($_POST['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
}
?>
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
});
</script>
REVISED: 06/15/2015 10:16AM GMT+8
You need use AJAX to send data. First, Add an id to the text field then create a php file for getting the data from the URL and insert the chat to DB. Try this code:
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' id='chat' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_chat.php?",
data: "Chat="+$('input#chat').val(),
dataType: "json",
success: function(data){
}
});
});
</script>
insert_chat.php
<?php
$Chat = mysql_real_escape_string(strip_tags($_GET['Chat']));
$Go = mysql_real_escape_string($_GET['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
?>
Related
I have asynchronously loaded form. When I submit the form by clicking the submit button, it submits multiple times. I have gone through some of the SO answers but still the problem is there.
Form:
<form action="" method="POST" id="aproveForm" class="smart-form" novalidate="novalidate">
<fieldset>
<section class="col col-5" >
<select class="form-control" name="groupid" onchange="loadInvoice(this.value);">
<option value="1">Sales</option>
<option value="2">Merchandiser</option>
</select>
</section>
</fieldset>
</form>
JS
function loadInvoice(id){
nid= 'id='+id;
$.ajax({
type:'POST',
url:'loadform.php',
data:nid,
dataType:'html',
success:function(data) {
$('#payform').html(data);
}
});
}
in the <div id="payform">, I have loaded the form from loadform.php which is like below:
<form method="POST" id="mulpayment">
<table class="table table-bordered" style="width:80%;">
<tr>
<th><div align="center">Name of Customer</div></th>
<th><div align="center">New Payment</div></th>
<th><div align="center">Total Debit</div></th>
</tr>
<?php
alldebt=0;
foreach($linvoice as $row): ?>
<input type="hidden" id="gcustomer" name="gcustomer[]" value="<?php echo $row['customerid']; ?>">
<?php
echo "<tr>";
echo "<td><div align=left>".$row['name'].".</div></td>";
echo '<td><input type="text" id="gpay" name="gpay[]" min="0" required style="width:100%;"></td>';
echo '<td align="right"><i class="fa fa-inr"></i> '.$row['totaldebit'].'</td>';
echo "</tr>";
$alldebt += $row['totaldebit'];
endforeach;
?>
<tr>
<th colspan="3"><div align="right">Total</div></th>
<th><div align="right"><i class="fa fa-inr"></i> <?php echo number_format($alldebt,2); ?></div></th>
</tr>
<tr>
<td colspan="6">
<div align="right">
<input type="submit" id="savePayment" value="Save Payment" class="btn btn-success">
</div>
</td>
</tr>
</table>
</form>
When I submit the form, it submits multiple times,i.e., paymentupdate.php runs multiple times. I want to run paymentupdate.php one time only. How do I solve this problem? Please help.
$(document).on("submit", "#mulpayment", function(e){
e.preventDefault();
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
}else{
alert(data.msg);
}
}
});
return false;
});
Try adding disable to your button after submitting your form. like for example
$(document).on("click", "#mulpayment", function(e){
e.preventDefault();
$(':input[type="submit"]').prop('disabled', true);
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
$(':input[type="submit"]').prop('disabled', false);
}else{
alert(data.msg);
}
}
});
});
in this way, it can prevent from clicking multiple times. you can enable back the button once the ajax request succeeds.
Try change button type="submit" for type="button":
$(document).on("click", "#mulpayment", function(e){
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
}else{
alert(data.msg);
}
}
});
});
And remove action and method attributes from the form tags, you dont need it if you use ajax:
<form id="aproveForm" class="smart-form" novalidate="novalidate">
<form id="mulpayment">
I am having a slight problem figuring out why this ajax response isn't updating properly. I have a php while loop which lists gallerys in text format, i am using . It is getting details from the php page but only for one result so essentially when you hover over the name a qtip tooltip box pops up so you can edit the name of the gallery. The problem is it only lists one result for all results in the loop.
PHP & HTML
<?php
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE UserID='".$_SESSION['user_id']."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$BaseHeight = 150;
$GalleriesBoxHeight = $BaseHeight + ( 20 * $MemberGalleriesCount );
echo '
<div id="ManageGalleries" style="height: '.$GalleriesBoxHeight.'px" align="center">
<div id="ManageGalleriesHeader">Manage Galleries</font></div><br><br>
<font color="#000000"><b>Click Gallery To Edit</b></font><br><br>
';
while($GalleryData = $MemberGalleriesQuery->fetch_assoc())
{
echo '>> <b><a class="EditGallery" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
}
echo '<br><br></div>';
}
$MemberGalleriesQuery->free();
?>
JAVASCRIPT:
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
$.ajax({ //Make the ajax request
url: link,
cache: false
}).done(function( html ) { //On complete run tooltip code
//Display tooltip code goes here, returned text is variable html
$('.EditGallery').qtip({
content: {
text: html
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$('.EditGallery').qtip('click', true);
$(".EditGallery").page();
});
});
CONTENTS OF Crowork.Backend/Crowork.EditGallery.php
if ( isset( $cleanGet['action'] ) && $cleanGet['action'] == 'EditGallery' ){
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE GalleryID='".$cleanGet['gallerykey']."' AND UserID='".$SessionUserID."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$GalleryData = $MemberGalleriesQuery->fetch_assoc();
}?>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<input type="hidden" name="GalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID']?>">
<input type="submit" name="DeleteGallery" value="Delete Gallery">
</form>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<table border="0" width="100%">
<tr>
<td colspan="2" align="center"><font size="-1"><b>NOTE:</b> Letters & Numbers Only</font></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="GalleryName" size="30" value="<?php echo $GalleryData['GalleryName']?>"></td>
</tr>
<tr>
<td align="right" colspan="2">
<input type="hidden" name="OriginalGalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID'] ?>">
<input type="submit" name="EditGallery" value="Edit Gallery">
</td>
</tr>
</table>
</form>
<?php }?>
PREVIEW:
http://www.bigjohn863.com/mini-upload-form/uploads/ajaxproblem.png
See how all three are the same results.
Try:
$('.EditGallery').each(function()
{
$(this).qtip({
content: {
text: "Loading...",
ajax: {
url:$(this).attr('href'),
type: "GET",
success: function(data, status) {
this.set('content.text', data);
}
}
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$(this).qtip('click', true);
});
http://jsfiddle.net/st0j8nLy/
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
....
everytime you are calling $('.EditGallery'). $('.EditGallery'). is an array, you need to change all references to $('.EditGallery') that is within the loop to $(this):
var link = $(this).attr('href'); //Gets link url
You Might be need to create dynamic id so you can call proper ajax.
please modify your ajax call as below
$gid=$GalleryData['GalleryID'];
echo '>> <b><a onclick="editgalary($gid)" id="EditGallery_$gid" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
replace this code in while loop.
function editgalary(galaryid){
var link = $('#EditGallery_'+galaryid).attr('href');
//ajax code as it is.
}
try and let me konw
I am trying to print the elements of an array in PHP which was passed from Javascript. I think the js array is being passed but for some reason it is not being printed via php. Sorry if my code is not properly indented. TIA
<?php
$link = mysqli_connect("localhost","xxxx", "xxxxxx","xxxx");
if($_POST['delete']){
$delete= json_decode($_POST['str'], true);
foreach($delete as $x){
echo"<script> alert(".$x.");</script>";
}
}
?>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body >
//This is a table which displays rows from a database.
//The user selects rows and the ids of those rows are
//are stored in a javascript array called 'toDelete'
//I want to pass this array to PHP
<form method="post" id="myForm" >
<table id="secondDiv" >
<tr>
<th >
<form><input class="checkbox"type="checkbox" name="selectAll" id="selecctall" value=""></form>
</th>
<th>Date</th>
<th>Event</th>
<th>Details</th>
<th>Time & Location</th>
</tr>
<?php
$link = mysqli_connect("localhost","xxxx", "xxxxxx","xxxx");
$query = "SELECT * FROM meetings";
if($result = mysqli_query($link,$query)){
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><form ><input class=\"checkbox1\" type=\"checkbox\" name=\"".$row['meetingNo']."\" >
</form></td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['event']."</td>";
echo "<td>".$row['details']."</td>";
echo "<td>".$row['location']."</td>";
echo "</tr>";
}
}
?>
</table>
<!-- <input type="submit" class="btn btn-warning" value="Edit" /> -->
<input type="hidden" id="str" name="str" value="" />
<input type="submit" id="btn" name="delete" value="Delete" />
</form>
<script>
var toDelete = new Array();
$(document).ready(function() {
$('#selecctall').click(function(event) { //on click
if(this.checked) { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
// JSON.stringify(toDelete);
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
toDelete.push(this.name);
}
return true;
}
);
$(document).ready(function(){
$("#btn").click( function() {
$.post( $("#myForm").attr("action"),
$('#str').val(JSON.stringify(toDelete))
);
});
$("#myForm").submit( function() {
return false;
});
});
</script>
</body>
</html>
As you are printing a string, not a javascript variable, you don't have quotes within alert call.
Change the line:
echo"<script> alert(".$x.");</script>";
With:
echo "<script> alert('$x'); </script>";
Or:
echo "<script> alert('".$x."'); </script>";
I have a html page with a drop down menu, The menu works and onchange calls a function popBox() that too works. Within the function i am using ajax to post the value of the drop down menu into php where it selects form the db. I wish to fill the textboxes in the form "DetailsForm" with the information selected. I currently fill no text boxes and the alert (msg) displays the whole html side of the page in and alert box. Could somebody please help me with my problem. I have tried multiple different variation of ajax and jquery to perform this and after 15hrs on the same function i am starting to get slight frustrated to say the least. Thanks in advance for any help, i do appreciate it.
Here is my code:
HTML
<head>
<link href="../UserTemplate.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Tours</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"> </script>
<script type="text/javascript">
function popBox(str)
{
$.ajax({
type: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
//document.getElementById("txt_Duration").value = <?php Print($Duration); ?>;
//document.getElementById("txt_Vessel_Name").value = <?php Print($Vessel); ?>;
//document.getElementById("txt_Location").value = <?php Print($Location); ?>;
//document.getElementById("txt_Available").value = <?php Print($Available); ?>;
//document.getElementById("txt_Price").value = <?php Print($Price); ?>;
}
</script>
</head>
<body>
<div id="MainDiv">
<div id="Header">
<div id="Logo"><img src="../Scotia Sea Life Logo.png" width="150px" height="110px" alt="Company Logo"/></div>
<div id="NavBar"><ul>
Home Tours About Donate Account
</ul>
</div>
<div id="Title">Tours</div>
</div>
<div id="Content">
<div id="Search">
<div id="SearchDiv">
<form id="SelectTourForm" style="margin:5px;">
<table border="0" align="center" width="100%">
<tr>
<td>
<label style="color:#FFF; font:Georgia, 'Times New Roman', Times, serif; font-size:20px; margin-left:10px; margin-top:25px">Select Tours Details</label></td>
</tr>
<tr>
<td><select name="lst_MonthDrop" style="background-color:#FF9933; color:#FFF; border:none; margin-top:10px; margin- left:10px;" onchange="popBox(this.value);">
<option>Please Select</option>
<?php
include 'populatedrodown.php';
foreach ( $results as $option ) : ?>
<option value="<?php echo $option- >Date; ?>"><?php echo $option->Date; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="btn_TourSearch" id="btn_TourSearch" value="Search" style="background:#009300; border-radius:5px; border-color:#009300; color:#FFF;margin-left:5px;" /></td>
</tr>
<tr>
<td></td>
</tr>
</table>
<p> </p>
</form>
</div>
</div>
<div id="DetailsDiv">
<div id="DetailsContent">
<form id="DetailsForm" >
<table border="0" align="center" width="100%">
<tr><td><label style="color:#FFF; font-size:14px;">Tour ID</label> <input type="text" id="Tour_ID" /> </td></tr>
<tr><td><label>Duration</label> <input type="text" id="txt_Duration" /> </td></tr>
<tr><td><label>Vessel Name</label> <input type="text" id="txt_Vessel_Name"/> </td></tr>
<tr><td><label>Location</label> <input type="text" id="txt_Location" /> </td></tr>
<tr><td><label>Date</label> <input type="text" id="txt_Date" /> </td></tr>
<tr><td><label>Available</label> <input type="text" id="txt_Available" /> </td></tr>
<tr><td><label>Price</label> <input type="text" id="txt_Price" /> </td></tr>
</table>
</form>
</div>
</div>
</div>
<div id="Footer">
<div id="FooterLinks"></div>
</div>
</div>
</body>
</html>
PHP
<?php
$q = $_POST['dat'];
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "pwd";
$mysql_db_database = "db";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
$sql="SELECT * FROM Tour WHERE Date = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$Duration = $row['Duration'] ;
$Vessel = $row['Vessel_Name'] ;
$Location = $row['Location'] ;
$Available = $row['Available'];
$Price = $row['Price'];
}
mysqli_close($con);
?>
Try to modify you JS code similar to this:
function popBox(selectValue) {
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: selectedValue },
success: function(serverResponse) {
// after success request server should return response with data
// that will be passed to this callback function as parameter
// and you can use it to fill text boxes:
$('#txt_Duration').val(serverResponse.duration);
}
});
}
Also you should modify your PHP code to return data in JSON:
// At the end you should return selected array. For example:
echo json_encode($dataArray); exit;
As you are using $_POST in your PHP code, you would need to edit the ajax call script.
Type is either GET or POST and page address comes in to the url attribute.
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
}
Following is code for username.php
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
$("#message").html("<img src='ajax-loader.gif' /> checking...");
var username=$("#username").val();
$.ajax({
type:"post",
url:"check.php",
data:"username="+username,
success:function(data){
if(data==0){
$("#message").html("Username available");
}
else{
$("#message").html("Username already taken");
}
}
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="id" id="username""/><td>
<td id="message"><td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="text" name="password" id="password" /><td>
</tr>
</table>
</body>
</html>
And the code for check.php
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['id']))
$username=$_POST['id'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
this code gives output as username and password boxes. I have included all the 3 files ajax-loader.gif, username.php and check.php in one single folder.On entering username no validation is performed. Can anyone help me to figure out why is this happening?
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username']))// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
Use data:"id="+username in Ajax request because that is the POST variable your checking in PHP.
Also on a side note:
Make sure you handle a case where $_POST['username'] is not set.
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username'])) {// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
} else {
echo "-1";
}
?>
And do not use mysql_* functions. They are deprecated. Use mysqli_* functions or PDO.