jquery $.post fails to send data on second request - php

I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.

you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.

Related

Using multiple forms to insert data to DB using Jquery & PHP without refreshing the page

I have working code for posting data to DB using PHP and Jquery without refreshing the page.
But however, I could only use 1 form with the given code, if I'm to add another form with different variables both the forms getting submitted.
My code goes as:
index:
Query starts
$countlikes = 1;
$countdislikes = 1;
<form data-id='<?= $countlikes?>' action="likeinsert" method="post" id="myform<?= $countlikes?>">
<input type="hidden" id="fid<?= $countlikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countlikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-toggle="tooltip" data-placement="right" title="Like" class="up"><i class="fa fa-thumbs-o-up"></i><?= $f_likes; ?></button>
</form>
<form data-id='<?= $countdislikes?>' action="dislikeinsert" method="post" id="myform<?= $countdislikes?>">
<input type="hidden" id="fid<?= $countdislikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countdislikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-placement="right" data-html="true" title="DisLike" class="down"><i class="fa fa-thumbs-o-down"></i><?= $f_dislikes; ?></button>
</form>
$countlikes ++;
$countdislikes ++;
Query Ends
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'likeinsert.php',
{
fid: $("#fid"+id).val(),
uid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'dislikeinsert.php',
{
fiid: $("#fid"+id).val(),
uiid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
When I to click on any form button, both forms are getting submitted.
It is happening, because you are adding two submit event listeners on both forms, so when you submit one form, both jquery scripts are getting executed.
To prevent this, add form's unique ids to your event listeners (in your case they are myform1 and myform1, but you should make them unique), somewhat like this:
$(document).on('submit','form#dislikesForm',function(e){
request to dislikeinsert.php ...
$(document).on('submit','form#likesForm',function(e){
request to likeinsert.php...

Php, codeigniter, ajax, mysql

I want to update record in the database with ajax without reloading the page.
//Here is my controller.
Public function changeid()
{
$this->view->('admin/change_id');
}
Public function ajax_changeid()
{
$old_id =$_POST[studentid];
$newid =$_POST[new_id];
If(isset($_POST[`new_id')){
$data =array(
'student_id'=>trim($newid));
$this->db->where('student_id', $old_id);
$this->db->update('student');
echo "info submited";
}
echo json_encode($data);
}
My view form change_id
<form id='formajax' method='post' name='form'>
<input type="text" id="studentid"
name="studentid" readonly="readonly"
value="<? php echo $row- >student_id; ?>" />
<input type="text" name="new_id" id="new_id" >
<input type="submit" id="btnsubmit"
value="Update" class="button success"
onclick="myFunction()" />
<\form>
// Ajax script
<script>
//ajaxForm({
//function myFunction(){
(document).ready(function(){
$("#btnsubmit").click(function(event){
event.preventDefault();
var stud_id =
document.getElementById("new_id").value;
var studentid =
document.getElementById("studentid").value;
var dataString = 'new_id1=' + new_id +
'$studentid1=' + studentid;
$.ajax({
type:"POST",
url:"<?php echo base_url()?
>"+"index.php/school_settings/ajax_changeid",
data:dataString,
cache:false,
success:function(html){
//alert(html);
alert('im working');
}
});
return false;
});
});
</script>
The challenge is the page keep reloading every time.
i click submit button without doing anything.
i want to be able to change id and get a success
message displayed without reloading d page.
You have some issues in your code, use this modified code:
Controller:
public function changeid()
{
$this->load->view('admin/change_id');
}
public function ajax_changeid()
{
$old_id = $_POST['studentid'];
$newid =$_POST['new_id'];
if(isset($_POST['new_id']))
{
$data =array(
'student_id'=>trim($newid));
$this->db->where('student_id', $old_id);
$this->db->update('student');
echo "info submited";
}
echo json_encode($data);
}
View:
<form id='formajax' method='post' name='form'>
<input type="text" id="studentid" name="studentid" readonly="readonly" value="<?php echo $row->student_id;?>"/>
<input type="text" name="new_id" id="new_id">
<input type="submit" id="btnsubmit" value="Update" class="button success" onclick="myFunction()"/>
</form>
What i have changed?
Change load view function as $this->load->view('admin/change_id'); instead of $this->view->('admin/change_id');
Change isset chekcing isset($_POST[`new_id') as isset($_POST['new_id']), you have missed the ending ] bracket and also using backticks (Dont know why)
Correct form ending tag <\form> as </form>
Remove onclick="myFunction()" event from button, because you are using button id for onclick event in ajax.

jQuery/js submit form on click

I can't submit the form after disable the submit button.
I make a jquery code to prevent multiple submit it's work but the form doesn't send the POST request.
jQuery:
$(document).ready(function() {
var enblereg = function(e) {
$(e).removeAttr("disabled");
}
$("#goRegister").click(function() {
$(this.form).submit();
var reg = this;
$('#reg').submit();
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
});
});
php:
<?php if (isset($_POST['goRegister'])) { echo "send";} ?>
<form action="?" method="POST" id="reg">
<h6>Full Name: <?php echo $fnamerr; ?></h6>
<input type="text" name="fname" value="<?php echo $fullname;?>">
<h6>Email: <?php echo $emailerr; ?></h6>
<input type="text" name="email" value="<?php echo $email;?>">
<h6>Re-enter Email: <?php echo $aemailerr; ?></h6>
<input type="text" name="aemail" value="<?php echo $aemail;?>">
<h6>password: <?php echo $passworderr; ?></h6>
<input type="password" name="password">
<h6>Re-enter password: <?php echo $apassworderr; ?></h6>
<input type="password" name="apassword">
<h6>Birthday: <?php echo $bdayerr;?></h6>
<?php include ("/incs/birthdayinc.php");?>
<h6>Gender: <?php echo $gendererr; ?></h6>
<input type="radio" name="gender" value="female"><font size="1"><b>Female</b></font>
<input type="radio" name="gender" value="male"><font size="1"><b>Male</b></font><br>
<input type="submit" name="goRegister" id="goRegister" value="Register">
</form>
without the jQuery the post work, I tried to solve it with "ONCLICK":
this.form.submit() - doesn't work
what should I need to add in jQuery to submit the form before disable the submit button ?
I think the jQuery code for the process would be like this
$(this.form).submit();
This would submit the form for you. If it doesn't actually trigger the event. Then you can capture the form and submit it directly using the id of it.
id="reg"
So, it would be
$('#reg').submit();
Do this... The form has id of #reg. So simply use $('#reg').submit();
$("#goRegister").click(function() {
var reg = this;
$('#reg').submit();
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
});
EDIT
Updated for ajax submit
$("#goRegister").click(function() {
var reg = $(this);
var form = $('#reg').serialize();
var url = "Whereveryouareposting.php";
//Submit ajax form
$.post(url,form,function(data){
//This is where you could send back error messages or success from the server
// To dictate wether to hide the button, or display errors.
// Ie On success....do this...
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
// On error, send a message packet with the errors, and loop through it to attach error
//messages to fields
});
});

Passing a value through Button to Php function

I am beginner in php and I am currently working on admin panel (you can see my admin panel page). The thing is that I want to pass serial number through these two buttons to perform further. But I can't find how to send $value to edit and delete a particular line.
<div id="headin2"><strong> <h3>Admin page </h3></strong></div>
<?php
echo "<table width=\"100%\" border=\"0\" id=\"tab\">";
echo "<tr>";
echo "<th id=\"td1\">Serial No</th><th id=\"td2\">Account Title</th>
<th id=\"td3\">Email</th><th id=\"td4\">Gender</th><th id=\"td5\">city</th>
<th id=\"td6\">Course</th><th id=\"td7\">status</th><th id=\"td8\" colspan=\"3\">Action</th>";
echo "</tr>";
while ( $row = mysql_fetch_array($query))
{
$SN = $row['SN'];
$actitle = $row['ac_title'];
$email = $row['email'];
$gender = $row['sex'];
$cite = $row['city'];
$course = $row['CRS'];
$status = $row['status'];
echo "<tr>";
echo "<td>".$SN."</td><td>".$actitle."</td><td>".$email."</td>
<td>".$gender."</td><td>".$cite."</td><td>".$course."</td><td>".$status."</td>
<td>"."<input type=\"button\" name=\"edit\" value=\"Edit\"/>
<input type=\"button\" value=\"Delete\" name=\"delete\" >"."</td>";
echo "</tr>";
}
?>
</table>
You need both the action (edit/delete) and the row id. Unfortunately, without some JS the button will only post one value.
You can create a new form for each row, add in a hidden element. For example:
<?php while ($row = mysql_fetch_array($query)) : ?>
<tr>
<!-- other cells -->
<td>
<form method="post" action="">
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Update"/>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>"/>
</form>
</td>
</tr>
<?php endwhile; ?>
Then after posting it you can just check for the action and id
if ($_POST['action'] && $_POST['id']) {
if ($_POST['action'] == 'Edit') {
// edit the post with $_POST['id']
}
}
You can do it one of two ways.
jQuery and AJAX
For each <tr>, everywhere there is a delete button,
Delete
Script at the bottom:
//Include jQuery here
<script language="javascript">
$('.delete-row').click(function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
url: "url/to/delete",
method: "POST",
cache: false,
data: { id: id },
success: function (html) {
$(this).parent().parent().remove();
});
});
});
</script>
This puts the ID of the row into the <a href> itself using data and uses jQuery to send out an AJAX call to delete the record. If the delete is successful, it removes the row from the table.
Old-School Button
For each <tr>, everywhere there is a Delete button,
<form method="POST" action="url/to/delete">
<input type="hidden" name="id" value="<?php echo $value; ?>" />
<input type="submit" value="Delete" />
</form>
This is the old-school way to do it, where the hidden field is how the backend knows which row to delete.
On the backend, you still use $_POST['id']; to get the ID of the record to remove. In the above examples, $value is the ID for each row, and is most likely something like $row['id'] when it is coming from a foreach().
Use a hidden input (e.g.<input type="hidden" value="your_value_here">)
when you click Edit it open a page with corresponding record. You can do it by a Edit link or a image or a button.
<?php echo "<a href='".BASE_URL."admin/edit.php?id=$id' target='_blank'> <img src=".BASE_URL."/images/edit.png width=16 height=16 alt=Edit /> </a>";?>
for delete you can use jquery. here is a example
echo "<a href='#' onclick='deletePrescription($id)' ><img src=images/document_delete.png width=16 height=16 title='Delete Prescription' alt=Delete /> </a>";
<script type="text/javascript">
function deletePrescription(checkup_id) {
//alert(checkup_id);
var agree=confirm("Do you really want to delete the prescription?");
if (agree)
{
$.ajax
({
type: "POST",
url: "delete_prescription_admin.php",
data: "checkup_id="+checkup_id,
success: function(msg)
{
//
//alert( "array Updated: " + msg );
location.reload(true);
}
});
}
else
{
return false ;
}
}
</script>
PHP is on the server side, so you need to send parameters, parse it and have your php act.
i.e.
The edit button will make POST or GET request with parameter: id=123&action=edit
and your PHP will parse the Query String:
$strID = $_GET['id'];
$strAction = $_GET['action'];
then act on it..
if ($strAction=='edit'){
// do something...
}
Your buttons should be wrappen in a form like:
<form action="yourFile.php?id=<?=$SN ?>&action=edit" method="GET" id="formEdit<?=$SN ?>">
<button type="submit" value="Edit">
</form>
<a href=register_course.php?id=$roll&code=".$row['course_code']."&name=".$row['course_name']."><input type=submit value=Register>
*here register_course.php is the file where you are sending some variable having some data it will be delivered when button is clicked whose value is register //course code is the variable you want to send ... im assigning its value as $ code... and assigning id $roll as id and assigning course_name as $name....
the other file will get the variables having some data

PHP/jQuery: Ajax call & where to have my code?

So im making a "delete" button to my commentsystem..
I want to make it smart, so it should run a ajax call to remove the comment.
Now I have tried out myself, this and have gotten this far:
<?php
echo "<a href='#' onclick='javascript:DoCommentWallRemove()' title='ta bort inlägg'> <span class='removeWallComment'></span> </a>";
?>
<script type="text/javascript">
function DoCommentWallRemove(){
var wrapperId = '#profileWall';
$.ajax({
type: "POST",
url: "misc/removeWallComment.php",
data: {
value: 'y',
commentwallid : "<?php echo $displayWall['id']; ?>",
BuID : "<?php echo $v['id']; ?>",
uID : "<?php echo $showU['id']; ?>"
},
success: function(msg){
alert(msg);
}
});
}
</script>
Now as my comments shows in a while(), I have placed the JS function is right under the link, so it should grab the actual comment id, but instead it gives the same ID to every comment.
But when i do a normal php <?php echo $displayWall['id']; ?> it shows different comment ids like it should do in the javascript.
I would suggest a similar solution to GuidoH, but with a few minor changes.
PHP Code for the Comment Thread:
<form method="post" action="misc/removeWallComment.php">
<input type="hidden" name="value" value="y" />
<input type="hidden" name="BuID" value="<?php echo $v['id']; ?>" />
<input type="hidden" name="uID" value="<?php echo $showU['id']; ?>" />
<div id="commentList">
<?php
foreach( $comments as $c ){
echo '<div id="comment'.$c['id'].'">';
echo $c['commentBody'];
echo '<input class="delButton" type="submit" name="'.$c['id'].'" value="Delete Comment" />';
echo '</div>';
}
?>
</div>
</form>
This will render as:
<form method="post" action="misc/removeWallComment.php">
<input type="hidden" name="value" value="y" />
<input type="hidden" name="BuID" value="ThisIsThe_BuID" />
<input type="hidden" name="uID" value="ThisIsThe_uID" />
<div id="commentList">
<div id="comment001">
This is Comment Number One
<input class="delButton" type="submit" name="001" value="Delete Comment" />
</div>
<div id="comment002">
And, This is Comment Number Two
<input class="delButton" type="submit" name="002" value="Delete Comment" />
</div>
</div>
</form>
In the Javascript for the page holding the Comment thread:
<script>
$(document).ready(function(){
/* Add a Handler for the Delete Button */
$('div#commentList input.delButton').click(function(e){
/* Stop the Link working */
e.preventDefault();
/* Alias the main jQuery Objects */
$this = $(this);
$comment = $this.closest('div');
$form = $comment.closest('form');
/* Grab the Comment Number from the Button's NAME attribute */
commentID = $this.attr('name');
/* Perform the AJAX Action */
$.ajax({
url : $form.attr('action') ,
type : 'POST' ,
data : {
'value' : $form.find( 'input[name="value"]' ).val() ,
'commentwallid' : commentID ,
'BuID' : $form.find( 'input[name="BuID"]' ).val() ,
'uID' : $form.find( 'input[name="uID"]' ).val() ,
'mode' : 'ajax'
} ,
dataType : 'text' ,
complete: function( XHR , status ){
if( $.trim(status).toLowerCase()=='success'
&& $.trim(XHR.responseText).toLowerCase()=='comment deleted' ){
/* Success - Hide, then Remove the Comment */
$comment.hide().remove();
}else{
/* Something Went Wrong */
alert('Deleting Comment #'+commentID+' Failed');
}
}
});
});
});
</script>
In the misc/removeWallComment.php file:
if( $_POST['mode']=='ajax' ){
/* Perform the Action. Return 'Comment Deleted' is Successful */
}else{
/* This is to Extract the Comment ID from the "Delete Comment" button */
$_POST_REV = array_flip( $_POST );
$_POST['commentwallid'] = $_POST_REV['Delete Comment'];
/* Perform the Action.
Return the Full Page, or Redirect, you want Non-Javascript Users to See. */
}
NOTE:
This advice is based on the assumption he BuID and uID variables are the same for any delete action performed by the user from the same page.
Edited:
Updated to provide Graceful Degradation in the event that the user does not allow Javascript to run, and to extract a number of variables from the HTML FORM, (rather than have to code them in twice).
Eww, that's just gross! You probably want something like this:
function removeComment(id, obj) {
$.post('misc/removeWallComment.php', {id: id}, function(msg) {
alert(msg); // or do some useful stuff,
// like remove the comment from the page
// with 'obj' you'll know which comment to remove :)
});
}
And then just something like this for each comment:
delete comment

Categories