Sending form ID to AJAX on button click - php

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.

Related

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.

Post Input Attribute (Not Value) to Thank You Page

Is there a way to post attributes other than the value to another page?
For eg: If i have <option value="Bulgaria" data-key="BG" data-geo="EMEA">Bulgaria</option>
I know i can post the value and get it on the thank you page with $_POST,
but what if i wanted to get the data-key instead of the value?
$( "#myselect option:selected" ).data("key") or
$( "#myselect option:selected" ).attr("data-key")
But you need to send values via js insted of html form send
You can only post the value (unless you use AJAX and a bit of manipulation). If you go for the JavaScript route, this would be achieved with something like this:
$('form').submit(function(e) {
data = {};
url = '';
e.preventDefault();
$('input', this).each(function() {
var pcs = $(this).data();
var datakey = $(this).attr('data-key');
if (undefined == data[datakey]) {
data[datakey] = {};
data[datakey]['_'] = $(this).val();
}
$.each(pcs, function(k, v) {
data[datakey][k] = v;
});
});
$.ajax({
url: url,
data: data,
type: "POST"
}).done(function() {
// data-key successfully POSTed
});
});
The better question is why are you attempting to do this? If you only want an output of BG, use that as the value. If you want both Bulgaria and BG, you can make use of a hidden input to additionally send the secondary data (as a value):
<input type="hidden" name="shortcode" value="BG" />
Simple, you can try it:
HTML:
<form ... method="post" onsubmit="return form_check()">
<input type="hidden" name="data_key" id="data_key">
<input type="hidden" name="data_geo" id="data_geo">
...
<button type="submit">Submit</button>
</form>
jQuery:
function form_check() {
$('#data_key').val($('#myselect option:selected').data('key'));
$('#data_geo').val($('#myselect option:selected').data('geo'));
return true;
}
then in your PHP you'll receive them in $_POST['data_key'] and $_POST['data_geo'].

Multiple submit buttons with ajax & php not being processed

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);
});
});

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);
}
});
}
});
});

ajax validation for multiple forms on page, all have same class

basically i am making a CMS and want to have in post editing.
How it works atm is that the blog post is echoed out (PHP) and there is a hidden ckeditor which when an edit button is clicked gets displayed. The edit button is then replaced with a save button.
This all works fine and good however the issue comes when saving the blog post.
the php works fine, and the ajax validation also works fine but ONLY when there is 1 blog post.
When there is more than 1 post the errors come. The issue is that it seems to be that the save post button is sending all of the data from every blog post. I checked it with the firebug net and saw that all data is being sent.
I just need a way of making it so that the save button in the form, only affects the data inside of that form. At the moment the error / success message is displayed by all of them.
Here is the post echoed out:
<div class="blogtest">
<form action="process/updatepost.php" class="updatepost" method="post">
<input type="button" class='.$editenabled.' value="Edit">
<input type="submit" class="saveupdatebutton" value="Save">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<div class="text">
<div class="buildtext">'.$text.'</div>
<div class="editor"><textarea name="ckeditor" class="ckeditor">'.$text.'</textarea></div>
</div>
</form>
</div>
This is the javascript:
$(document).ready(function(){
$(".updatepost").submit(function(){
$(".error").remove();
$(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var blogpost = $('.ckeditor').val();
// Validation
if (blogpost == '') {
check = false;
$('.ckeditor').after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $(".updatepost").serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$('.ckeditor').after('<div class="success">Post Updated</div>');
else
$('.ckeditor').after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
Thanks for reading. Hope you can help.
You just need to limit the validation logic to the form that's actually being submitted. Right now $('.ckeditor').after('<div class="error">Text Is Required</div>'); is modifying all items that match the ckeditor class name. See below -- I've added a variable called $targetForm which grabs the form being submitted and modified the code appropriately to only reference the children of that form.
$(document).ready( function() {
$(".updatepost").submit(function() {
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $ckEditor = $targetForm.find('.ckeditor'),
blogpost = $ckeditor.val();
// Validation
if (blogpost == '') {
check = false;
$ckeditor.after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$ckeditor.after('<div class="success">Post Updated</div>');
else
$ckeditor.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});

Categories