I am using a button to submit a form with ajax..all works fine..But I need to check if the button is clicked in server side page..How to do it??Any help appreciated..Thanks..
<form>
some values
</form>
<input type="button" name="delete" id="delete" value="Delete"/><br/>
<input type="button" name="edit" id="edit" value="Edit"/><br/>
Script
$("#edit").click(function(event) {
event.preventDefault();
$("#form1").submit()
});
$("#form1").validate({
debug: false,
rules: {
plid:"required",
},
messages: {
plid: "Please select a pack name id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "aanew.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
I want to carry any attribute to check if my button is set... Thanks again..
The form value passes successfully, but I need to check the button status in another page..
First of all your buttons in page should be in form tag like this
<form>
some values
<input type="button" name="delete" id="delete" value="Delete"/><br/>
<input type="button" name="edit" id="edit" value="Edit"/><br/>
</form>
then Simply just use isset function
if (isset($_POST['delete']))
or
if (isset($_POST['edit']))
whatever you click
Put this field on the form, and the other inputs too like others have already pointed
<input type="hidden" name="check_click" value="1">
then in server side
if ((isset($_POST['check_click'])) && ($_POST['check_click'] == 1))
{
//The form was clicked
}
UPDATE:
if you want for each button
if ((isset($_POST['check_click'])) && ($_POST['check_click'] == 1))
{
//The form was clicked
if (isset($_POST['delete']))
{
//delete has some value
}
if (isset($_POST['edit']))
{
//edit has some value
}
}
You can insert into the form tag two submit buttons with different values. And on server side check - which one has come. This approach is also make adding Ajax functionality easier - because you can now add the same callback on this two buttons/
Related
please help me.
I have form like this in index.php
<form id="statusForm" enctype="multipart/form-data" method="post">
<textarea name="statusText" role="textbox" id="wallpost"></textarea>
<input id="photo_input" type="file" name="photo_input" />
<input type="hidden" name="to_id" value="1" >
<button type="button" name="submit" onClick="write_wall_post();">
</form>
<div id="content"></div>
then i have .js file to handle this form
function write_wall_post()
{
var formData = new FormData($("#statusForm")[0]);
$.ajax({
type: "POST",
url: "act_post_status.php",
data: formData,
success: function(data){
$("#wallpost").val("");
$("#photo_input").val('');
var newStatus=data;
$(newStatus).hide().prependTo("#content").fadeIn(2000);
},
processData: false, // tell jQuery not to process the data
contentType: false,
cache:false
});
}
and i have act_post_status.php to process this file submit
<?php
//some configuration
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//some variable declaration and image validation
//Original Image
if(move_uploaded_file($uploadedfile, $path.$time.'.'.$ext))
{
$is_image=1;
}
else
echo "failed";
}
}
//inserting data to database
$status = trim(strip_tags(htmlspecialchars($_POST["statusText"])));
mysql_query("insert into news (status,is_image) values ('$status','$is_image')");
echo "<div class='post'>$status</div>";
?>
the scenario i want is:
when user input data (status), then click submit button, the content automatically show the update (handled by jquery)
but the fact is:
(1) when I completed the form (both status and picture), it works normally.
(2) but when I completed just data form (filling status input only), it was submitted to database successfully, but the content don't update automatically. I should refresh them to get the update.
(3) when i just filling the image input, it works normally like case (1).
Please help why if($_SERVER['REQUEST_METHOD'] == "POST") failed to echo the input by ajax request when data input (status) is blank/empty.
thousands of thanks. :)
I'm not sure why it matters whether you leave the file input unfilled, but you need to disable the normal form submission when you use AJAX. The onclick function should return false to do this.
<button type="button" name="submit" onClick="write_wall_post();return false;">
I have a form with two submit buttons:
<form method="POST">
<input type="submit" name="Update" value="Update"/>
<input type="submit" name="Submit" value="Delete"/>
</form>
I need to manipulate some things on the form before it is submitted so I used this jQuery:
$('form').submit(function (e) {
e.originalEvent && e.preventDefault();
//manipulate stuff
this.submit();
});
The problem is, I need to know which button was clicked at the back end but
$_POST['Submit'] and $_POST['Delete']
are both undefined. It seems the inputs are removed from the post array by the jQuery.
What would be a good way to solve that issue?
I would go about it with two event handlers for each button and a hidden input to tell the php which action is requested. As an addition I would advice you to checkout Ajax.
Code is as follows:
$('#update').click(function (e) {
e.originalEvent && e.preventDefault();
//manipulate stuff
$("form").append("<input type = 'hidden' name = 'action' value = 'update' />");
this.submit();
});
$('#delete').click(function (e) {
e.originalEvent && e.preventDefault();
//manipulate stuff
$("form").append("<input type = 'hidden' name = 'action' value = 'delete' />");
this.submit();
});
And on the back-end side you'll get what was submitted in $_POST['action'] that is either going to be "update" or "delete"
I would suggest you add an action as input type hidden and two buttons that may or may not be a part of the form. Add event listeners to the buttons to know when those are clicked and change input action field accordignly, then submit the form.
First, give your form a name or id, rather id.
<input type="hidden" name="action" value=""/>
<input type="submit" name="Update" value="Update"/>
<input type="submit" name="Submit" value="Delete"/>
$('input[type="submit"][name="Update"]').click(function() {
$('input[type="hidden"][name="action"]').val('Update');
$("#something").submit();
});
$('input[type="submit"][name="Submit"]').click(function() {
$('input[type="hidden"][name="action"]').val('Delete');
$("#something").submit();
});
I have the following HTML:
<form method="post" id="IssueForm" action="wh_sir_insert.php" >
<input name='id[]' type='checkbox' class="selectable" value='$col[8]' />
<input type="submit" name="Build" value="BuildSir" />
<input type="submit" name="wht" value="Proceed Your Transfer" />
</form>
When I click the submit button, both value and form values are sent:
$("input[name='Build']").click(function(){
// some validation
});
following are the posted values:
$("input[name='wht']").click(function(){
//validation code
})
But when I submit the form through jquery.submit(), the values of the submit buttons are not posted:
$("#IssueForm").submit();
On the server side, I pick an action based on the submitted type. How I can add extra post information with $("elem").submit(); to send along type of action?
Please, note one way is through $.ajax Or $.post but it would require a huge effort to change all my code.
Below is my scenario:
$("input[name='Build']").click(function(){
var per=$("input[name='issueperson']");
$.ajax({
url:"ajaxloads/confirmuser.php",
dataType:"json",
data:"username="+per.val()+"&ownership="+$("#ownership").text(),
success:function(r){
if(r.success){
var agree=confirm("Are you sure you want to Build SIR?");
if (agree){
$("#IssueForm").submit();
// To avoid Double Submission
}
}
else{
$("#admin_message").show();
$("#ErrorMessage").text(r.info);
}
}
});
return false;
});
How I can send the value of submitted button along with the form submit?
Finally I got to work in some way by adding a extra Value with query string.
$("input[name='Build']").click(function(){
var per=$("input[name='issueperson']");
$.ajax({
url:"ajaxloads/confirmuser.php",
dataType:"json",
data:"username="+per.val()+"&ownership="+$("#ownership").text(),
success:function(r){
if(r.success){
var agree=confirm("Are you sure you want to Build SIR?");
if (agree){
$("#IssueForm").attr("action","wh_sir_insert.php?Build=BuildSir");
$("#IssueForm").submit();
}
}
else{
$("#admin_message").show();
$("#ErrorMessage").text(r.info);
}
}
});
return false;
});
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
So my issue is submitting a form via AJAX with jQuery when I submit it to the PHP it doesn't matter what button submits the form when using the jQuery AJAX but when using a form action the form submits and lets me know if the delete or update button was pushed. For example here's the HTML to submit the form
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
Here's the AJAX Call below.
$(document).ready(function() {
$("#update-form").submit(function () {
$.ajax({
type: "POST",
url: "updateHandler.php",
data: $("#update-form").serialize(),
success: function(data) {
var login = JSON.parse(data);
if (login.success) {
alert(login.message); //Show the ticket was updated!
} else {
alert(login.message);
}
}
});
return false;
});
});
Now here's my PHP code that the AJAX Calls.
<?php
$json_data = array();
if(isset($_POST['delete'])) {
$json_data['message'] = 'Ticket was deleted!';
} else {
$json_data['message'] = 'Ticket was updated!';
}
// Encode response as JSON
echo (json_encode($json_data));
?>
EDIT
After being asked for the console output here's what I got
The "No Button Pushed" if from the code from the answer by adeneo
{"success":true,"message":"No Button Pushed"}
Array
(
[ticket-num] => 6
[technician] => 1
[category] => 1
[email] => nstark#mail.com
[name] => Ned Stark
[country] => Canada
[issue] => I'm Having an issue with Product Y
)
What happend was the buttons weren't being serialized with the form because when submitting the for programmatically it doesn't know what button you pushed so it doesn't send it. So what I did was put a hidden input and changed the value of it depending on the button they clicked to submit the form.
Also note I defaulted the value of the choice to update. I did this so if a user uses the enter key on the keyboard to submit the form it will do something automatically and not error.
HTML
<input type="hidden" name="choice" id="choice" value="update">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
jQuery
$('input[type="submit"]').click(function() {
$('#choice').val(this.name)
});
PHP
if(isset($_POST['choice']) && $_POST['choice'] == "update") {
//if user clicked update
} else if(isset($_POST['choice']) && $_POST['choice'] == "delete") {
//user clicked delete.
}