How to submit a form via Ajax using PHP - php

I'm a complete Ajax newbie.
My non-ajax form currently looks like this:
<form id='myform' action=".htmlspecialchars($_SERVER["PHP_SELF"])." method='post''/>
<input type='hidden' name='id' value='$id' />
<td>
<input style='height:18px' type='date' name='date' value='$date' required/>
</td>
<td>
<select name='status' form='myform' required/>
<option>$status</option>
<option value='status_one'>status_one</option>
</select>
</td>
<td>
<input form='myform' type='text' name='memo' value='$memo'/>
</td>
<td>
<input form='myform' type='submit' value='Save' />
</form>
</td>
As the data is posted to the same page, the following code retrieves it upon submission:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//do stuff
}
This works fine, except that I want to be able to submit without refreshing the page, so the form info is submitted in the background. I know Ajax is the way to go here and I read lots about it, but I'm having trouble getting it to work. I'm unsure if the Ajax script is supposed to replace the retrieve part or it works in conjunction.
Much appreciated.

Use jQuery $.post
<script>
$(function(){
$("#submit").click(function()
{
var form = $("#myform").serialize();
$.post('url.php', form, function(data){
alert(data);
});
});
});
</script>
Note: You need to ID the submit button properly.

AJAX replaces the functionality of the submit button with other code that you have in javascript. #getvivekv's solution will work fine for you on that side.
The PHP server side will be easier to do if you separate it into a different script (or else put your ajax handling at the very top and exit; afterwards.)
You will fine life a lot less frustrating if you read through a good tutorial or another one before banging your head too hard against a new type of technology.
If you are doing AJAX for the first time I would actually recommend doing it in plain vanilla javascript so you know how to do it - then when you've got that figured out then see how it works in jquery.

Here's a quick example of how you could do this with keeping it all in one file using Ajax:
First, in the top of your page, add the logic that handles your form data:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// output for example
echo $_POST['id'] . "<br>";
echo $_POST['date'] . "<br>";
echo $_POST['status'] . "<br>";
echo $_POST['memo'] . "<br>";
//do stuff
}
?>
Following that you can add your ajax script:
<!-- remove jQuery if already included -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#myform').submit(function() {
$.ajax({
type:'POST',
url:'<?php echo $_SERVER["PHP_SELF"]; ?>',
data: $(this).serialize(),
success: function(data) {
$('#ajax-result').html(data);
}
});
return false;
});
});
</script>
The return false; will prevent the default form submission.
The .serialize() method creates a text string in standard
URL-encoded notation containing your form data.
The .html() method in the success: callback will return the
data to the specified element once processed by your script.
Then, add your form below that:
<?php if (empty($_POST)): ?>
<form id='myform' action="<?php echo $_SERVER["PHP_SELF"]; ?>" method='post'/>
<input type='hidden' name='id' value='$id' />
<td>
<input style='height:18px' type='date' name='date' value='$date' required/>
</td>
<td>
<select name='status' form='myform' required/>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
<td>
<input form='myform' type='text' name='memo' value='$memo'/>
</td>
<td>
<input form='myform' name="submit" type='submit' value='Save' />
</form>
</td>
<?php endif; ?>
<!-- This is the div in which your data will be returned. -->
<div id="ajax-result"></div>
Just a note that there are various ways that this I would definitely encourage you to check out the tutorials mentioned here.

Related

ajax serialize gives different strings and form autosave doesnt work

I am trying to implement an autosave functionality using ajax and php. Here is my script:
function autosave() {
alert($("#myform").serialize());
$.ajax({
url: "form_creator.php",
data: $("#myform").serialize(),
type: 'POST',
success: function(data){
if(data && data == 'success') {
alert("saved");
// Save successfully completed, no need to do anything
}else{
alert(data);
// Save failed, report the error if you desire
// ....
}
}// end successful POST function
}); // end jQuery ajax call
// end setting up the autosave on every form on the page
}// end function autosave()
setInterval(autosave, 5000);
The problem is that I am getting different strings in the first alert and in the second one (in else section). In the first alert, the string seems to be correct with key=value&key2=value2.... but the second alert in else section gives me all html page. Is this correct behaviour? The autosave functionality doesn't work... Am I missing something?
<?php if((isset($_POST['sub'])) || (isset($_POST["autosave_check"])))
{ //save to db
}else{
?>
<form action="" method="post" id="myform" class="ajax_form" name="myform" enctype='multipart/form-data'>
<ul class="sorting dd-list" id="my_list">
//generate inputs
</ul>
<input type="hidden" name="chbox" class='hdbox' id="chbox" value="" />
<input type="hidden" name="save" value="<?php echo $idn?>" />
<input type="hidden" id="autosave_check" name="autosave_check" value="1">
<br class="clear" /> <br />
<div class="creator-buttons">
<h2 class="subheader-creator"> Akce </h2>
<table>
<tr>
<td>
<a href="javascript:;" class='radiusz addchbox' id="ch" value="Checkbox field"><?php echo $langa['formc'][10];?>
</a>
</td>
<td align='right'>
<input type="hidden" id="paths" value="<?php echo $patH?>" />
<input type="submit" name='sub' value='<?php echo $langa['formc'][13]?>' id="saveT" class='dugme1 submitforms' style="float:right;" />
</td>
</tr>
</table>
</div>
</form>
<?php } ?>
Its quite long code so just some parts.. Saving on button click works perfectly as for any other form.

