Jquery form submit behavior not understandable - javascript

I am writing code for a small webproject using js and jquery. In it, at some point, onclicking a button, i create a dialog. the dialog has a form within it with a name field and some number fields. I am supposed to check user inputs and send them to server, along with appending the name field to a list in the browser, to intimate user, one more item has been added. Two strange things are happening -
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
2) The name entry doesn't get appended to the list. Its as if the whole page refreshes after the submit. With the original default entries of the list of names.
Anyone has any ideas on why this is happening? Would post some code for your aid.Please don't suggest to use Ajax instead. I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
<div id='dialog' title='Define New Matrix'>
<form name='form1' id='form1' method='post'>
<fieldset>
<label for="Name">Name</label>
<input type='text' name='nameofmatrix' id='Name' class='whitepanes'><br>
<label for="a11">a11</label>
<input type="text" name='a11' id='a11' class='whitepanes number-field'><br>
<label for="a22">a22</label>
<input type="text" name='a22' id='a22' class='whitepanes number-field'><br>
<button id='submit_button'>Submit</button>
<button id='cancel_button'>cancel</button>
</fieldset>
</form>
<p id='tip' style='color:red;'><i>All fields are required</i></p>
</div>
<script>
//#button_define is a button on whose clicking the dialog opens.
$('#button_define').click(function(){
$('#dialog').dialog('open');
$('#tip').html("<p style='color:red; font-size:small'>All fields are mandatory</p>");
});
$('#submit_button,#cancel_button').button();
$('#cancel_button').on('click',function(){
$('#dialog').dialog('close');
});
$('#submit_button').click(function(event){
event.preventDefault();
var name=$('input[name=nameofmatrix]').val();
//Validate is a function which returns a bool if validation proceeds correctly
var isCorrect = Validate();
if(isCorrect){
//if validated correctly then add to list
$('#form1').submit();
//$('#dialog').dialog('close');
$('#selectable').append("<li class='ui-widget-content'>",name,"</li>");
}
});
</script>

Its as if the whole page refreshes after the post. with the original entries.
That's precisely what happens. Though I'm not sure where you're submitting the POST request to since there's no action attribute on your form. But a standard non-AJAX request triggered by a form sends the request to the server and then renders the response from the server. If the response is this same page again, then this same page will be rendered again.
JavaScript isn't going to remember the state of the previous page when it loads this new response. Even if they're the same page, they're two separate responses from the server. So...
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
The dialog isn't closing. After the page refreshes you're in an entirely new page context. It didn't close, it just hasn't been opened yet in this context.
2) The name entry doesn't get appended to the list.
There's nothing that would cause this to happen when the page loads, so in the new page context it doesn't happen. Your server-side code would need to include this content in the response to the POST request.
I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
Included in that misunderstanding is the fact that AJAX is part of JavaScript. (The "J" in "AJAX" stands for "JavaScript.") It's not "switching to some other technology." It's taking advantage of the capabilities of the technology you're already using. All AJAX does, really, is send requests and receive responses to/from the server without refreshing the page context.

You are not properly appending the name. The concatenation operator is not a comma, but a + in javascript:
$('#selectable').append("<li class='ui-widget-content'>" + name + "</li>");
Next, the form refreshes because you are submitting the form using $('#form1').submit();. If you do not want the page to refresh while submitting, use ajax.

Related

jQuery Submit Hidding Field on Page Load

