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.
}
Related
I am trying to get a popup submit button working but I haven't quite found the solution I'm looking for.
I am using the jquery modal plugin to show the client the content of their changes before they submit them. However, when I try submitting, nothing happens. The submit button exists on the pop up, whereas the .modify button is the button that opens it. I am having no issues with the pop up itself.
My console test is printing so I know there's nothing wrong with my event listener. Maybe it has something to do with event.preventDefault()?
Thanks in advance.
Here is my code
Back end
jQuery(".modify").click(function() {
event.preventDefault();
var submit = confirm('Are you sure?');
<?php
$post_ids = array();
while($author_entry_posts->have_posts()) : $author_entry_posts->the_post();
array_push($post_ids, get_the_ID());
endwhile;
?>
if (submit == true) {
var data = {
'action': 'modalcall',
'postid': <?php echo json_encode($post_ids)?>,
'userid': <?php echo get_current_user_id() ?>
};
jQuery.post(ajaxurl, data, function(response) {
jQuery(response).appendTo('body').modal();
//Script which handles the submit button on the modal pop-up
jQuery(".modal_submit").click(function() {
console.log("test");
jQuery().submit();
});
});
} else {
return false;
}
});
Front end
<input type="submit" name="submit" value="Submit" class="button modal_submit">
In your handler for click on modal submit you are not defining which form needs to be submitted.
jQuery(".modal_submit").click(function() {
console.log("test");
jQuery().submit(); // you are not defining which form to submit.
});
Instead the <input type="submit" name="submit" value="Submit" class="button modal_submit"> needs to be inside a form which needs to be submitted by calling jquery submit on it.
jQuery(".modal_submit").click(function() {
console.log("test");
$(this).closest('form').submit(); // asking to submit the form which contains this button
});
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 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/