Page change using Ajax, still save data entered - javascript

I am writing a practice website using jQuery's ajax.
Currently I have 3 buttons, each of which, when clicked, shows different contents with forms using ajax call. The contents are stored in different files. Let's say you enter "AAA" in the form in the content shown after clicking the first button. Then you click on the second button, which will replace the first content with the new second one. And you enter "BBB" in the form on there. What I want to achieve is, when you do this, I don't want the page to forget what you typed in the first page (or before you changed the page using ajax call), and at the end, you press SUBMIT button, which is common in all buttons' content. Then, I want the webpage to submit both "AAA" and "BBB" for more computation.
Is this ever possible?
This is kind of like a pizza website. Assume that there are 2 tabs on the website, one for pizza dough option, and the other for topping option. Also assume the pagenation of the tabs happens using ajax by asynchronously displaying the contents. When you choose options in pizza dough tab, and you change the tab to select topping options. Then you finally place the order, which reflects customers' option for both dough and topping.
How could you possibly implement this? Any advice would be greatly appreciated.
Do I need a database using SQL? Since this is a simple practice website, it does not have to remember the customer's options once you submit the form and they close the page.
Here is some portion of my code since I cannot write them all. I also omitted some unimportant parts.
php file1:
<script>
$(document).ready(function(){
$(".dough, .topping").click(function(){
$.ajax({
url: /*URL is either dough.php or topping.php*/
success: function(data){
$(".result").html(data);
},
error: function(data){
alert("error");
}
});
});
});
</script>
<button class="dough">Dough</button>
<button class="topping">Toppings</button>
<div class="result"></div> <!--Here I want to show the content with ajax-->
php file2 (=dough.php) and file3(=topping.php): /*This is the form-containing files and both have the same structure */
<form action="confirm.php" method="POST">
<!--Pizza's dough and topping photos, price and name etc-->
<input type="text" name="******"> <!--This is the input form-->
</form>
In this case, I feel like I should have the final "submit" button outside the form tag because the submit button is common and should stay at the bottom of the page during the course of pagenation.

<form action="confirm.php" method="POST">
<!--Pizza's dough and topping photos, price and name etc-->
<input type="text" class='myValue' name="******">
<!-- this button is for saving the input entered above; for topping form give 'toppings' class-->
<input class='option-button pizza-dough' type='button' value='select'/>
</form>
Add event handler for the above form(s)
$('.result').on('click','.pizza-dough,.toppings',function(e){
//using on() because forms are dynamically added
var myValue = $(this).siblings('.myValue').val();
if(this).hasClass('.pizza-dough') {
localStorage.setItem('pizza-dough', myValue);//store the value in localStorage
}else{
localStorage.setItem('toppings', myValue);//store the value in localStorage
}
});
Now, suppose you have following common submit button
<input type='button' value='submit' class='submit-values'/>
Add event handler for this button to submit the values
$('.submit-values').click(function(e){
var dataToSend = {'pizza-dough':localStorage.getItem('pizza-dough'),'topppings':localStorage.getItem('toppings')};
$.ajax({
url: /*submit url*/,
method: "POST",
data: dataToSend,
success: function(data){
//handle success
},
error: function(data){
//handle error
}
});
});
Adding validation for localStorage values is left for you.
Read more about localStorage and sessionStorage to choose what best suits you.

Related

html submit form ajax response

Im currently loading my pages in Codeigniter using ajax for sections of the page.
but, when i press submit on one of the loaded forms, i dont get the response out from it. its like the form never was sent. im exspecting the layout to be proccessed, instead it returns the same layout as if it wasnt proccessed.
How can i make so, when pressing submit button on the loaded form data, that it will be proccessed by the same url, and then load the new response to the view?
piece of code:
$("form").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$(".main_center").html(data);
});
return false; // prevent normal submit
});
piece of html:
<form method="POST" action="/crime">
<input type="hidden" name="crimeinput" id="crimeAction" value="123">
<input type="submit" value="do" name="docrime" id="krimsubmit" style="display:none">
</form>
EDIT:
After more looking into it, it seems like only the crimeInput variable is sent to the server, and not the docrime. How can i make it able to send the submit name aswell?
As per the docs for serialize:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
So if you want that field to be passed, you'll have to add it in a different way, perhaps as another hidden input.

Update form fields without refresh (prevent duplicated form)

