How to make Dojo as generic while submitting a form? - ajax

I have the following dojo (ver 1.9) code:
require(["dojo/dom", "dojo/on", "dojo/request", "dojo/dom-form"],
function(dom, on, request, domForm){
var form = dom.byId('user_login');
var selectedTabId = showIdOfSelectedTab();
// Attach the onsubmit event handler of the form
on(form, "submit", function(evt){
// prevent the page from navigating after submit
evt.stopPropagation();
evt.preventDefault();
// Post the data to the server
request.post("login1.php", {
// Send the username and password
data: domForm.toObject("user_login"),
// Wait 2 seconds for a response
timeout: 2000
}).then(function(response) {
dom.byId(selectedTabId).innerHTML = response;
});
});
}
);
And html below:
<form name="user_login" id="user_login">
User name: <input type="text" name="user_name" id="user_name" /><br />
Password: <input type="password" name="user_password" id="user_password" /><br />
<button id="submitbutton" name="submitbutton">Submit</button>
</form>
I want to make the above dojo code as generic by sending the post action (login1.php) and the form id (i.e., user_login). I tried several ways but I could not achieve it.
Please let me know if any of you have idea.
Thanks in advance.
-Uday

This is the demo drom the dojo Tutorial right?
http://dojotoolkit.org/documentation/tutorials/1.9/ajax/
Did you get any Errormessages?
So let's see.
Have you load the dojo libary correct? If not, the widgets can't be loaded.
Must be somthing like:
src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js">
Check the path to the login1.php.
If it's in another Folder than your code the path must be something like "../myfolder /myphp/login1.php"
Regards, Miriam

Related

AJAX shows different behaviors in an if/elseif-statement which is inside the success function [duplicate]

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

Get the ID from a button which has a dynamic ID