Regular button and submit button in one form don't work

I have a form returned back from a PHP request. The form has a submit button and a regular button. The submit seems to work just fine, but the regular one won't work! Please advise.
Here is my HTML:
<tr id='actionRow' name='actionRow' hidden='hidden'>
<td>
<input class='actionBtn' type='submit' id='confirm' name='confirm'
value='Confirm' onclick='genChanged();'/>
</td>
<td>
<input class='actionBtn' type='button' id='cancel' name='cancel'
value='Cancel' onclick='cancel();' />
</td>
</tr>
And here is the cancel() function:
function cancel(){
alert('in cancel');
document.getElementById('editRow').hidden = false;
document.getElementById('actionRow').hidden = true;
window.location.replace("admin.php");
};
The alert never appears!
Is it even right to put multiple non-submit buttons in one form?
UPDATE
my form looks something like:
<form action='save.php' method='POST' id='myForm'>
I've added the line document.getElementById('myForm').submit(); to the getChange(); function, to make the button be:
<input class='actionBtn' type='button' id='confirm' name='confirm'
value='Confirm' onclick='genChanged();'/>
Yet, cancel(); function still doesn't work!
You can't use the same name for the id and the function name.
In my sample 'a' have the same id and function name test() and b have different id and function name cancel()... cancel work fine and test don't.
<script>
function cancel(){
alert('in cancel');
};
function test(){
alert("in test")
};
</script>
<body>
<form action='save.php' method='POST' id='myForm'>
<tr id='actionRow' name='actionRow' hidden='hidden'>
<td>
<input class='actionBtn' type='button' id='test' name='a'
value='a' onclick='test();'/>
</td>
<td>
<input class='actionBtn' type='button' id='b' name='b'
value='b' onclick='cancel()' />
</td>
</tr>
</form>
</body>
For more informations you can see this helpful answer : https://stackoverflow.com/a/9160009/1318727

href hyperlinks as POST

I'm wondering which is the best way to map <a href=...></a> hyperlinks performing a HTTP GET to perform a HTTP POST (I'd like to avoid passing all variables in the URL)? For instance, the 2 hrefs below. Furthermore, I would like also to get rid of the submit button and use a regular <a href=...></a> hyperlink. Any suggestions?
<form action="test.php?action=update" method="post" id="cart">
<table>
<tr>
<td>
<a href="test.php?action=delete&id=<?php echo $id ?>" class="r">
remove
</a>
</td>
<td>
add
</td>
</tr>
<tr>
...
</tr>
</table>
<div> <button type="submit">Update</button> </div>
</form>
I'd suggest using jQuery.post and click. When the link is clicked, submit the data via something like this
$('.r').on('click', function() {
$.post('test.php', {key:'value', key2:'value2'}, function(data) {
//error check here
});
return false;
});
As far as i know you can't perform any POST requests with links. You can make your GET requests with links and php as a fallback for users with javascript disabled and for those who have javascript enabled cancel default behavior for links with javascript and make with ajax your POST request with help of AJAX.
for example:
<a class="submit" href="hallo.html?hello=world&test=yes">Test</a>
and js(i used jquery) would be:
$('.submit').click(function(){
var urlPairs = this.href.split('?')[1].split('&'),
total = urlPairs.length,
current = [],
data = {};
for(;total;) {
current = urlPairs[--total].split('=');
data[current[0]] = current[1];
}
$.post('test.php', data);
return false;
});
​
you could also write your POST function other for more info check jQuery post function doc
P.S. I wounder, if you are using FORM any way why wouldn't you use submit button, is it because of CSS styling? You could style it the same way like any other element(with some tweaks in some browsers).
You can keep the input tags as hidden in your form to submit them as POST.
<td>remove</td>
<td>add</td>
Rewrite the above using two forms, having <input type="hidden" name="id />
and buttons <input type="button" name="delete" />
etc..
if you run print_r($_POST) in your action script. You'll get a list of the buttons and the values of the hidden fields. Now, you can write conditions for the actions to run. I didn't write complete code here, just passing the idea.
Edit: See the example below.
<form method="post" id="cart">
<table>
<input type="hidden" name="id" value='some value' />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="add" />
</tr>
<tr>
...
</tr>
</table>
<div><button type="submit">Update</button></div>
</form>
<?php print_r($_POST); ?>