I need to update (submit) form without refresh. I know it should be done using Ajax, so I found many examples on this website, but none of them was useful in my case. Here's the catch - I don't need to display any "success" or similar messages when form was submitted, I need to display exactly the same form, but with new values.
Examining examples on this site, I got it working, but when form is submitted via ajax (this part works fine), I see two forms displayed. Here's the example - http://www.lipskas.com/form/ (the whole source is available to view)
What should I change here?
P.S. If I change "$('#msg').html(html);" to "$('#myForm').html(html);" duplicated form doesn't appear, except one "little" problem - the form can be submitted only for the 1st time. Then no more values are properly submitted.
In case you are interested why I need to display exactly the same form (but with updated fields) again, it's because I built some type of calculator which has many fields, and when user updates ANY field, re-calculations are made ( http://lipskas.com/bandymas/ )
Get rid of the "onclick" in the submit button and add this in the header above the chk function
<body>
<form id="myForm">
<input type="text" name="username" value="submitted - "><br/>
<input type="text" name="password" value="submitted - "><br/>
<select name="some_array[1]"><option value="1">1</option><option value="2">2</option></select>
<select name="some_stuff[2]"><option value="3">3</option><option value="4">4</option></select>
<input type="submit" name="submit_ok" value="test me">
</form>
</body>
function chk(this)
{
$.ajax({
type:"post",
url:"index.php",
data: this.serialize(),
cache:false,
success: function (html){
$('body').html(html);
}
});
}
$(function(){
$("body").on("submit","#myForm",function(){
chk($(this));
return false;
});
});

jQuery get values from current form

Hello everyone I'm working on a project and I'm pretty sure I've made a rather large mistake. Basically I have some PHP code that retrieves some values from a database, and each row gets its own in a table. Then each one has a button that deletes it, which shows a small dropdown form asking for some details along with a submit button. However, I for some reason wasn't thinking that there would be multiple forms, and have each input an id, resulting in multiple elements having the same id.
So, in JavaScript, an AJAX request is made when a user submits deleting a row, and the values from the form (values are found by the ID of the input) are sent as POST variables to a PHP script. Since I'm doing this, the AJAX request only works if they're deleting the first row, but not any under that.
So, this HTML is output by PHP to add a dropdown form to each row:
<td class='dropdown'><a class='dropdown-toggle' href='#' data-toggle='dropdown'><button class='btn btn-warning'>Kick</button></a>
<div class='dropdown-menu' style='padding:15px; width:340px'>
<div class='form-group'>
<form id='delete-form'>
<label for='delete-reason'>Reason: </label>
<input class='form-control' id='delete-reason' name='delete-reason'>
<input type='hidden' id='delete-id' name='delete-id' value='". $value['Name'] ."''>
</div>
<br>
<input type='submit' id='delete-submit' name='delete-submit' value='Delete ". $value['Name'] ."' class='btn btn-default'>
</form>
</div>
</div>
Then I use this JavaScript to submit the form to send the data from the form to a PHP script by an AJAX request.
$("#delete-form").submit(function(e){
e.preventDefault() // stop form from submitting
var reason = $("#delete-reason").val();
var id = $("#delete-id").val()
$.ajax({
type: 'POST',
url: 'php/ajax.php',
data: {
deletereason: player,
deleteid: id
},
success: function(response){
$("#delete-result").append(response);
$("#delete-result").fadeIn(500);
}
})
})
So, like I said, it only works on the first row because on the others, it just gets the values of the first found input with that id. And when I do it on any row besides the first, it adds the values as a query string, which doesn't do anything because well, it's not supposed to.
However I don't really know how to make it where it would get the values from the current form, not the others, and that's why I'm here.
I understand this is all pretty confusing and if you need me to clarify anything or explain more I'd be happy to.
Any suggestions?
You need to have unique id for each form and input element and then follow the answer provided by #ArunPJohny. But if you cannot have unique id for each element then follow below code
$(".form-group form").submit(function (e) {
e.preventDefault() // stop form from submitting
var reason = $(this).find("input[name='delete-reason']").val();
var id = $(this).find("input[name='delete-id']").val();
$.ajax({
type: 'POST',
url: 'php/ajax.php',
data: {
deletereason: player,
deleteid: id
},
success: function (response) {
$("#delete-result").append(response);
$("#delete-result").fadeIn(500);
}
});
});

Passing variables in URL

I have an address book widget that shows if there are contents.
If there are no contents, an add button will show up. Upon pressing the add button, it will redirect to another page which will show the form.
The initial design of my website is as follows:
When the user click the add button, it will direct to a page using javascript function:
document.location.href="address?addOnly=true";
The form will display.
If successful, there are $.post that will change the div only that will enable user to do CRUD in the address book.
The problem with the variable inside the url which is address?addOnly=true is that when the user refresh it, it will always shows the add form.
That's why i've decided to hide the implementation using $.post
$.post('address', {"listEmty":true}, function (data) {
window.location = "address";
});
The problem with this is that it can't pass the variable at all.
My questions are:
How to handle the page refresh if using the get method, which passes the paramater in the URL,
Are there anyways in javascript/jquery to pass the variable using post method then refresh the page?
Thank you.
<FORM method="post" action="address" id="refresh" style="display: none;">
<DIV>
<INPUT type="hidden" name="addOnly" value="true">
</DIV>
</FORM>
<SCRIPT type="text/javascript">
document.getElementById('refresh').submit();
</SCRIPT>
What this does is create an invisible form, then immediately submits it. You can of course call the submit from within your other javascript code.

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

Categories

Resources