Multiple submit buttons with ajax & php not being processed - php

I'm very new to PHP & AJAX. I have two submit buttons in HTML and I'm passing/extracting some values to/from a PHP file using ajax serialize() or say ajax. The problem is that serialize() is not able to distinguish which button is used, the "reject" button or the "accept" button which is creating problem for PHP file as it is neither processing for accept button nor for reject button.
At the end, my main purpose is to add some data to DB when a user hits Accept Button & remove some data from DB if a user hits Reject Button But using Ajax.
HTML
<button class="p" type="submit" value="accept"></button>
<button class="p" type="submit" value="reject"></button>
PHP
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST["accept"]){
// doSomething
}else if(isset($_POST["reject"]){
// doSomethingElse
}
}
...
...
...
Ajax (It's not the complete code, just to have basic idea)
var form = $d('#formName');
$('.p').click(function(){
var formData = $d(form).serialize();
$d.ajax({
type: 'POST',
url: $d(form).attr('action'),
data: formData
})
.done(function(response){
window.location.reload(true);
})
});

You will need to give your submit a name attribute. Example:
<button class="p" name="action" type="submit" value="accept"></button>
<button class="p" name="action" type="submit" value="reject"></button>
And your PHP code can check the $_POST value for action.Example:
if($_POST["action"] == 'accept'){
// doSomething
}else if($_POST["action"] == 'reject'){
// doSomethingElse
}

Submit buttons are not serialized, you can get the data from them manually.
Also make sure the buttons have name attribute.
$('.p').click(function(e){
e.preventDefault();
var formData = $(this).attr('name') + '=' + encodeURIComponent(this.value) + '&' + $d(form).serialize();
$d.ajax({
type: 'POST',
url: $d(form).attr('action'),
data: formData
})
.done(function(response){
window.location.reload(true);
});
});

Related

Ajax requests are failing to send after an initial ajax request is made - trying to figure out what is causing a conflict

I have a form with multiple types of ajax calls.
- general form update that saves all input fields
- per-field uploads
- per-upload deletion
The per-field and per-upload ajax calls are targeted by the class name of the button that is clicked. So there are only 3 scripts in the page.
Each of the scripts work. When the page loads fresh, I can complete any of the form update, field upload, or upload deletion actions.
However, after I have completed an initial action, subsequent actions don't work.
Example:
If I click the "save" button to update the form, this causes the per-field upload and per-upload deletion buttons not to work.
If I click the "per-field" upload, the upload works, but then I'm not able to delete anything.
If I click a "per-upload" delete button, I can no longer upload anything.
But in each case, I am still able to click "save" to update the form.
Here's a visual of how the page is set up:
When a file or image is uploaded to a field, it appears in a container div within the field's markup. The uploaded asset comes with a 'delete' button allowing the user to remove the upload.
Here's the basic HTML of the page
<form id = "form" action = "/process.php" method = "post">
<div class="field">
<label class="field-label">
<span class="field-label-text">Upload 1</span>
<input type="file" data-name="answer1" name="files_answer1[]" />
</label>
<!-- destination for ajax response messages -->
<div id="ajax-message-answer1" class="ajax-field-message"></div>
<!-- upload button -->
<button type="button" class="ajax-button" data-field="answer1" data-type="files">Upload</button>
<!-- container div for uploads -->
<div class="assets" id="assets-answer1">
<div class="asset file">
Name of file
<label class="asset-action">
<!-- deletion button to remove asset -->
<button type="button" data-asset="asset1" data-parent="answer1" class="ajax-delete" value="asset1" onclick="return confirm('You are about to delete this item. Press OK to proceed.')">Delete</button>
</label>
</div><!-- .asset.file -->
</div><!-- .assets -->
</div><!-- .field -->
.... more fields of the same kind ...
<button type = "submit" id = "save">Save</button>
</form>
JS
There are several other scripts in the page, such as jQuery, jQuery UI, Bootstrap, and some custom ones for generating slugs, etc. But I'm thinking these aren't to blame since the problem began only when I started running more than one Ajax request in the page. Here's the JS:
Form Update script
<script type="text/javascript">
$(document).ready(function() {
// process form
$('#form').submit(function(eform) {
// stop regular form submission
eform.preventDefault();
// set variables
var form = $('#form');
// serialize form data
var fdform = form.serializeArray();
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: $.param(fdform),
dataType: 'json',
success: function(data) {
// get URL for redirect if supplied
if (data.redirect) {
window.location.href = data.redirect;
} else {
// replace with updated template from response
$('#form').html(data.html);
// place template js in specified div
$('#ajax-js').html(data.js);
}
},
error: function(report) {
console.log(report.responseText);
}
});
}); // .click
}); // .ready
</script>
Per-Field Upload script
<script>
$(document).ready(function() {
$(".ajax-button").click(function() {
var fdUpload = new FormData();
// get field info from the clicked button
var field = $(this).data('field');
var uploadType = $(this).data('type');
var input = $('#' + field)[0];
var container_id = '#assets-' + field;
var button_id = '#button-' + field;
// add each file to uploads array
$.each(input.files, function(i, upl) {
// add each file to target element in fdUpload
fdUpload.append(uploadType + '[]', upl);
});
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdUpload,
dataType: 'json', // returns success(data) as object
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').append(data.js);
// clear file input after upload completes
input.value = '';
if (!/safari/i.test(navigator.userAgent)) {
input.type = '';
input.type = 'file';
}
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Per-Upload Deletion script
<script>
$(document).ready(function() {
$(".ajax-delete").click(function() {
var fdDelete = new FormData();
// get asset info from clicked button
var asset = $(this).data('asset');
var parent = $(this).data('parent'); // answer
var container_id = '#assets-' + parent;
var button_id = '#delete-' + asset;
var message_id = '#ajax-message-' + asset;
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdDelete,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').html(data.js);
// retrieve and display response status
$(message_id).html(data.status);
$(message_id).addClass('show');
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Summary
Again, each ajax request works when activated after a fresh page load. But after the form has been updated or after an upload or deletion, the upload and deletion no longer fire.
The 'error' callback doesn't display anything in console when this failure occurs.
Do you see a conflict somewhere in the scripts? Maybe the scripts need function names defined? Or is it a problem that the returned response object is called 'data' in each script?
I haven't been working with Ajax very long, so I'd really appreciate your help. I've been banging my head on this all day.
You're using $(".ajax-...").click(...) but in ajax success handler you're updating HTML code for container, thus loosing any attached click handlers for elements in this container.
If you switch to using $("#form").on('click', '.ajax-...', ...) then you'll catch click events even after directly replacing HTML.
jQuery.on() documentation

jQuery trigger previously defined onclick from link in new window

I am submitting a form using jquery onclick. On the PHP side, it checks to see if there is already an existing document by the same name. If true, a small form is returned in the response with 3 options, dependent on the record data. Those options are displayed in a message window. One of those selections needs to resubmit the previous form data, substituting the new name.
The problem is, the change name form does not exist when the page is loaded and thus does not recognize the ClickCheck class in the new form.
How can I resubmit this form with the new DocName?
The submit in the main form (actually this is one of four submits)
<a class="ClickCheck" id="Create" href="javascript:void(0)">Create Bill</a>
The jQuery:
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#TheForm');
if(ButtonID == "Save")
{
// Do save code
}
else
{
var FormData = Form.serialize();
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: FormData,
success: function(response)
{
$('#MWContent').html(response);
$('#MessageWindow').show();
}
});
}
});
Then, in the response, I have:
<form id="ChangeName" name="ChangeName">
Use another name:
<input type="text" id="DocName" name="DocName" size="60" maxlength="60" value="" placeholder="Document Name" />
<a class="ClickCheck" id="NewName" href="javascript:void(0)">Go</a>
</form>
The idea is to have the "NewName" resubmit the form (with the new name, of course.) I can, of course, detect that in the click function.
You can attach the click() event to the document to make it global.
$(document).on('click', '.ClickCheck', function(e){
e.preventDefault() // <<<< Either this
// Do stuff
return false // <<<< Or this
})
http://api.jquery.com/on/
Also don't use href="javascript:void(0)", use return false or e.preventDefault() in the callback function.

How to post a variable to a php file using ajax

I want to pass a variable to college.php where that variable can be used to fetch data.
I already tried get and post methods using form, but then using get the variable values are visible in address bar and using get form resubmission alert appears
this is what I used.
<form class="morestories"method="get" enctype="multipart/form-data" action="college.php">
<input type="hidden" name="collegename" value="<?php $collegename=$row['name']; echo $collegename; ?>">
<input class="morestoriesbutton" type="submit" name="collegeselectlink" value="More Stories" />
</form>
also the variables i am passing to college.php file, on refresh it should be used again to access data so any possible help
This is a example where I am passing name and password to a php function ,
you can refer this and apply it accordingly to your condition.
$(document).ready(function(){
//this is my button
$("#click").click(function(){
// getting username and password from my html
username = $("#name").val();
password = $("#pad").val();
if(username=="" || password==""){
alert("please check the details");
} else {
$.ajax({ url: 'reverse.php',
data: {username:username,password:password},
type: 'post',
success: function(output) {
alert(output);
}
});
}
});
});

Sending form ID to AJAX on button click

I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.

Jquery Ajax NyroModal Page Reload after Succes

I have site running Jquery, Ajax, PHP, and an HTML form. It uses two pages.
Pages...
Example.php & Processexample.php
When you click the edit button on example.php a form pops up in the NyroModal window posting to Processexample.php and allows you to edit customer data that's posted using Ajax.
After user clicks save on Porcessexample.php a SQL update is made and a success message is posted back to the Modal Box (end-user).
Here are the issues...
I can't get the NyroModal window to close after (data) success is called on processexample.php. I tried setting the Timeout in JQ/Javascript below but error occurs.
setTimeout("$.nyroModal.close()", 4000);
How do i get example.php page to display updated data automatically, or have the page reload after #send button is clicked and success is displayed in modal window.
HTML Form Code on processexample.php
<form id="AjaxForm" name="AjaxForm" action="#" method="post">
<input name="submitform" type="hidden" value="1"
<button id="send">Save Client</button>
JS Code on processexample.php --> See bold text in code where issue is.
$(document).ready(function() {
$("#AjaxForm").submit(function() { return false; });
$("#send").on("click", function(e){
var idval = $("#client").val();
var calval = $("#view").val();
var emailval = $("#customer_email").val();
var nameval = $("#customer_name").val();
var phoneval = $("#customer_phone").val();
var msgval = $("#customer_note").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'saveclient.php',
data: $("#AjaxForm").serialize(),
success: function(data) {
if(data == "true") {
$("#AjaxForm").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your information has been updated.</strong></p>");
**setTimeout("$.nyroModal.close()", 4000);**
});
}
}
});
}
});
});
</script>
I was able to work this out myself. Use location.reload(); after the success call.

Categories