Issue checking value of form input with jQuery

I want to perform an if statement based upon the value of a hidden input within myform.
the scenario is that I have a table consisting of tests. Each test is essentially its own form. the hidden input basically contains 'YES' if the test has a password attached. I want to prompt the user to enter the password if that is the case when they attempt to execute a particular test (submit the form).
so here is my code I am attempting:
$("#submit").live('click', function(event) {
if ($(this).parent().find(':input:hidden[name=has_password]').val() == 'YES') {
$('.messagepop').remove();
$(this).parent().append('<div class="messagepop pop"><p><label for="password">Enter test password</label><input type="text" size="30" name="pass" id="pass" /></p><p><input type="button" id="submitPass" value="GO" id="pass_submit"/> or <a class="close" href="/">Cancel</a></p></div>');
$(".pop").slideFadeToggle(function() {
$("#pass").focus();
});
return false;
}
});
Without the if statement the code works: on clicking a particular button within a form, another small password entry form pops up. However I only want the form to pop up if a value of a hidden input is 'YES'.
I have checked that values are present in the hidden input.
I imagine I am using the jQuery slightly wrong as I am a beginner. So can somebody identify a better way of performing the check?
Many thanks,
EDIT (jsfiddle with html etc):
jsfiddle
Your HTML is extremely malformed. The <tr> and <form> end-tags are mismatched, you've got a <form> tag directly inside the <tr>, which is not allowed, you haven't self-closed your <input /> tags and you have duplicate id's on the same page.
<tr>
<form name='myform' method='post' action='test_sim.php'>
<input name='test' type='hidden' value='1'>
<input type='hidden' name='has_password' value='NO'>
<td>TEST 1</td>
<td>B352</td>
<td>10</td>
<td>2011-05-12 06:00:00</td>
<td>2011-05-12 12:00:00</td>
<td>06:00:00</td>
<td><input id='submit' type='button' value='execute test'></td>
</tr>
</form>
It should be like this:
<tr>
<td>TEST 1</td>
<td>B352</td>
<td>10</td>
<td>2011-05-12 06:00:00</td>
<td>2011-05-12 12:00:00</td>
<td>06:00:00</td>
<td>
<form name='myform' method='post' action='test_sim.php'>
<input name='test' type='hidden' value='1' />
<input type='hidden' name='has_password' value='NO' />
<input class='submit' type='button' value='execute test' />
</form>
</td>
</tr>
Fixing the HTML solves your problem: http://jsfiddle.net/brianpeiris/ezFgU/16/
You should use the W3C Validator tool to check your HTML so that you can prevent these types of issues.
Edit: As mcgrailm mentioned, your id attributes are duplicated. jQuery is forgiving here, it seems, that's why the above jsFiddle works. You should use a class to identify your submit buttons and use the corresponding $('.submit') selector to attach a click handler.
i believe
if ($(this).parent().find(':input:hidden[name=has_password]').val() == 'YES')
should be
if ($(this).parent().find('input[name=has_password]:hidden').val() == 'YES')
i think your selector is incorrect try this
$("#submit").live('click', function(event) {
if ($(this).parent().find('input[name="has_password"]:hidden').val() == 'YES') {
$('.messagepop').remove();
$(this).parent().append('<div class="messagepop pop"><p><label for="password">Enter test password</label><input type="text" size="30" name="pass" id="pass" /></p><p><input type="button" id="submitPass" value="GO" id="pass_submit"/> or <a class="close" href="/">Cancel</a></p></div>');
$(".pop").slideFadeToggle(function() {
$("#pass").focus();
});
return false;
}
});
WORKING DEMO

Loading Data from Form Into Ajax Driven PHP Page using jQuery.change

