jQuery submit preventDefault - javascript

I load a page from example.com on port 80, then from the loaded page, submit a form to the same server on a different port (as defined in the form action attribute).
(html)
<form id="enabledForm" action="http://example.com:39991/updateEnabled" method="POST">
(javascript)
$('#enabledForm').submit()
This works fine and the data is delivered as expected to the form action url, but the browser is redirected to the address of the POST request instead of staying on the requesting page.
If I use
$('#enabledForm').submit(function (event) {
event.preventDefault();
});
or
$('#enabledForm').submit(function (event) {
return false;
});
then the server receives no data but the page is not redirected.
if I add an alert within the event handler then the alert is not shown.
$('#enabledForm').submit(function (event) {
alert('inside submit event handler');
return false;
});
Clearly I'm soing something wrong but after hours of headbanging and trying everything I can think of I'm stuck.
What to do?

You have two basic options here:
Have the server return a 204 No Content response and forget about using JS entirely
Prevent the submission of the form with JS and send the data to the URL with Ajax instead
No content:
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent.
How you set the HTTP response status code depends on your server side language / framework. For example:
In Catalyst it would be something like:
$c->response->status(204);
In PHP it would be:
http_response_code(204);
There are many Ajax tutorials out there, so I'm not going to provide another one. The jQuery documentation has a detailed section on Ajax.
Note that since you are working across origins (different ports), you will need to circumvent the Same Origin Policy. The standard way to do that is with CORS.

Sending a form would automatically change your browser URL (and refresh view).You should use an Ajax request to send informations to your server and eventually retrieve completion (success, error, informations...).
Extract your inputs' values to an object via Jquery and send your request via Jquery.post or Jquery.get
$('#enabledForm').submit(function (event) {
//Prevent natual post
event.preventDefault();
//Retrieve inputs values
var data = {}
$('#enabledForm input,textarea').each(function(index){
data[$(this).attr('name')] = $(this).val();
});
//Send request
$.post('http://example.com:3999/updateEnabled',data,function(response){
//Parse response if you want to inform user about success of operation
});
});
I don't know if val() is usable with all of yout inputs, but it's easy to adapt...

Related

Setting the request URL of a Suitelet form

I have a form with text fields that I want to send to another server. The problem I am having is that I don't know how I set the request URL. I want to send the contents of the form to another URL and then process the response into Netsuite records. Below is the format of how the code will look. Any ideas on how I'm supposed to set that URL? Should I be using nlapiRequestURL()?
function mainFunction(request, response){
if (request.getMethod() == 'POST'){
var form = nlapiCreateForm('Form');
form.addField('field_one', 'text', 'value 1');
...
...
form.addSubmitButton('Submit');
// on submit send to specified URL
// response processed
}
}
By using form.addSubmitButton, whenever that is clicked, NetSuite will POST the request back to the same Suitelet that drew the form. This POST request should contain all of the field values from your Suitelet form.
Since you are already rendering your form when the Suitelet receives a POST request, you'll have to decide how to differentiate between the initial POST to render the form, and the POST from the submit button.
If you are sending a request to a different URL (e.g. another Suitelet, or a web service somewhere), then you are correct that you would use nlapiRequestURL.
If you use addSubmitButton, the Suitelet will use the same URL passing the field values to the same url. If you want to send the data to a different URL you can use addButton and put a custom function that will send the data to that URL.

Is it possible to detect form submit fail in javascript?

I have this simple form:
<form action="www.faildomain.com">
<input name="foo" value="bar">
<button type="submit">Submit</button>
</form>
In my case, the action will fail. But could it be that this is a valid action, but the user has experienced a connection error?
Are there different Javascript events generated or os this out of my control?
This is out of your control if you don't handle the submit event.
Basically, when you click on the submit button, your browser will do an HTTP POST request to your "action" URL.
If you want to check your inputs validity before sending it, what you'll have to do is to handle the form submission event: submit.
const myForm = document.getElementById('my-form');
// Add a listener to the submit event
myForm.addEventListener('submit', function (e) {
const errors = [];
// Check inputs...
if(errors.length) {
e.preventDefault(); // The browser will not make the HTTP POST request
return;
}
});
But, even with this code, you'll never know if the user has a network problem.
The only way you can check that kind of errors is by doing an asynchronous call to your backend route using Ajax (it's just an HTTP POST request, called asynchronously). For example, using jQuery:
$("#myForm").on("submit", function(e) {
event.preventDefault();
const data = {};
// Get data from form...
// Stop form from submitting normally
$.post("www.faildomain.com", data)
.done(function(data) {
// No problem
},
.fail(function (jqXHR, textStatus) {
// An error occured (the server responded with an error status, network issue, ...)
// More information about the error can be found in jqXHR and textStatus
 },
.always(function () {
// This method is always executed whether there were an error or not
});
If you Submit it using Ajax you can get it via response headers. Take a look at this plugin:
http://malsup.com/jquery/form/#ajaxForm
it will help you a lot because it already have a method error for that.

JSF 1.2 AJAX Redirect to URL

I've got a requirement where we need to redirect to a page for JSF 1.2 Ajax call. In our case, we need to redirect to session expired page when the ajax call get fired after the session got expired. We are implementing the session expiry check in a filter and the invocation of httpservletresponse.sendRedirect is redirecting correctly to the session expired page as expected, but the url is not getting changed which is the issue now.
Any hints/soultion either at the client/server side is highly appreciated.
~Ragesh
Finally I managed to find a solution for the above problem.
In the filter, I set the response header "Location" and another custom header which I'll use in the client side to filter the response.
Filter code:
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setHeader("x-timeout-status", "true");
httpServletResponse.setHeader("Location", httpServletResponse
.encodeRedirectURL(sessionexpiryurl));
Richfaces have got a javascript file with various callbacks required during the AJAX call invocation which is packed inside the Richfaces libraries. There is one callback function called "processResponse" which will get invoked upon receiving response for all AJAX call initiated by JSF Ajax components . I've made use of this to handle the redirection functionality.
JS code:
var originalAjaxProcessResponse = A4J.AJAX.processResponse;
A4J.AJAX.processResponse = function(req) {
if (req.getResponseHeader('x-timeout-Status') != undefined && req.getResponseHeader('x-timeout-status') == 'true') {
window.location.href = req.getResponseHeader('Location');
} else {
originalAjaxProcessResponse(req);
}
}
Here we are overriding the method to handle our specific case and delegate the rest of the ajax call response handling to the in-built processing provided by richfaces.
Please let me know if you see any limitation to this solution or have a better solution to this problem
~Ragesh

nodejs cannot get the response data from server

I am new to nodejs and jquery, I just want to get some data from a server and use that data to update a page:
Client side (uses jquery): as you can see, I want the text inside '#info' change to data got from server.
$('#button').click(function(){
$.post("/search", function(data) {
$('#info').text(data);
});
});
Server side (uses express):
app.post('/search', function(req, res){
res.send('hello');
})
The problem is: instead of updating the content of '#info', the content of the whole webpage will be gone and only 'hello' is printed on the webpage.
The client side seems unable to get the data from the server side, but I cannot figure it out why.
As mentioned in my comments, instead of handling button click event, you could handle form submit event and stop the form from submitting.
$('form').submit(function(){
$.post("/search", function(data) {
$('#info').text(data);
});
// This will prevent further processing...
return false;
});

I need to know about the response type of $.ajax() method in jquery

I am working on an e-commerce site and I need google sign-on it, so when a user creates his/her shopping list and click on the add to list button. I am able to send my data through the $.ajax() method, so what I exactly want is when the response from ajax method come it should redirect me to Login page if the user is not logged in, else it should save my object.
In the target endpoint of that .ajax() call, check your authentication, and if the user is not logged in, set the response header to - 401 Unauthorized.
Then in the .ajax() do this:
$.ajax(function() {
//.. your other ajax stuff..//
error: function(jqXHR, textStatus, errorThrown) {
// only redirect if user unauthorized - 'errorThrown' has text part of HTTP status header
if(errorThrown == "Unauthorized") {
window.location.href = "myloginpage.html";
}
}
});
The response header being set to 401 will trigger .ajax()'s error function, instead of the success function.
Edit:
Changed the error function to only redirect on Unauthorized
Also note, that if this is a cross-domain jsonp call, it won't work, as jsonp requests fail silently and don't trigger the error function
check in your response callback function and write your programming logic that you want
$.ajax({
'url':location,
'type':type,
'success':function(response){
/*write here your logic*/
},
'error':function(){
/*you code for error handling*/
}
});
to redirect window by javascript use
window.location.href = 'your location';
You can redirect to login page using window.location = 'yourlocation' in either success or error function of the response (depending upon what response you are gettig from server. If you are bringing the response code in header 401 error function will be executed other wise success).
but i think what you would like to have is take user back to the same page after login from which he started.
If you are interrested in this, you can use spring security for this. Its very easy to integrate if you are using spring already.
If you are not using spring you might look for some alternative for the same. Following links may help you
Spring Security Ajax login
http://java.dzone.com/articles/implementing-ajax
In jquery there is .post() method found to do this. In action page you can do whatever you want.

Categories