Prevent the default action when using jQuery for Ajax - php

I'm trying to prevent the default action when submitting a form with ajax but I believe I have my code wrong as the page seems to do a 'refresh' and the form clears but nothing is sent to the database. I tried adding the link to the php processing script in the 'action' part of the form and it does submit fine to the database so the problem seems to be with my jQuery code.
<script type="text/javascript">
$(document).ready(function(e){
e.preventDefault();
$("#rpack_add_form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $("#rpack_add_form").serialize(), function(data) {
$('#ajaxResult').html(data);
});
}
});
});
</script>
My form code:
<div id="rpacks_admin" style="display: none;">
<h5>Add A New Recovery Pack</h5>
<form id="rpack_add_form" class='small_form' name='rpack_add_form' action='' method='post'>
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for content</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for contentrm</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add' name='add_rpack'>
</form>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
and my PHP if needed
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
include_once 'bcrypt.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if password and username has been submitted then add to DB
if (empty ($number))
{
echo "You need to enter a recovery pack number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}

The .validate() object has a sendForm parameter. It is set to true by default, but you need to set it to false, as in the code below, to prevent the form from being submitted:
$(document).ready(function () {
$('#rpack_add_form').validate({
submitHandler: function (form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $('#rpack_add_form').serialize(), function (data) {
$('#ajaxResult').html(data);
});
},
sendForm: false
});
});
You can reference the docs for more info.

Related

Why does my submit button not submit to mySQL?