I can not grasp my mind around this.
I am making a ajax call into a servlet. The problem is, on the page that is displayed, i could have 1-20 different buttons that needs to recall the same servlet. So I have the following form...
<form id="ajax-contact">
<input type="text" value="${item.transactionId}" id="transactionId" name="transactionId"/><br>
<input type="text" value="deliveryReceipt" id="action" name="action"/><br>
<input type="text" value="${item.id}" id="id" name="id"/><br>
<button type="submit" id="${item.id}" class="btn btn-primary" data-toggle="modal" data-target=".${item.id}">view delivery receipt</button>
</form>
In my ajax, I have this...
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
//var formData = $(form).serialize();
var id = $("#id").val();
var tranid = $("#transactionId").val();
var action = $("#action").val();
var dataFromForm = "trannsactionId="+tranid+"&action="+action+"&id="+id;
alert(dataFromForm);
alert(formData);
// Submit the form using AJAX.
$.ajax({
url : "Controller",
type: "GET",
data : dataFromForm,
dataType: "json",
})
.success(function(response) {
...
I am trying to make it so the ajax call uses the params for the specific set of information within the form. How can I do this?
Thanks!
More detail:
Once this page shows, if I have 10 sections on there with a button. When I click on the first view delivery receipt button, it works fine.
If I go down my list and click on t he 8th view delivery receipt, itll make an ajax call for the first form.

MVC form post not reaching controller

I have a form that on submit doesn't reach the controller method (I put a breakpoint there)
[HttpPost]
public ActionResult SaveBilling( FormCollection fc )
{
...
}
the frontend code is something like this
<form action="/PersonSettings/SaveBilling" method="post" >
...
<input type='submit' value="save" />
</form>
any ideas ?
not sure if it is a route handler problem because it does reach the GET version if i go to /PersonSettings/SaveBilling in browser but the post method just yields a blank page and doesnt go into the code
Rewrite your view as:
#using (Html.BeginForm("SaveBilling", "PersonSettings", FormMethod.Post))
{
....
<input type='submit' value="save" />
}
Is this controller in any area or not?
I realize this has been solved, but I thought I'd tack on another possible cause: Having the [ValidateAntiForgeryToken] attribute on your method without an #Html.AntiForgeryToken() in your code will create the same problem.
Turns out it was a routing related issue after all , I have some complex routes and the default mvc route was catching things that should have gone through the default mvc route with areas.
Was able to recreate the issue by having explicit parameters for my function instead of a formcollection, so that might have been the issue ohwell.
use form and define action path.
<form id="subscriptionForm" action="/Category/Create" method="post">
--your div
</form >
Now use script to serialize the form
<script type="text/javascript">
$('#Save').click(function () {
var form = $("#subscriptionForm");
var url = form.attr("action");
var formData = form.serialize();
$.post(url, formData, function (data) {
$("#msg").html(data);
});
})
</script>
Now you can reach your controller action.
Sometimes using a network sniffing tool like Fiddler is helpful to see what's wrong when the request is sent and it seems not reaching the server.

Why is a form's submit event not firing (jQuery)?

I have a form + layout like so:
<form ...>
<div id="editor">
[form html]
<input type="submit" value="Submit form" />
</div>
</form>
And the following javascript:
$(function() {
var form = $('#editor').parents('form');
alert(form.length); // this alerts "1"
$(document).on('submit', 'form', function() {
alert('document form submit fired'); // this works as expected (alerts)
});
form.on('submit', function() {
alert('selected form submit fired'); // this is never alerted
});
});
This form is not loaded via ajax. When the page loads, the first dialog alerts "1". However when submitting the form, only one alert is fired -- the one that triggers submit for all forms in the document.
Why would this happen?
It does work. Something else is happening which is preventing the second alert from firing.
Your form selector is incorrect.
Try and do this
$("form").on('submit', function() {
Pretty sure this should work
Actually if nothing is being loaded through ajax or dynamically through javascript
You can just do
$("form").submit(function() {
EDIT
Scratch my above. Didn't see you set the value of form. Check out http://jsfiddle.net/s3fvM/1/. Seems to be working fine to me. both are firing and alerting.

Grails WebFlow with Ajax

I am trying to transition to next state of a WebFlow using Ajax requests. But it stays in the same state and returns the GSP as response for that state while I am expecting the GSP for the next state.
Following is the WebFlow code:
def gettingStartedAjaxFlow = {
flow1 {
on("next") {
println "flow1"
}.to("flow2")
on("skip").to("flow2")
}
flow2 {
on("next") {
println "flow2"
}.to("flow3")
on("skip").to("flow3")
}
flow3 {
on("next"){
println "flow3"
}.to("finish")
on("skip").to("finish")
finish {
redirect(action:"index")
}
}
}
Following is the Ajax call I am making for the state transition:
$.ajax({
type: "POST",
url: "/UN/user/gettingStartedAjax",
success: function(data) {
$("#wizardDiv").html(data);
}
});
The GSPs for each state (flow1, flow2, flow3) contains a a code fragment having remoteForm & required next and skip submit buttons to transition to next state and as a result update the "wizardDiv" div. Following is the GSP fragment for flow1 state:
<g:formRemote name="flow1Form" url="[controller:'user', action:'gettingStartedAjax']" update="wizardDiv">
<p>You are in flow 1</p>
<g:submitButton name="next" value="Next Flow" />
<g:submitButton name="skip" value="Skip Flow" />
</g:formRemote>
I'm stuck on the same problem, Nearly figured it out,
what you need to do, is send back the Grails webflow "_flowExecutionKey" that keeps
track of the current state,
I'm sure you've seen this, as its the only decent result Google finds.
I send an ajax request to an action, which populates a template and sends it back
with an input tag,
<input id="flowExecutionKey" name="_flowExecutionKey" value="${request.flowExecutionKey}" size="100"/>
But you could try send a temple back marked up like JSON with the "_flowExecutionKey" along with the data you want to send back,
That's my two cents
As well as keeping track of the execution (as Daxon posted), you'll need to make sure your buttons are named _eventId_next and _eventId_skip. g:submitbutton is normally clever enough to do this for you but it might not be inside of a remoteForm.
Also, my web flow code uses the parameter execution, not flowExecutionKey - which version of Grails are you using?
Here a solution that works in grails 2.5.3 at least for one single action. The id and name of the button are automatically modified to include "eventId" as prefix but this still did not work for me unless I added _event_id manually as input parameter. However, I'm not sure how this can work for multiple possible events.
<g:formRemote name="flow1Form" url="[controller:'user', action:'gettingStartedAjax']" update="wizardDiv">
<input type="hidden" id="execution" name="execution" value="${request.flowExecutionKey}"/>
<input type="hidden" id="_eventId" name="_eventId" value="next"/>
<fieldset class="form">
</fieldset>
<fieldset class="buttons">
<g:submitButton name="next" value="Next flow"/>
</fieldset>
</g:formRemote>

Resources