I am trying to add some additional tracking information to a site. I want to place a hidden field on every page that pulls in the URL of the initial page the person landed on, and submit that value to a form on another page, without ever leaving the landing page.
So for example, someone lands on a blog post and this hidden field submits that value to the form but the client never leaves the page. This person clicks through to various areas of the site, and decides to submit a form. That form submission will then contain the value of the initial page that was landed on. This would only be able to happen on the initial page though, because if it re-submits the value on every page the person visits it will not show the initial page the person started on.
Hopefully that makes sense. Any ideas, or am I pretty much just looking at buying expensive software that already does this type of thing?
$(function () {
$('#form-track').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/schedule-service" method="post" id="form-track">
<input name="form-source" value="THIS URL IS DYNAMICALLY GENERATED" type="hidden">
</form>
Try this... the value will then be set in a cookie called "landingURL"
if (document.cookie.indexOf("landingURL=") < 0) {
URL = insert URL HERE...
document.cookie = "landingURL="+URL;
}

Page changes when i submit the form

<form action="/devilmaycry/register?action=addtocart" method="post">
<input type="hidden" name="user" value="<%=user%>"/>
<input type="hidden" name="pid" value="<%=pid%>"/>
<input type="submit" value="Add to cart" onclick="add();"/>
</form>
i am using the above code to submit a form and add a product to cart
the java code it calls is as follows:
else if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==1)
{
pw.println("<h3>Added to cart !!!<h3>");
}
else
{
pw.println("<h3>Errror , try again <h3><br>");
}
it does add the product to the table but it changes the jsp page ... i tried to use requestDispatcher but the URL has many parameters so i want something else through which i can retain the same page and update the table also
In order to stay on the same page you need to use AJAX rather than submit the form in the traditional way. HTTP works in a request-response fashion, so when the user submits the form, the browser expects to receive a new page in the response from the server, and will thus refresh the page and render the new HTML it receives.
You have two options here:
Stick with the traditional HTTP form submission request-response approach, and when you receive the request on the server to add an item to the card, after you add the item to the card, rebuild the URL of the page that is showing the information to the user. In this case it is important to use the 'Redirect-After-Post' approach (i.e. in the response to the form POST you put a redirect to the page). Otherwise if the user refreshes the page by pressing F5, the form data will be resubmitted again and the item added again to the cart.
Go for an AJAX approach. In the add() function, you need to submit the form using Javascript. If you are using JQuery it makes it very easy for you to do this. There are various questions / examples if you search around, such as the one here.
In the latter case you will need to change a bit how you process the information from your Servlet but its the only way to get the browser to stay on the same page (without reloading it). You also have the success and error handlers, which you can use to show a message on the screen to display the result.

AJAX form checkbox array value gets "stuck" hanging

To make it really short and simple.
I have an AJAX form with method="GET", because I want to reflect all the changes in the URL (and for it to be accessible afterwards).
And the form is getting submitted to the server automatically when either of form elements is changed. On the server I rewrite the URL by using "history pushState".
I'm using Ruby-on-Rails as a server-side technology, if it matters.
One of the elements checkbox array (multiple elements can be chosen) - it is a list of parameters that user would like to see.
Now to the problem itself - suppose we visit this page for the first time.
None of checkboxes is checked so far. Then we check, for example, first checkbox.
Event is triggered - form is getting submitted -> url is rewritten properly.
Then I uncheck this checkbox -> event is triggered -> form gets submitted -> url is rewritten properly again!
Everything is correct so far.
And now the case that does NOT work.
I check this checkbox -> form is submitted -> url rewritten. Correct. And after that I hit "refresh" (F5 or Ctrl-R). I see that the checkbox is checked (as it is supposed to be), but ... I attempt to UNCHECK this checkbox, BUT for some odd reason on the server-side I still see this array value reaching the server. And, of course, it is reflected in the URL as well - it is present there (while it should not).
Sorry for messy explanation.
I'm I doing something extremely wrong?
P.S Form works correctly with ordinary parameters (fields, mainly).
P.P.S I was really curious - what is going on there, and I even attempted to see form values before they got submitted to the server by executing following code:
$("#my-form").on("ajax:beforeSend", function(){
console.log("FORM BEFORE SUBMISSION: " + $(this).serialize());
});
And the checkbox is absent there. Which is correct!
Thanks in advance!
P.P.P.S This is how my idea is implemented in general (very briefly):
<form method="GET" action="/search/?" id="my-form" data-remote="true">
... (some form elements here as well)
<input type="checkbox" name="search[types][]" value="1">
<input type="checkbox" name="search[types][]" value="2">
<input type="checkbox" name="search[types][]" value="3">
... (and submit button)
</form>
$("#my-form").change(function(){ $(this).submit(); });
Sorry everyone for wasting your precious time.
I found the problem - I used query-params as form "action" attribute, so submitting the form caused query params duplication every single time I refreshed the page before submitting it.
Easy :) Should have thought about it in the first place.

One Form, with 2 actions

I am attempting to create an HTML form, that of which uses the submit button, to email me the data that has been entered (have that part covered) but also send the data to another external page (that can handle this request).
I can have it working by doing:
<form name="contactform" method="post" action="http://somesite.com/page.php">
But, I also need it to submit to a local page (form.php) at the same time.
I have tried javascript, by doing this for the submit button:
<input type="submit" value="Submit" onclick="return doSubmit();">
With this code in the source:
function doSubmit()
{
document.contactform.action = "form.php";
document.contactform.submit();
document.contactform.action = "http://somewebsite.com/page.php";
document.contactform.submit();
return true;
}
But when I do this, the information is not sent to my email, and instead of displaying the result on form.php the page is refreshed.
Any ideas on how I can make this work in a simple way?
You can't submit to multiple actions at the same time as the browser can only load one request per window at a time by design. Some solutions include:
Just do the email handling with the same server script that does the form input handling
Send the form data to the email script via ajax and then submit the form normally on completion, e.g.
I would recommend adding/altering a function in your php script. Then you can do whatever you like with the posted data.
Obviously you cannot submit two forms. You can try either of these two things:
Make one of them an ajax request, and set it to be executed before submit.
Execute the second php file directly from the first one in the server
side.

Submit form values to a script without loading a new page

I have an issue regarding sending form values to a script. I have a form set up, and upon the user pressing a button I want the values in the form to display on another part of the page. I can easily do this with php or another web scripting language, but all I know is how to do this by sending it to the script in a form of
http://www.example.com/myScript.pbp?value1=VALUE
is there a way to do this without loading a new page? Like just show a loading overlay on the page until the script completes and displays the value on the page?
I'm guessing this would be accomplished using Javascript or Ajax or something like that.
If anyone could help me out, or even just say where I should start to look, I'd really appreciate it!
Indeed. Just attach an onsubmit event listener to your form that always returns false to prevent actual sending of your form via the usual GET or POST request.
In your event listener you can send the form values using XMLHttpRequest and let the callback function update the relevant part(s) of your page.
But remember to always create a fallback option (with the usual GET or POST request of the form) to handle your form in case JavaScript is not available (e.g., turned off, blocked, etc.).
Yes AJAX would be exactly how you would do it. Have a look at the tutorial over at Tizag: http://www.tizag.com/ajaxTutorial/index.php
That will get you started in no time at all.
If you just want the values in the form to display on the page again without any interaction with the server then something like jQuery would be the best approach.
Jquery has a nice form plugin that you can do the following:
var form_values = $('#form_name').formHash();
the form_values will then be a hashed array of your form values in the system i.e.
<form id="test">
<input id="test1" name="test1" type="text" value="Test Text"/>
</form>
So form_values['test1'] would hold the value Test Text in it
Once you have the values you could then use some other jquery functions to display them on the page i.e.
<div id="displayDiv"></div>
then your javascript could be
for (key in form_values) {
$('div#displayDiv').append('<div>Key: ' + key + ' Value: ' + form_values[key] + '</div>');
}
This would put your values in the display div
Here is a simple javascript ajax object. You can use without loading any library.

Categories