I have a php form I'll call it "php1" that uses ajax to populate the input text boxes from a mySQL db. to do so it uses a secondary page I'll call "php2". On php2 there is a submit "button" being used to submit any changes to the mySQL db. Every aspect works beautifully, except the submit, unless I test php2 by itself, then it submits to the db.What am I doing wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function myBlur(str){
if (str == "") {
document.getElementById("demo").innerHTML = "You Must Enter a Device Name! <br>";
$("#demo").css("background-color","red");
$("#Name").css("background-color","red");
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("form1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","php2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
This is to call the second page.
<fieldset><legend>Input</legend>
<div width="100%" id="form1">
<div id="demo"><br></div><br>
<form method="post" action="php1.php">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="<?php echo $Name ?>" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="<?php echo $MAC ?>">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="<?php echo $Own ?>">
Type: <select name="Type" id="Type" required="required" readonly="true" value="<?php echo $Type ?>">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
</form>
That is the form code from php1
$sql = "SELECT * FROM $table WHERE Name = '$q'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$N=$row["Name"];
$MA=$row["MAC"];
$Ow=$row["Own"];
$Ty=$row["Type"];
echo "<tr>";
echo "<form method='post' action='php1.php' id='UpAss'>",UpAss,"
<br><br>
Device Name: <input type='text' id='Name' name='Name' value=".$N." onBlur='myBlur(this.value)'>
MAC Address: <input type='text' id='MAC' name='MAC' readonly='True' autocomplete='off' value=". $MA.">
Owner or Location: <input type='text' id='Own' name='Own' value=". $Ow.">
Type: <select id='Type'>
<option value='".$Ty."'>". $Ty."</option>
<option value='Desktop'>Desktop</option>
<option value='Laptop'>Laptop</option>
<option value='Server'>Server</option>
<option value='Monitor'>Monitor</option>
<option value='Printer'>Printer</option>
<option value='Phone'>Phone</option>
<option value='iPhone'>iPhone</option>
</select>
echo "<input type='submit' id='Usubmit' value='Update Asset' form='UpAss' onClick='myUpdate()'></input></form>";
}
function myUpdate()
{
// Create connection
$connU = new MySQLi($db_host, $db_user, $db_pass, $db_name, $db_port);
// Check connection
if ($connU->connect_error) {
die("Connection failed: " . $connU->connect_error);
}
$Name = ($_POST["Name"]);
$MAC = ($_POST["MAC"]);
$Own = ($_POST["Own"]);
$Model = ($_POST["Model"]);
$OS = ($_POST["OS"]);
$Type = ($_POST["Type"]);
$sqlU = "REPLACE INTO SET $table SET MAC='$MAC', Own='$Own', Type='$Type' WHERE Name=$Name;";
if ($connU->query($sqlU) === TRUE) {
echo "PPC-".$Name." Has Been Updated!";
} else {
echo "Error: " . $sqlU . "<br>" . $connU->error;
}
$connU->close();
}
if(isset($_POST['Usubmit']))
{
myUpdate();
}
?>
And that is the code to load the form from php2 in to php1. I am sure it is something simple that I am missing and would appreciate any help. all this code works great, but the submit.
*(I left the DB information out of this code on purpose.)
1.) For Posting(Insert, update and delete via ajax)
This will get you started on how to post via ajax jquery. you can see comments on the code
You can also see that form parameter is set to id="add_content" which is refrenced in the jquery ajax call
<form method="post" id="add_content">
you can also see in the body of the html div that shows image loader when button is click and when result from backend is displayed hence
see sample on that
post.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#add_content').on('submit', function(e){
e.preventDefault();
alert('ok');
// display a loading image and message
$('#loader').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'post.php',
data:$(this).serialize(),
crossDomain: true,
cache:false,
success:function(msg){
// hide loader to display result
$('#loader').hide();
$('#showposts').fadeIn('slow').prepend(msg);
}
});
});
});
</script>
</head>
<body>
<div id="loader"> </div>
<div id="showposts"> </div>
<form method="post" id="add_content">
Asset Number: <input type="text" required="required" id="Name" name="Name" autocomplete="off" autofocus="true" value="100" onChange="myBlur(this.value)">
MAC Address: <input type="text" id="MAC" name="MAC" autocomplete="off" value="1001">
Owner or Location: <input type="text" id="Own" name="Own" readonly="true" value="nancy read only">
Type: <select name="Type" id="Type" required="required" readonly="true" value="nancy type">
<option value=""></option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Server">Server</option>
<option value="Monitor">Monitor</option>
<option value="Printer">Printer</option>
<option value="Phone">Phone</option>
</select>
<br>
</div>
</fieldset>
<input type="submit" name="add" id="add" value="Add" />
</form>
</body>
example of post.php
<?php
// use strip_tags to avoid html injection that can also leads to xss attck
// sample with assets number
$asset_number= strip_tags($_POST['Name']);
$MAC= $_POST['MAC'];
$Own= $_POST['Own'];
$Type= $_POST['Type'];
// you can check for emptiness eg.
if($asset_number ==''){
echo "asset number is empty";
exit();
}else{
echo "success. my assests no is: $asset_number";
}
?>
sample 2.
if you want fetch records only with or without sending parameters, you can try
Remember to pass jquery library (jquery.min.js) if you are calling it from another page
<script>
$(document).ready(function(){
// set variable payload for formality. though you can pass it to backend as a variable
var payload= 'Am Nancy Mooree';
var datasend = "payload="+ payload;
$('#loader1').fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Please Wait.. submiting form..</span>');
$.ajax({
type:'POST',
url:'showresult.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader1').hide();
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
<div id="loader1"></div>
<div id="listposts"></div>
showresult.php
<?php
// assuming you are sending a post or get variables to query database
$payload= strip_tags($_POST['payload']);
// query your database to display result to ajax.
echo $result ="Am from database where payload is: $payload";
?>

Submit page but dont refresh

I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php

How to get the values from a submitted do...while form

I have the following code with a form inside a list that should submit the element through Ajax. The values in the form is repeated through a do ... while loop, so that the list become a dynamically list, like in this picture:
But when I click a button, the only element that is sent through the Ajax code is the value of the last button, even though I click on Oranges for example.
The code is as follow:
<script>
function submitForm() {
$.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#MyJobsForm').serialize(), success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}});
return false;
}
</script>
</head>
<body>
<ul id="btn_MyJobs" data-role="listview" data-inset="true">
<li id="MyJobs_List" class="push">
<form id="MyJobsForm" onsubmit="return submitForm();">
<?php do { ?>
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</form>
</li>
</ul>
<div id="myJobs_Right">
<div class="form_result"> </div>
</div>
</body>
The jQuery-ajax-demo.php page looks like this:
<?php
if(isset($_POST['name'])) {
$name = $_POST['name'];
?>
Your Name Is: <?php echo $name; ?><br />
<?php
die();
}
?>
If you have to do it this way, then you might try creating a new form for each button:
<?php do { ?>
<form onsubmit="return submitForm(this);"> <!--Note I added "this" -->
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
</form>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Then the only value that will get posted will be the hidden value that is in the form whose button you clicked. I updated the onsubmit call above to include this in the call. So you can do the below in your function:
function submitForm(form) {
var $form = $(form);
$.ajax({
type:'POST',
url: 'jQuery-ajax-demo.php',
data:$form.serialize(),
success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}
});
return false;
}

jQuery Ajax not submitting data

I decided to have my first go with ajax to submit my data but I'm having problems. The form seems to reset but no data is sent to the database, I'm probably missing something obvious here:
jQuery (currently included in the header of my file)
<script>
// jQuery to submit form data via AJAX to add a recovery pack
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}}
</script>
The PHP/HTML form
<form id="rpack_add_form" class='small_form' name='rpack_form' method='post' onsubmit="return submitForm();">
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for 2nd form at a later date</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for 3rd form at a later date</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add Recovery Pack' name='add_rpack'>
</form>
<div class="form_result"> </div>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
The PHP for addrpack.php (this code works fully when I remove the ajax part from above and just submit as normal)
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if a number has been entered
if (empty ($number))
{
echo "You need to enter a number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}
Probably a syntax error - missing );
$('#rpack_add_form').submit(function(){
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}
});
return false;
});
$.ajax({
type:'POST',
url: 'addrpack.php',
data:{"data":$('#rpack_add_form').serialize()},
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}
});//Syntax misatke
Not sure what your onsubmit="return submitForm();" in form does but you have to stop the submit button from sending the data and instead make it use your ajax function.
$(function(){
$('.button').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response) {
$('#rpack_add_form').find('.form_result').html(response);
}
});
});
});

