Posting Div Content in Php - javascript

I have two php pages. In the first.php page user choose orders and a div is filling with this content, no problem. And there is a confirm button to confirm these list. When the user click this button, second.php page should be opened and the contents of the div should be displayed on that page. This is my html code for the first.php div and confirm button.
<form method="post">
<div class="col-md-5" id="orderList">
<h3 align="centre">Order List</h3>
</div>
</form>
<form role="form" method="post" action="second.php">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" id="firstConfirmButton" class="btn btn-primary btn-lg">Confirm</button>
</div>
</form>
This is the javascript code to post the contents to second.php. First alert is working fine but second alert is not.
$("#firstConfirmButton").click(function() {
var content = $('#orderList').html();
alert(content);
$.post("second.php", { html: content})
.done(function(data) {
alert(data);
$('#confirmForm').empty().append(data);
});
});
Second.php page has the confirForm div and I want to display the contents in this.
<div id="confirmForm"> </div>
Where is the problem?

Your button is a submit button, so if you don't cancel the default event, the form will be submitted the regular way as well.
You need to capture the event and cancel it:
$("#firstConfirmButton").click(function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
Or in modern versions of jQuery:
$("#firstConfirmButton").on('click', function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code

You submit the form to the page second.php by using the POST method, so the data can be retrieved from the second page by using this PHP code:
var_dump($_POST);
So basically, the data is stored within the $_POST array.
Regarding your second question. You need to avoid that you submit the default form if you first need to grab a value form a Javascript. You can do that by something like that:
$("#firstConfirmButton").click(function(e) {
var data = $('#orderList').html();
e.preventDefault();
//...
}
This will avoid that your submit button submits the form without adding the desired POST data to it.

Related

Is there a way to submit a form that's loaded from a separate page via ajax within the same window?

I have this form:
<form method="post" action="/cart" id="ajax">
{...}
<div>
{{ product.option | hidden_option_input }}
</div>
<button name="submit" type="submit" title="add to cart">Add to Cart</button>
</form>
The form is being loaded to the page via ajax, and its action page also preloaded via ajax in a different link in the navbar. I'd like to submit the form but prevent it from opening a new page when submitted. How can I go about this? I've tried:
Add to Cart
to replace the button, but even though I've attempted to negate the default behavior with "return false;" it still reloads a new page on click. I can see the linked popup window just before the new page load, but it does not submit until the new page appears. I believe it's because the form is being loaded via ajax when a user clicks the link to it, therefore I cannot attach a script to it specifically because until it's on screen, it does not technically exist.
If I understand your question, you would like to just update a portion of the current page. If so, you will have to use AJAX for this:
Keep the "submit" button but make it a standard button and give it an id such as "submit":
<button id="submit" name="submit" title="add to cart">Add to Cart</button>
Then your JavaScript would handle the click event on the button as follows:
$(function() {
let submit = $('#submit');
submit.click( function() { //
submit.prop('disabled', true); // prevent a re-submission
var form = $('#ajax');
var request = $.ajax({
url: form.attr('action'), // get the action from the form
type: form.attr('method'), // get the method from the from
dataType: 'html', // the assumption is that we are dealing HTML here
data: form.serialize()
});
request.done(function(ajaxResult) {
// update the DOM with the results
$('#some_div').html(ajaxResult); // replace contents of <div id="some_div"></div> with new html
submit.prop('disabled', false); // re-enable the submit
});
});
});
You have to arrange for the results sent back to be just the HTML that is required to be updated.
Update
Since responding, you have added a comment with a link that suggests I may have misunderstood your intent. The phrase you used, "submit the form but prevent it from opening a new page when submitted" definitely can lead one to my original interpretation.

Why is this dynamically assigned id using a loop only showing the first assignment? javascript, AJAX & JSTL

Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot

Partially update the current form if the target form has an error, else submit the target form

I have this idea for the script below:
What the script should do is that when the form id="try" is submitted by clicking the submit button, it would not be submitted immediately but rather check if there would be an error on the page where the form is to be submitted.
If there is an error, I can just display an error message by partially updating the div id="content" saying, "Sorry, your user action is currently not possible due to an unexpected issue."
If it has no error (the page "try1.php" was found and has no runtime errors on it), we submit the form and go to "try1.php", not that the contents of the "try1.php" would be sent into the div id="content"
HTML:
<div id="content">
THIS IS THE DIV: "content"
</div><br>
<form id="try" action= "try1.php" method="post">
<input type="submit" value="Try">
</form>
jQuery:
$(document).ready(function()
{
$("#try").submit(function(e)
{
e.preventDefault();
// get the action
var action = $(this).attr("action");
$("#content").load(action, function()
{
//if the action is loaded to the <div id="content"> without any errors:
document.getElementById("try").submit();
//else if the target page has an error:
$("#content").html("Sorry, your user action is currently not possible due to an unexpected issue");
});
})
});
I'm new to jQuery, do you have any advise on how can I do the if else statement? Is jQuery the right thing to use or are there other solution for this?
Thanks in advance.
Changing the form submit button to a regular button would help, as making this button call a function would do the trick, like:
<form id="try" action= "try1.php" method="post">
<input type="button" value="Try" id="submitButton"/>
</form>
Then in the JavaScript part:
$(document).ready(function()
{
$("#submitButton").click(function(e)
{
e.preventDefault();
// get the action
var action = $("#try").attr("action");
$("#content").load(action, function()
{
//if the action is loaded to the <div id="content"> without any errors:
document.getElementById("try").submit();
//else if the target page has an error:
$("#content").html("Sorry, your user action is currently not possible due to an unexpected issue");
});
})
});
Hope it solves the problem. For more clarifications, please comment.

What do I need to use to submit a form while opening up a modal?

I'm trying to create an 'edit' button for a post that when clicked will both submit the form which will pass in the post id and call a modal(I'm using bootstrap modal). The modal that opens up will show the content from the passed in post id.
however, I' having trouble coming up with a tag that will both submit and call the modal(href). I have tried combinations of anchor tags, input tags and button tags but neither really seem to work together to achieve the goal. I'd appreciate any advice. Thanks
<form>
<a class="btn" data-toggle="modal" title="edit" id="editbtn" href="#myeditModal">
<input type="submit" name="edit" id="edit"></a>
</form>
----the modal div -------
<div class="modal hide" id="myeditModal">
If I've understood your question correctly, I'd simply use a JQuery click function on a submit button, so for example:
User clicks submit button on form
JQuery click function opens modal
Return true
Form gets submitted
If you need the modal to remain open during an Ajax post, then just serialize the form using the same click function, post, wait for response, and return false.
UPDATE:
For example:
$(".your-submit-button").click(function() {
// Do something with modal box
$("#your-modal-box").show();
// Do ajax request
var url = $(this).parents("form").attr("action");
var params = $(this).parents("form").serialize();
$.post(url, params, function(output) {
// Optionally do something with the output of ajax request
});
return false;
});

Collecting form data and removing or hiding a form field using JQuery

I'm currently working on a problem that basically involves processing all data in a form, saving it, and replacing the entire form with a text link. My primary goal is to convert a form, with some data using the POST method, and a submit button, into a standard text link that can then take the saved/serialized data and POST it to the server as if it were the original form; and when JS is disabled, the standard form and submit button is presented, i.e. a graceful degradation. I'm currently using jQuery, I know it's possible to process form data by serializing it, but I'm not sure how to go about removing or hiding (whichever one is possible) a form completely so it doesn't interfere with the layout of surrounding HTML element.
In summary:
-Is it possible to remove or hide an entire form field with jQuery?
-When jQuery serializes form data, where is it saved to?
-Can that saved data be referenced by a text link (i.e. Submit") somehow and POSTed as if it were a standard form?
Thank you.
UPDATE: Ok, I implemented Franz's code in a separate JS file I call from my test.html page. The content of the JS file is as follows:
$(document).ready(function() {
//Store form data before removing
var tempStorage = $('.postLink').serialize();
// Remove form:
$('.postLink').remove();
//Assign onClick event to anchor tag
$('.submit').click(function(){
$.ajax({
//aspx page
url:"doSomethingImportant/10",
//Using POST method
type: "POST",
//The data object
data: tempStorage,
//No caching
cache: false,
//Alert on success
success: function(html) {
alert('great');
}
});
});
});
The only difference here is I'm using the class attribute as an identifier for the forms I want removed as opposed to id. Again, this is what I'm tasked with, not by choice. For some reason, however, it doesn't make it to the alert message, i.e. it doesn't work. Below is the snippet of html I'm having the script act on:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<style type="text/css">
h1.intro {color:blue;}
p.important {color:green;}
h2.outro {color:DarkGreen;}
</style>
<script type="text/javascript" src="jQuery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Form2Link.js"></script>
<title>Form Remover demo</title>
</head>
<body>
<h1 class="intro">Hello World!!</h1>
<p>How's it going??</p>
my First Link
<form id = "myForm" name="myForm" action="doSomethingImportant/10" class="postLink" method="post">
<input type="submit" id="submitThis" name="submitThis" value="clickThisLink"></input>
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
</form>
<a class="submit" href="">Submit Link</a>
my Second Link
my Third Link
<br>
<br>
<form action="doSomethingImportant/10" method="post">
<input type="submit" id="submitThis" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>
<form action="doSomethingImportant/11" method="post">
<input type="submit" value="clickThisLink"></input>
<input type="hidden" value="12345" name="antiCSRF"></input>
</form>
<h2 class="outro">That's nice, gotta go.</h2>
</body>
</html>
UPDATE 11/10/09:
Ok, I've found an alternate way of going about this problem by hiding the form and adding an anchor tag immediately after the form. I then attach a click operation to the anchor that acts on the submit button in the hidden form. My problem now is that this only works with one form defined in the DOM, I want to come up with a generalization of this function so that it works with several forms. How can I traverse each form and replace it with its own unique link?
Code for my current script:
/**
* Hide forms on page load.
* Call submit button within a form from a link
*/
$(document).ready(function() {
//Hide form:
$('.postLink').hide();
//Append a anchor tag after each form that is replaced
$('.postLink').after("<a class=\"submitLink\" href=\"#\">Submit Link</a>");
//Submit button in hidden form
$('.submitLink').click(function(){
$('#myForm').find('input#submitThis').click();
return false;
});
});
Part 1 is easy:
$('#yourform').hide();
EDIT: (to the best of my understanding - using ScottE's step-by-step idea)
Part 2:
Save the form in a local variable:
var tempStorage = $('#yourform').serialize();
Part 3:
Assign a function to the onClick event of your link that sends the data via an AJAX request:
$('#yourbutton').click( function() {
$.ajax({
// Your PHP processing script goes here
url: "yourfile.php",
// You wanted to use POST, right?
type: "POST",
// The data object (I hope, it's accessible here)
data: tempStorage,
// We don't need caching
cache: false,
// A function that gets executed on success
// Note that you have the response of the script in the html variable
success: function(html) {
alert('great');
}
});
});
If I understand what you're looking for, you could do the following:
handle the submit event of the form.
store the form data in a local variable in js - look to http://docs.jquery.com/Ajax/serialize
hide the form
show the link that will submit the form (again), and handle it's click event, initiating an ajax call where you pass in the local variable created in step 2.
This seems like an odd request...
Ok all, I went the route of hiding all my forms and appending anchor tags following each form based with class="postLink", I added a conditional statement that adds a unique ID if a form doesn't already have one, the script then adds an anchor tag with the unique ID and the value of the submit button to the end of the hidden form. A separate click function the processes the submit button in the hidden form that is tied to an anchor tag by the unique ID. Code follows:
/**
* Hide all forms with class="postLink" on page load.
* Call submit button within a form from an anchor tag
*/
$(document).ready(function() {
//Hide form(All forms with class="postLink" will be hidden):
$('.postLink').hide();
var num = 0;
//Loop over each form with a postLink class
$("form").each(function(){
//Add value of submit button as name of text link
if($(this).hasClass("postLink")){
//Get value attribute from submit button
var name = $(this).find('input#submitThis').val();
//Add a uniqueID if the form has no id
if($(this.id).length == 1){
this.id='uniqueID'+num;
num++;
}
var id = $(this).attr('id');
//Append a anchor tag after each form that is replaced
$(this).after("<a id="+id+" class=\"submitLink\" href=\"#\">"+name+"\</a>");
}
});
//Submit button in hidden form by clicking associated anchor tag
$('.submitLink').click(function(){
var anchorID = $(this).attr('id');
//Find the form id that matches the anchor id
$("form").each(function(){
if(this.id == anchorID){
$(this).find('input#submitThis').click();
}
});
return false;
});
});

Categories