I am probably making some silly mistake but I am newer to the world of Jquery and am looking for some help with this issue.
I have a form that I need to check/validate two dates once they change their values. Once they change I had an Ajax call that loaded a page "checkdates.php" and passed in two bits of data. The Date that changed and a project name to "checkdates.php" using GET and adding the data to the URL string. This Ajax call loaded the page in a div with the ID "status" and php page displayed what the outcome of the date check was.
The Old code used prototype to pull in the data as a function and I used the onChange event on the form elements:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
/*function checkDate(date,project){
if(date!==''){
new Ajax.Updater('status', 'datechecker.php?date='+date+'&project='+project, { method: 'get' });
} else {
alert('enter a valid date!');
}
}
</script>
The code I'm trying to move over to jquery now looks like:
<script type="text/javascript">
$(document).ready(function() {
$('input#date_to').change(function() {
var datevalue = $(this).val();
$('#status').load('datechecker.php?date='+datevalue+'&project='+<? echo $_COOKIE['department']; ?>);
}
);
$('input#date_from').change(function() {
var datevalue = $(this).val();
$('#status').load('datechecker.php?date='+datevalue+'&project='+<? echo $_COOKIE['department']; ?>);
}
);
});
</script>
I think it may be an issue probably with how i'm pulling in my data or how i'm asking it to check the .change feature because it's not firing. Any assistance would be wonderful. Again the disclaimer: I'm sort of new to jquery so please be nice if it's some obvious idiot mistake.
EDIT:
As requested the HTML/PHP of the rest of the file (sorry for the formatting, this was a quick and dirty project that was last minute but turned into a huge headache):
<form id="form1" name="form1" method="get" action="?page=post_request">
<div class="timeavailable">
<?
require('data.php');
$name=$_COOKIE['un'];
$query="SELECT * FROM time WHERE emp_name='".$name."'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
$i=0;
?>
Vac: <b><? echo mysql_result($result,$i,"vacationtime"); ?></b>
Personal: <b><? echo mysql_result($result,$i,"personaltime"); ?></b>
Pts: <b><? echo mysql_result($result,$i,"points"); ?></b>
<input type="hidden" name="vacationtime" value="<? echo mysql_result($result,$i,"vacationtime"); ?>">
<input type="hidden" name="personaltime" value="<? echo mysql_result($result,$i,"personaltime"); ?>">
</div>
<h1>Time Off Request Form</h1>
<div class="header">
<div class="floatydetails">
<br>
Reason for Absence:<br>
<textarea name="reason_detail" id="reason_detail" rows="<?php echo $textareaheight; ?>" cols="<?php echo $textareawidth; ?>"></textarea>
<div id="status"></div>
<div id="daysrequested"></div>
</div>
<div class="col1">
Type of Absence Requested:<br>
<label for="reason_for_request"></label>
<select name="reason_for_request" id="reason_for_request">
<option value="Sick" >Sick</option>
<option value="Vacation" >Vacation</option>
<option value="Bereavement" >Bereavement**</option>
<option value="Doctor Appointment" >Doctor Appointment**</option>
<option value="Court" >Court*</option>
<option value="Jury Duty" >Jury Duty*</option>
<option value="Personal Day" >Personal Day</option>
<option value="Other" >Other</option>
</select><br>
<div class="col2">
Date of Request (mm/dd/yyyy)<br/>
<label for="date_from">From:</label>
<input type="text" name="date_from" id="date_from" class="required" /><br>
<label for="date_to">To:</label>
<input type="text" name="date_to" id="date_to" class="required" /><br>
Partial Request (HH:MM am/pm)<br/>
<label for="date_from">From:</label>
<input type="text" name="partial_from" id="partial_from" class="date-pick" /><br>
<label for="date_to">To:</label>
<input type="text" name="partial_to" id="partial_to" class="date-pick" /><br>
</div>
</div>
<div class="clear-fix"></div><br><br>
<hr>
<center><b>
Note: If You do Not have the Time Available, Your request will be Denied.<br>
* Proper Documentation is required Before approval is made. ** Proper documenation is required upon return.
</b></center>
</div>
<input type="hidden" name="do" value="post">
<input type="hidden" name="emp_name" value="<? echo $_COOKIE['un']; ?>">
<input type="hidden" id="projects" name="projects" value="<? echo $_COOKIE['department']; ?>">
<input type="hidden" name="supervisor" value="<? echo $cms->grabItemByName(employees, $_COOKIE['user_id'], supervisor); ?>">
<input type="hidden" name="emp_number" value="<? echo $cms->grabItemByName(employees, $_COOKIE['user_id'], employee_id); ?>">
<input type="hidden" name="page" value="post_request">
</form>
Is $_COOKIE['department'] an integer? Otherwise you'll probably have a syntax error there.
Both the functions seem to be identical so you can combine them like this:
<script type="text/javascript">
$(document).ready(function() {
$('input#date_to,input#date_from').change(function() {
var datevalue = $(this).val();
$('#status').load('datechecker.php?date='+datevalue+'&project='+<? echo json_encode($_COOKIE['department']); ?>);
});
});
</script>
Here is a possible answer:
jquery change event trigger
Also, try watching the console in Firebug to make sure your php page is getting/returning the correct values.
I found a solution after some of your help and some trial and error. Using the .ajax I was able to get more flexiability to do what I wanted.
<script type="text/javascript">
$(document).ready(function() {
$('#date_to,#date_from').change(function() {
//$('input').change(function() {
var datevalue = $(this).val();
var project = $('#projects').val();
$('#status p').load('datechecker.php?date='+datevalue+'&project='+project);
});
});
</script>
Hope this helps someone out.

Categories