Update div on AJAX submit jQuery is updating all divs

I'm trying to update a div with an ajax post. Problem is...it's updating every div.
Here's the json.php:
//json.php
$data['months'] = $db->escape_value($_POST['check']);
$data['id'] = $db->escape_value($_POST['hidden']);
$query = "UPDATE month SET months = '{$data['months']}' WHERE monthID = '{$data['id']}'";
$result = $db->query($query);
if($result) {
$data['success'] = true;
$data['message'] = "Update Successful!";
$data['text'] = $_POST['check'];
echo json_encode($data);
} else {
$data['message'] = "Update could not be completed.";
}
And the html:
<?php
$query = $db->query('SELECT * FROM month');
?>
<html>
<head>
<title>jQuery/Ajax - Update is updating all divs</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.check, button.save, input.cancel, div.message").hide();
$(".edit").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").hide();
$(this).parent().siblings("li.liThree").children("button.save").show();
$(this).parent().siblings("li.liFour").children("input.cancel").show();
$(this).parents("ul").siblings("div.showText").hide();
$(this).parents("ul").siblings("input.check").show();
$(this).hide();
return false;
});
$(".cancel").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").show();
$(this).parent().siblings("li.liThree").children("button.save").hide();
$(this).parent().siblings("li.liOne").children("input.edit").show();
$(this).parents("ul").siblings("div.showText").show();
$(this).parents("ul").siblings("input.check").hide();
$(this).hide();
return false;
});
$("form[name=form1]").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText").html(data.text);
$(".message").html(data.message).slideDown("fast");
$(".check").hide();
$("button.save").hide();
$(".cancel").hide();
$(".edit").show();
$(".delete").show();
$(".showText").show();
return false;
}
}, "json");
return false;
});
});
</script>
</head>
<body>
<div class="message">message</div>
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
<div class="container">
<div class="showText"><?php echo $row['months']; ?></div>
<input name="check" type="text" class="check" value="<?php echo $row['months']; ?>" />
<input name="hidden" type="hidden" class="hidden" value="<?php echo $row['monthID']; ?>" />
<ul class="list">
<li class="liOne">
<input name="edit" type="button" class="edit" value="edit" />
</li>
<li class="liTwo">
<input name="delete" type="submit" class="delete" value="delete" />
</li>
<li class="liThree">
<button name="save" type="submit" class="save" value="<?php echo $row['monthID']; ?>">save</button>
</li>
<li class="liFour">
<input name="cancel" type="button" class="cancel" value="cancel" />
</li>
</ul>
</div>
</form>
<?php } ?>
<!--<a id="reset" href="test3.php">reset</a>-->
</body>
</html>
You need to specify a context (the form) for the elements you're changing:
$("form[name=form1]").submit(function(){
var form = this;
var params = $(this);
$.post(form.action, { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText", form).html(data.text);
$(".message", form).html(data.message).slideDown("fast");
$(".check", form).hide();
$("button.save", form).hide();
$(".cancel", form).hide();
$(".edit", form).show();
$(".delete", form).show();
$(".showText", form).show();
return false;
}
}, "json");
return false;
});
Also, if you hide a parent element, the children are hidden, too, so you probably want to do that...
Every div has the same class: showText. They need unique IDs instead, like Div1, Div2. Then update them by their ID: $("#Div1")
Hint, instead of answer:
How many elements does $(".showText") return?
2nd Hint: It's more than one!
===
Edit for more clarity:
The first issue is that you're selecting by classes like .showText. But you're creating multiple forms, each of which has an element that matches .showText. You need some way to point at the right element in each form. One way to solve this is to add an ID on each FORM tag, so you can then select things like $('#form-number-$N .showtext) -- which selects any elements with class="showtext" inside the element with id "#form-number-$N"
You're looping over rows in your database and writing the forms. So you need some variable data to identify each individual form.
You've got a while loop that populates $row:
<?php while($row = $db->fetch_assoc($query)) { ?>
But currently, every form you create has a name attribute of "form1".
So what if, instead of:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
You did something like:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form<?PHP echo $row['id']; ?>" id="<?PHP echo $row['id']; ?> class="myFormClass" method="post">
Then you could use a handler that looks something like:
$("form.myFormClass").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(this.id + " .showText").html(data.text);
...
return false;
}
}, "json");
return false;
});
Do you see what's happening there?

Categories