Jquery .load and POST data - javascript

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.

Related

Page change using Ajax, still save data entered

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.

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

ajax post refreshes the page when it shouldn't

I have a uses jquery post answers to a grader.php script, which works perfectly. Depending on the results, it brings a form so they can send message with contact info. When I try to post to the second script to process the mailer, the whole page refreshes without posting the data or returning the appropriate message. It turns out the call is not being made at all. If you want to see the staging site you're welcome to look. It's kind of a cheesy way for me to get my feet wet with jquery. However, I believe the suspect script is here.
I added an alert to the click event to see if it even triggers the click on the score button. No alert triggers and all I get is a page refresh.
Alternatively, is there any way log posts and console data to see exactly what's happening?
HTML:
<div id="result">
<form id="info" method="post" action="">
<input name="phone_number" placeholder="phone number" type="text" size="20" value="">
<input name="email_address" placeholder="email address" type="text" size="30" value="">
<textarea cols="50" rows="10" placeholder="Questions? Comments?" name="comments"></textarea>
<input type="submit" id="score" name="score" value="Send">
</form>';
</div>
Jquery:
$("#score").click(function(event){
alert("clicked");
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var info = $("#info").serialize();
$('#result').fadeOut().html("");
$.post('paider.php', info, function(data , status){
$('#result').fadeIn().html(data);
alert(status);
});
});
I think there are 2 problems here.
Problem 1:
As the form resides inside #result, setting #result's html to "" effectively empties the form before serialization? Have you tried?
$("#score").click(function(event){
var info = $("#info").serialize();
$('#result').fadeOut().html("");
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$.post('paider.php', info, function(data , status){
$('#result').fadeIn().html(data);
});
});
Problem 2:
Okay so I took a look at your staging site and think I've found the issue. You begin by having a form similar to the one in the question on this topic, but you then "replace" that form with a new form containing now a "#score" element (input type='submit').
You are applying your jquery event handler on document load but at that time the #score element does not yet exist in the DOM because you have not loaded it yet.
You believe you are running the script inside $("#score").click but in fact the page is simply using default behavior of a form with no action and a submit button.
To correct this issue you need to apply the event handler at either a higher level in the DOM tree OR you can do some easier way just to test if this is the problem
Please try this in your first #submitbuttonclick handler
$("#submitButton").click(function(event){
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var formdata = $('form').serialize();
$.post('grader.php', formdata, function(data , status){
$('ul').css('display', 'none');
$('#result').fadeIn().html(data);
//Here add the handler for #score click
$("#score").off("click").on("click", function(event){
//Insert code snippet shared above here
});
});
});
What this will do is bind the click event on the #score submit button after it has been written into the DOM. In case the script executes more than once we do not want the handler to fire multiple times, which is why we first call "off".
Hope this helps.

Mutiple Form Submission Failing to Work

Can someone help me please. I had replies to a similar question but am unable to solve my problem so I have tried to be as detailed as I can here. Sorry if it's a repeat but I am really in need of help on this.
I am trying to submit three forms to the same asp page via a mouseover event. The asp page executes code to save an image according to which form was submitted and the data it contains. I have tried several ways to do this. Submitting in turn as shown below results in some or all of the images being created, but it is random and it seems subsequent submissions are overwriting previous calls.
function save_all_des(){
document.getElementById("form_zoom1").submit();
document.getElementById("form_zoom2").submit();
document.getElementById("form_zoom3").submit();
}
I have also tried using jquery like this:
$("#create_image").mouseover(function() {
$("#form_zoom1").submit(function() {
$("#form_zoom2").submit(function() {
$("#form_zoom3").submit();
});
});
});
This doesn't work at all, even if I try just one form. (The mouseover event itself fires ok.)
The three forms have the same input names (I've shown just one) but with different values. Individually they submit ok.
<form id="form_zoom1" name="form_zoom1" action="abc.asp" target="MyFrame">
<input type="hidden" name="tab" value="1">
</form>
<form id="form_zoom2" name="form_zoom2" action="abc.asp" target="MyFrame2">
<input type="hidden" name="tab" value="2">
</form>
<form id="form_zoom3" name="form_zoom3" action="abc.asp" target="MyFrame3">
<input type="hidden" name="tab" value="3">
</form>
<iframe id="MyFrame" name="MyFrame" style="display:none;"></iframe>
<iframe id="MyFrame2" name="MyFrame2" style="display:none;"></iframe>
<iframe id="MyFrame3" name="MyFrame3" style="display:none;"></iframe>
How do I make sure the code behind the one form submittal is fininshed before the second, then third, is submitted?
Any help appreciated.
Thanks
It sounds like you'd be better off using AJAX to send POST requests to the server, rather than actually submitting the form. You could possibly send all three requests at the same time, and have it work correctly, but that depends on exactly what you're doing with the response from the server after the submit.
Take a look at the jQuery Documentation for more information on using it to perform AJAX calls.
Sample code may look something like this:
function submitForm(form) {
$.ajax({
url: 'abc.asp',
method: 'post',
data: {
tab : $('input[name="tab"]',form).val()
},
success: function(data) {
/* handle the response from the server here
if you don't need to do anything to the structure of the page, you can probably just leave this blank
may want to put in some console.log or alert statements for debugging purposes
*/
}
});
}
$('#create_image').mouseover(function() {
submitForm($('#form_zoom1'));
submitForm($('#form_zoom2'));
submitForm($('#form_zoom3'));
});
Note that that sends three AJAX POST requests, one for each form, at roughly the same time. There's no guarantee that they'll complete in that order (though this doesn't seem important given the information you've provided).

jQuery - reset form after submit w/ form plugin

let me start by saying it may look simple but im finding it extremely difficult.
ive made a search script that uses PHP and to fetch a result would look like this
search.php?term=alice&submit=Submit
Standard stuff.. problem is, i use an SPI with AJAX and PHP so my results would have to load dynamically into a div, whilst still keeping the hash value, as not to lose the page the user had visited previous to searching.
jQuery.history.js is the plugin i use for back button support, which requires links to be like such:
Home Page
this would load 'home.html' into a div named pageContent. as far as i know theres no way to call php files unless you develop a little hack, which i have,
here is my JavaScript/jQuery for my search form:
<script language="JavaScript">
$(document).ready(function() {
// bind form using ajaxForm
$('#search1').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#pageContent',
// success identifies the function to invoke when the server response
success: function() {
$('#pageContent');
var hash = '#search.php?term='+($('#query').val()+'&submit=Submit').replace(/ /g, '+');
var stripped = hash.replace(/(<([^>]+)>)/ig,"");
update(window.location.hash = stripped);
}
});
});
</script>
Heres the form:
<form id="search1" action="search.php" method="post">
<input id="query" type="text" name="term" />
<input type="submit" name="submit" value="Submit" />
</form>
My problem is this:
ive tried this.form.reset(); this: Resetting a multi-stage form with jQuery , yet none of this works. please help me if you know a way of doing this..
$('#query').val(DefaultValue);
with this u can set your value to whatever you want, like blank: '';

Categories

Resources