I am extracting sql data to a another php table used for a site. For each row in the table I have a button to delete or edit that specific row. The edit button works fine but I have been having issues with the delete button. As of now the delete button only deletes the first row of the table and not the row that has been selected for deletion.
Here is a sample of the table:
while($row = mysqli_fetch_array($result)){
<tr>
<td>'.($row['some_data']).'</td>
<td>
<form action="meeting_update_milestone.php" method="POST">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="submit" value="EDIT" />
</form>
</td>
<td>
<form id="meeting_delete_item">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="button" onclick="delete_meeting_item()" value="DELETE" />
</form>
</td>
</tr>';
}
This data is being sent to an ajax call:
function delete_meeting_item(){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: $('#meeting_delete_item').serialize(),
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
As you can tell I loop through the rows creating multiple forms with the same id. I think this is creating the issue here? If so how can I fix it by keeping the same formatting. I believe the forms have to have a unique name, but I am not sure how to implement this into the ajax data string.
I can't comment on the validity of your php code, but as you say, the id values have to be unique. In this instance, I don't believe the ID really makes much difference to what you are trying to achieve.
Remove the id and the inline onclick event:
while($row = mysqli_fetch_array($result)){
<tr>
<td>'.($row['some_data']).'</td>
<td>
<form action="meeting_update_milestone.php" method="POST">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="submit" value="EDIT" />
</form>
</td>
<td>
<form>
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="button" class="delete" value="DELETE" />
</form>
</td>
</tr>';
}
And bind it using jQuery. I added a class to be able to get a selector to the delete button.
$(document).ready(function(){
$('.delete').click(function(){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: $(this).closest(form).serialize(),
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
}
On click of the delete button, we get the nearest form and serialize the data for that form.
Your problem is here
$('#meeting_delete_item').serialize()
You should use something else to determine that the current line is.
HTML FORM PART FOR DELETE
<form id="meeting_delete_item">
<input type="button" onclick="delete_meeting_item('.$row['id'].')" value="DELETE" />
</form>
JS
function delete_meeting_item(deleteId){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: {mile_id: deleteId},
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
Outside of your loop, you can keep a counter: $x = 0 and use that when generating the form: <form id="meeting_delete_item"'.$x.'>. At the end of the loop, increment the counter for the next iteration ++$x. In your javascript, you will probably retrieve the id according to the button that is pressed.
Sample Forms:
<form id="myForm1">
<button>Click me!</button>
</form>
<form id="myForm2">
<button>Click me!</button>
</form>
Sample JavaScript:
$('form button').click(function(e) {
var $form = $(this).closest('form');
console.log($form.attr('id'));
return false; //stop form submission
});
Live demo (click).
Also, inline js (like onclick in your html) has never been good practice. Instead, follow the example in my sample code and bind the click function with javascript. For more on this subject, read some of these results: https://www.google.com/search?q=Why+is+inline+js+bad%3F
Related
HTML
<input type="checkbox" name=options[cid]" value='1'
onChange="chkdeptCount(this.value)" class="test">
<input type="checkbox" name=options[cid]" value='2'
onChange="chkdeptCount(this.value)" class="test">
jquery:
function chkdeptCount(val){
$.ajax({ url: '../ajax/AjaxCall.php',
data: {Action:'IMPLODEARRAY',arrVal: val},
type: 'post',
success: function(output) {
alert(output);
$('.result').html(output);
}
});
}
PHP:
if($_POST['Action']=='IMPLODEARRAY'){
$arr_val[] = $_POST['arrVal'];
print_r($arr_val);
}
When I run this code does not return array value. It returns a single value WHY?
Note that, you are missing the quote here name=options[cid]".
And you are using onChange="chkdeptCount(this.value)" event with current value this, this will only return one value at once.
This is very basic Example:
HTML:
<form method="post" id="formID" action="">
<input type="hidden" name="Action" value="IMPLODEARRAY">
<input type="checkbox" name="options[cid]" value='1' class="test">
<input type="checkbox" name="options[cid]" value='2' class="test">
<input type="submit" name="submit" value="Submit" id="SubmitButton">
</form>
AJAX:
<script type="text/javascript">
$(document).ready(function(){
$("#SubmitButton").click(function(){ // when submit button press
var data = $("#formID").serialize(); // get all form input in serialize()
$.ajax({
url: YourURL, // add your url here
type: "POST", // your method
data: data, // your form data
dataType: "json", // you can use json/html type
success: function(response) {
console.log(response); // your response
},
beforeSend: function()
{
// if you want to display any loading message
}
}); // JQUERY Native Ajax End
return false;
});
});
</script>
PHP:
<?php
if(count($_POST) > 0){ // if you have some value in AJAX request
if($_POST['Action'] == 'IMPLODEARRAY'){ // your condition
print_r($_POST['options']); // get all checkbox value.
}
}
?>
Few more example will help you to understand, you can you use: Submitting HTML form using Jquery AJAX |
jQuery AJAX submit form
I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });
I've been racking my brains for days looking at examples and trying out different things to try and get my form to submit with Ajax without a page refresh. And Its not even sending the data now.. I don't know what I'm doing wrong..Can someone run through my ajax and form please.
Toid is the users id and newmsg is the text in which the user submits. The two values get sent to the insert.php page.
I would really appreate the help. I'm new to Ajax, and I look at some of it and don't have a clue. If I finally got it working, It may help me realize what I've done wrong. I am looking up tutorials and watching videos..but it can be very time consuming for something that would be simple to someone in the know on here. It maybe that I've got the wrong idea on the ajax and it makes no sense at all, sorry about that.
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
homestatus()
event.preventDefault();
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
});
return false;
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
</div>
</form>
INSERT.PHP
$user1_id=$_SESSION['id'];
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&isset($_POST['toid'])){
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
}else{
rawfeeds_user_core::create_streamitem("3",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
Try using firebug to identify bugs in your code. It's a really good companion for developing javascript. Nearly all of your bugs led to error messages in the firebug console.
You had several errors in your code, here is the corrected version:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){alert('success');}
});
});
});
And here the corrected html:
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
Actually onsubmit event has to be used with form so instead of
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
it could be
<form id="myform" method="POST" class="form_statusinput" onsubmit="homestatus();">
and return the true or false from the function/handler, i.e.
function homestatus()
{
//...
if(condition==true) return true;
else return false;
}
Since you are using jQuery it's better to use as follows
$("form#myform").on('submit', function(event){
event.preventDefault();
var toid = $("#toid").val(); // get value
var content = $("#newmsg").val(); // get value
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + toid + "&newmsg=" + content,
success: function(data){
// do something with data
}
});
});
In this case your form should be as follows
<form id="myform" method="POST" class="form_statusinput">
...
</form>
and input fields should have a valid type and value attribute, Html form and Input.
I think you should read more about jQuery.
Reference : jQuery val and jQuery Ajax.
change the form to this
<form id="myform" ... onsubmit="homestatus(); return false">
you don't need the onsubmit attribute on the submit button, but on the form element instead
homestatus might be out of scope
function homestatus () {
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
}
This isn't tested, but try this (I annotated some stuff using comments)
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
// not sure what this does, so let's take it out of the equation for now, it may be causing errors
//homestatus()
// needed to declare event as a param to the callback function
event.preventDefault();
// I think you want the value of these fields
var toid = $("#toid").val();
var content = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+toid +"&newmsg="+ content,
success: function(){
}
});
return false;
});
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" / >
</div>
</form>
It's a lot easier to let .serialize() do the work of serializing the form data.
The submit handler also needs event as a formal parameter, otherwise an error will be thrown (event will be undefined).
With a few other changes, here is the whole thing:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
homestatus();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: formData,
success: function(data) {
//...
}
});
});
});
</script>
<form id="myform" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" >
</div>
</form>
Unless you are omitting some of your code, the problem is this line:
homestatus()
You never defined this function, so the submit throws an error.
You may want to take a look at jQuery (www.jquery.com) or another js framework.
Such frameworks do most of the stuff you normally have to do by hand.
There are also a bunch of nice helper functions for sending form data or modifying html elements
<form name="ipladder" id="ipladder" action="/checkuser/master-check.php" method="post">
<input name="ipladder" type="text" id="ipladder" />
<input type="submit" name="submit" id="botton" value="Check" />
<input type="submit" name="geo" id="botton"/>
</input></form>
I have one input box and 2 submit buttons. When the first button is pressed (name="submit") I want it to go to master-check.php as specified in the action= parameter. However when the geo button is pressed, I want it to go through a different action which I haven't specified because I didn't know how to do so.
What can I do so I can have 1 input box and 2 buttons each processing through different action files?
Maybe you can try altering the "action" parameter of your form in an onclick method that, after changing, submits the form. Something like:
$('#btn1').click(function(){
$('#ipladder').attr('action', 'location1.php');
$('#ipladder').submit();
});
$('#btn2').click(function(){
$('#ipladder').attr('action', 'location2.php');
$('#ipladder').submit();
});
Another option of couse, is to post to 1 page...and handle the logic (some redirect or whatever) there.
Make a single PHP script that handles which button has been pressed and then redirects to correct PHP handling script (after correcting what Juhana commented of course).
Instead of using form action, I think you can use Ajax to achieve what you want. It will be something like this:
<form name="ipladder" id="ipladder" method="post">
<input type="text" id="ipladder2" name="ipladder2" />
<input type="button" id="button1" name="submit" value="Check" onclick="action1()" />
<input type="button" id="button2" name="geo" value="Something else" onclick="action2()" />
</form>
and in the header you can define 2 Ajax functions:
<script type="text/javascript">
function action1()
{
$.ajax({
type: "POST",
url: "/checkuser/master-check.php",
data: $("ipladder2").val(),
success: //do something,
dataType: //return dataType
});
}
function action2()
{
$.ajax({
type: "POST",
url: //other URL,
data: $("ipladder2").val(),
success: //do something else,
dataType: //return dataType
});
}
</script>
Well you can achieve your goal by single php page as well.
on mastercheck.php something like this can help you.
<?php
if($_POST['submit'])
{
//you code for master-check.php
}
else if(isset($_POST['geo']))
{
//you code for other page goes here
}
?>
I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:
Here is my jQuery:
<script type="text/javascript">
function processForm() {
var action= $('#action').val();
var data = $('#data').val();
var dataString = 'action=' + action + '&data=' + data;
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
}
</script>
Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)
<form action="" method="post" onsubmit="processForm();return false;">
<input type="hidden" name="action" value="action1" />
<input type="text" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Here is my PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!
SOLUTION (via Jen):
jQuery:
<script type="text/javascript">
function processForm() {
var dataString = $("#yourForm").serialize();
$.ajax ({
type: 'POST',
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
</script>
HTML:
<form id="yourForm">
<input type="hidden" name="action" value="action1" />
<input type="text" id="data" name="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
What I learned: Use the .serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and .serialize() does not typically make mistakes sending the info to php.
Give this a try:
$("#yourForm").submit(function(){
// Could use just this line and not vars below
//dataString = $("#yourForm").serialize();
// vars are being set by selecting inputs by id but id not set in form fields
var action= $('#action').val(); // value of id='action'
var data = $('#data').val(); // value of id='data'
var dataString = 'action=' + action + '&data=' + data;
// dataString = 'action=&data=' so nothing is posted to db
// because input fields cannot be found by id
// fix by adding id fields to form fields
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
And change the form to (I added the id attributes):
<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:
When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="", which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.
When you put return false; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET) to a processing file, not '.'
Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.
Hope this small hint helps (: