I have an HTML form in a PHP file like the attached snippet:
When I hit the "Save Details" button, I want the page to load a jQuery UI modal dialog. That dialog will execute a controller action (ex:savedetails) through Ajax.
Essentially, the controller action will get all the POST details in "frmEmployees" and saves the changes to a database through Ajax.
I am interested in the logic to load the dialog with the Ajax content in it (Get all the POST variables through the controller action, say "/public/empdetailcontroller" via Ajax). So, far I have something like the HTML below.
Any Ideas?
Snippet:
<form name="frmEmployees" id="frmEmployees" method="POST" action="">
<table>
<tr><td>Name:</td><td><input type="text" name="empName" size="50"></td></tr>
<tr><td>City:</td><td><input type="text" name="empCity" size="50"></td></tr>
<tr><td>Country:</td><td><input type="text" name="empCountry" size="50"></td></tr>
<tr><td colspan=2 align=center><input type="button" name="btnsubmit" value="Save Details"></td></tr>
</table>
</form>
<div id="dialogSaveChanges"
title="Saving.."
style="display:none;"><p><span
class="ui-icon
ui-icon-info"
style="float:left; margin:0 7px 20px 0;"
></span><span id="dialogText-savechanges"></span></p></div>
<script language="JavaScript>
$(document).ready(function() {
$('#dialogSaveChanges').dialog({
autoOpen: false,
width: 400,
modal: true,
title: titleText,
closeOnEscape: false,
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
resizable: false,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
});
$('#btnSaveChanges').click(function() {
$('#dialogSaveChanges').dialog('open');
$("span#dialogText-savechanges").html("Your Changes have been saved successfully.");
});
});
</script>
You'll need to submit the form in order for the form values to be sent. The logic will follow something like this:
Bind function (e.g., submitForm) to form's submit event, returning false to prevent normal (non-AJAX) form submission.
submitForm function makes $.ajax call.
AJAX call is configured to open the dialog before the the request is sent (event: beforeSend).
Dialog box is populated with "Loading..." text/image.
On success or failure of the ajax call (events: success/failure), the dialog box is populated with the results or an error message.
Code might look like:
$('#frmEmployees').submit( function() {
$.ajax({
url: this.attr('action'), // Make sure your form's action URL is correct.
method: 'POST',
data: this.serialize(), // this = $('#frmEmployees')
// Add hidden form inputs to send any control
// parameters to your server script.
beforeSend: openDialogFunction,
success: handleFormSuccess,
failure: handleFormFailure
});
return false; // prevent normal form submission.
});
If you program it like this, your page will also work without javascript, it just won't have the dialog box.
Not sure I completely understand what you are trying to do, but let me try...
So, you want to:
Send form details to a controller via AJAX.
Save the form data to the DB from the controller.
On success, show a dialog box with a "Success" message and the saved items.
On error (you didn't mention this), I assume you would display an alternate method, correct?
Look into the jQuery Ajax methods.
Related
I am making a chat script and an hoping to code it so that when a user submits a message, the script will run chat_new.php and then refresh #cbox. I use the code below to try and accomplish this, but unfortunately it won't reload. Just to rule it out, I tested without any jQuery and chat_new.php executes without problems, so it definitely is my ajax script. In addition, getUpdates() works just fine on it's own. I only have a problem when posting new messages through ajax.
<div id="cbox" align="left">
<script>
$(document).ready(function() {
setInterval(function() {
getUpdates()
}, 2000);
});
function getUpdates() {
$("#cbox").load("/lib/chat_post.php");
}
$("#submitmsg").click(function() {
$.ajax({
type: 'POST',
url: '/lib/chat_new.php',
data: {
submitmsg: 'submitmsg',
usermsg: 'usermsg'
},
success: function() {
getUpdates()
}
});
});
</script>
</div>
<form name="message" method='post' id="cbox_input">
<input name="usermsg" id='usermsg' type="text" size="63" maxlength="255" />
<input name="submitmsg" id='submitmsg' type="submit" />
</form>
Several issues:
Your click handler exists before the element it references and is not inside document.ready. Therefore it can't find the element and never gets bound to it
Once that is fixed you need to prevent the default form submit process. Otherwise page will reload on submit
// put this inside ready()
$("#submitmsg").click(function (event) {
event.preventDefault();
//other code
})
This might be a simple as moving }); from the third line of your script, to just before </script> so that your function and your ajax call are inside $(document).ready(... and therefore only get processed once the DOM has loaded, and all HTML elements are on the page.
Hi I have been at this for days now and I just cant figure out why this isn't working, please could someone take a look.
index.php
<form id = "update_status" method = "POST">
<textarea id="shadow" name ="user_status" placeholder = "Share what is on your mind!" cols="97" rows="1" title="Share what's on your mind"></textarea>
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="button" value="Add Post" title="Your posts will be made public"></input></form>
swift.php
$(document).ready(function(){
$("#btnStatus_update").click(function(e) {
e.preventDefault();
//alert("Confirming function works");
$.ajax({
cache: false,
type: 'POST',
url: './datacenter.php',
data: $("#user_status"),
success: function(d) {
$("#successMesg").html(d);
}
});
});
});
datacenter.php
if (isset($_POST['user_status'])) {
var_dump($_POST['user_status']);
foreach ($_POST as $ak => $av) {
if (empty(trim($_POST['user_status']))) {
echo 'Say what is on your mind'.' ';
} else {
$userstatus = $_POST['user_status'];
add_user_status($user_data['id'], $userstatus);
}
}
}
using var_dump for testing I was hoping it did return the data, but instead i get NULL, i need the data so i can pass it into the add_user_status function to be added to the database, but it seems there is something missing or off about the code denying me my satisfaction. Please help
There are a few things that appear to be missing:
Index.php:
You need to add an action="something" attribute to the form tag, this tells the form what to do when you submit it. (unless you are manually handling this is JS somewhere else?)
<form id = "update_status" action ="data.php" method = "POST">
Also, unless you are using JavaScript on the index page to handle the actual submitting of the form, your <input> should include a type="submit" attribute. (this will also make it a button) and when clicked it will automatically submit the form to the action location above.
Swift.php:
the code posted is JS, and does what the first line of the previous paragraph mentioned (handles the submit button). Do you include this file inside the index.php? if the index.php cannot see it, then it wont run. It must also be in the html somewhere in a proper <script> block.
I believe the correct way to send form data using ajax is to serialize the data:
$('#update_status').serialize() instead of just sending the one input field.
You will also be required to reference the jQuery libraries, preferably in the index, but could also go in swift.php. I am also assuming that the code posted appears in the necessary <script> block.
Data.php:
should this be datacenter.php? your Swift.php is sending the ajax request to ./datacenter.php
On a side note, if you need it to use Ajax then you actually don't need the action ="data.php" method = "POST" in the form (Ajax does all that for you)
The way it could be done would be something like this:
Index.php:
// HTML beginning stuff
<head>
// Either reference the script in its own JS file or:
// Need to also include jquery library
<script type="text/javascript">
$(document).ready(function(){
$("#btnStatus_update").click(function(e) {
e.preventDefault();
//alert("Confirming function works");
$.ajax({
cache: false,
type: 'POST',
url: './datacenter.php',
data: $('#update_status').serialize(),
success: function(d) {
$("#successMesg").html(d);
}
});
});
});
</script>
</head>
<body>
<form id = "update_status">
<textarea id="shadow" name ="user_status" placeholder = "Share what is on your mind!" cols="97" rows="1" title="Share what's on your mind"></textarea>
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="button" value="Add Post" title="Your posts will be made public"></input>
</form>
</body>
datacenter.php:
<?php
var UserStatus = user_status
if (!empty(UserStatus)) {
var_dump($_POST['user_status']);
// process as necessary
}
?>
But, including the
<form id = "update_status" action ="datacenter.php" method = "POST">
and changing the button to
<input style="float:right; margin-top: 0.3%;margin-right : 0% !important;" id = "btnStatus_update" name = "btnStatus_udate" type="submit" value="Add Post" title="Your posts will be made public">
will allow users to still post information if they have JavaScript disabled.
the selector for the textarea is incorrect, the id is not "user_status", its "shadow"
data: $("#user_status"),
should really be:
data: $("textarea[name=user_status]")
or
data: $("#shadow")
I am using jquery to change my div contents in the main.php file without refreshing the page,
but issue here is in the new div which is loaded contains a form, in the form action i want the form to be submitted to the same page(div) , but am redirected to the main.php which i don't want. What changes i have to make to the action to stay on the same page with the same div.
This is the code which i use to dynamically change the div.
main.php:
<li id="nav-home"><a class="button" href="main.php">Home</a></li>
<li id="nav-page1"><a class="button" href="page1.php">Page1</a></li>
<li id="nav-page2"><a class="button" href="page2.php">Page2</a></li>
<li id="nav-page3"><a class="button" href="page3.php">Page3</a></li>
<script>
$(function(){
$('.button').on('click', function(e){
e.preventDefault();
$('#content').load($(this).attr('href'));
});
})
</script>
example: when i click on the Page1 in the main.php the div content is being replace by the page1 where in page1 i have a form, when i submit the form i want to stay in the same page.
this is the code which handles the form in the page1:
<form name="form" id="form" method="POST" action=""> //my form elements </form>
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
debug: false,
rules: {
//rules
},
messages: {
//messages
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('scripts/formhandler.php', $("#form").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
You can use the form.submit function, and handle the submit in there using ajax
$('#form_id').submit(function()
{
e.preventDefault(); // Prevent the default form action
/*now add ajax code here to do form submit*/
});
Of course if you're loading the form after the page has already been loaded, you would need to use the jquery.live or jquery.on function to set the form handler instead of the above code. Example:
$('#form_id').on('submit', function()
{
// Code in here
});
You can read up more on .live and .on from the jquery site
You appear to be using validate plugin, and you can use the ajaxSubmit method which will basically wrap a submit call with preventDefault, handle all the form serialization, etc.
http://docs.jquery.com/Plugins/Validation/validate
i.e.
submitHandler: function(form) {
$(form).ajaxSubmit();
}
I am using facebox to display a contact form, however when the user selects submit I would like the action which for this example I shall call action="contact_send.php" to also open in a facebox. Currently it is easy to open a link into a facebox by declaring the rel attribute as facebox
e.g.
Contact
This opens contact.html in a facebox window, I would however like the action of this form to also open in a lightbox, does anyone have any suggestions that might help?
thanks in advance
-Ashutosh
Your HTML FORM
<form id="contactfrm" method="post" onsubmit="return false;">
....your form elements
<input type="submit" onclick="submitContact();" />
</form>
EDIT :
Your Script
Now use jquery to submit form
<script type="text/javascript">
function submitContact() {
$.facebox(function() {
$.ajax({
data: { 'name' : $('#name').val(), 'message' : $('#message').val() }, //Make sure to change these values that reflects yours.
error: function() {
$.facebox('There was error sending your message.');
},
success: function(data) {
$.facebox(data); // the data returned by contact_send.php
},
type: 'post',
url: 'contact_send.php'
});
});
}
</script>
When you click submit button on your page, this code opens facebox and processes the variable you sent to contact_send.php page and returns the output from that page to the facebox.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
<div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?
Many times the default behavior in a form when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>
try return false; in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}
I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....
I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>.