How to trigger browser password save - javascript

I have an application running with Backbone.js, and I need to trigger the browser password save when logging in.
Currently I am using preventDefault when the form is submitted, and thus the password save is not triggered. When searching for this I find old posts about using iFrames and stuff, which seems obsolete, so my question is:
How do you trigger the password save prompt, when handling form submit in JS?

I don't think you can force the Browser to do that; What I'm sure you can do is, after the ajax (or anything) post request, do a form submit something like that
in jquery :
$.ajax({
url:requestUrl,
success: function (data, text) {
//Request Finished with Success
$('#Form').submit();
},
error: function (request, status, error) {
//Request Finished with Error
}
});
in VanillaJS :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === 4) {
//Request Finished
if(request.status === 200) {
//Success
document.getElementById('Form').submit();
} else {
//Error
}
}
}
request.open('POST', URL);
request.send();
This way you let the Browser and the User keep control over what happens.
If you still want to save the password then use cookies, Here is something you might use

Related

Form that already being validated by JS. Need to have it also clear fields on submit

I have a web form that is part of a CMS, therefore I am not able to alter the input field of the submit button. The form is already being validated by JS, so I need to add a line to the existing code below that will clear the fields.
Currently, the page redirects to a Thank you page on submit. I want it to continue doing that. But, currently, if the user hits the back button on their browser, the data is still there. I need it to submit the data, clear the fields, then redirect to the thank you page.
$('form').submit(function(event)
{
if (validateForm())
return true;
event.preventDefault();
});
Have you tried adding document.querySelector('form').reset() above the return statement? In jquery that might just be $(this).reset(), I'm not sure.
if (data.status) {
$(this).find('input').val('');
// code to redirect to success page here
}
If form is successfully sent, then set the value of all inputs in the sent form to a string with the length of 0.
$('form').submit(function(event) {
event.preventDefault();
if (!validateForm()) {
return false;
} else {
formSubmit($(this));
}
}
);
function formSubmit(form) {
var url = form.attr('action');
var method = form.attr('method');
var data = form.serialize();
$.ajax({
method: method
, url: url
, data: data
})
.done(function (data) {
try {
$(this).find('input').val('');
// code to redirect to success page here
} catch (e) {
console.log(e);
}
});
}
FE validation is bad practice in my honest opinion, just good for lowering the amount of HTTP requests to the server. The hard form data validation should happen on the BE.

Is it possible to get the response code of the js imports in html programmatically?

In HTML, is it possible to see the response code of the script you imported?
I specifically need to get the response code of each script import. This has something to do with problem I'm dealing in this post.
I was wondering if I couldn't intercept using angularjs maybe I can do it by using pure javascript.
Ajax would be the way to go. To cleanly replace a browser's request for at script file with a manual one in JS, you would need to do the following.
var xhr = new XMLHttpRequest();
xhr.onload = function(event) {
// Check the http status code and inject script on page if 200
if (event.target.status === 200) {
var script = document.createElement('script');
script.innerText = event.target.response;
document.body.appendChild(script);
}
else {
// Handle other status codes..
}
};
xhr.open('get', 'script.js', true);
xhr.send();
You cannot intercept the response for resource requests made by the browser. The workaround would be to dynamically load the js files via ajax and check the result code there. E.g. (i'm using jquery syntax as its easier to write):
$.ajax({
url: "/js/my_js_file.js",
type: "GET",
success: function(data) {
eval(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// handle the response code
}
});
This would be however cumbersome if you have may js files on your pages.
If your challenge is to detect whenever the user is authenticate or not, the solution can be simpler: you can make an ajax call at the beginning of the page to a /check_auth endpoint and if the endpoint returns 401, redirect the user to the login page.

Check Availability of a page before loading it, using jquery/ajax

Is it possible to check the Availability of a page before loading it?
I have a form, running on mobile device using wireless connection. The problem is: not always this connection is available and I would like to alert the user when is doing a submit or an unload of the page.
The problem is that the page contains elements doing redirect like this:
<input type="button" value="MyText" onClick="script1;script2;...window.location='mylocation'" />
If the user click on this button and the server is not achievable, i will receive some undesirable errors.
Also if I want to generalize my script i do not know the value of "mylocation" previously.
The page contains elements to submit the Form also:
<input type="submit" name="SUBMIT" value="MyValue" onClick="return eval('validationForm()')" />
For the submitting I'm using the ajaxForm plugin and it works quite well.
to navigate back easily use this instead:
<input type="button" value="Back" onClick="window.location='history.go(-1);" >
where -1 means previous page. If you want to reload the current page use 0 instead, to navigate forward, use 1, etc.
If you use ajax from jquery, it sould handle it by itself... http://api.jquery.com/jQuery.ajax/
$.ajax({
///... need argument here...
timeout: 5000, // in milliseconds
success: function(data) {
//Do something success
},
error: function(request, status, err) {
if(status == "timeout") {
alert("can't reach the server");
}
}
});
EDIT AFTER COMMENTS:
You can check How do I check if file exists in jQuery or JavaScript?
in your case this sould work as expected:
//Initialize the var as global so you can use it in the function below
var goto_url = "http://www.mywebsites.com/foo.html";
$.ajax({
url:goto_url;
type:'HEAD',
error: function()
{
//do something if the gile is not found
},
success: function()
{
document.location = goto_url; //docuemnt.location will redirect the user to the specified value.
}
});
this will actually check if the file exist.. If it can't connect to the file it will not be able to find it..
If he can find the file, he obviouly was able to connect, so either case you win.
cheers!
Thanks to your answer I found the solution to the problem.
This check if the server is achievable before launching a script and redirect.
That's the code:
function checkConnection(u,s){
$.ajax({
url:u,
cache:false,
timeout:3000,
error: function(jqXHR, textStatus)
{
alert("Request failed: " + textStatus );
},
success: function()
{
eval(s);
}
});
}
$(document).ready(function() {
// part of the function that checks buttons with redirect
// for any button that contain a redirect on onClick attribute ("window.locarion=")
$("input[type=button]").each(function(){
var script = $(this).attr("onClick");
var url = "my_url";
var position = script.indexOf("window.location") ;
if (position >= 0) { // case of redirect
url = "\'"+url+"\'"; // that's my url
script = "\""+script+"\""; // that's the complete script
$(this).attr("onClick","checkConnection("+url+","+script+")");
}
});
// part of the function that checks the submit buttons (using ajaxForm plugin)
var options = {
error: function() {
alert("Message Error");
},
target: window.document,
replaceTarget: false,
timeout: 3000
};
$("form").ajaxForm(options);
});
I hope that this will be usefull.
You should use the callback of the jQuery Ajax function to catch the problem of a server not available.
You cant check the servers' availibility without making a request to it.
You're trying to see if there is a connection. AFAIK the only way for actually checking if a server is reachable is making a request to that server.
Set a timeout of a reasonably small amount of time (let's say 3s) and make a request. If you get a timeout error, then there is no connection, else you're good to send the form.

Checking form submit using conditional?

Is there a way to check if a form is submitted using an if statement?
I am trying to write a function that no matter what the user does, information is always recieved and displayed to them. But if they user submits a form, it sends that data to the database and updates it first.
I've been trying to find events or methods to help me with this, but couldn't seem to find anything helpful.
function getData(){
if ( FORM SUBMITTED ) {
//POST and send
request.open("POST", url, true);
request.onreadystatechange = useResponse;
request.send(str);
}
//GET and display
request.open("GET", url, true);
request.onreadystatechange = useResponse;
request.send(null);
}
EDIT: I am not refreshing the page. I forgot to mention that I am doing this using AJAX. When the page loads, this function runs initially (which displays the form data). But I do not want the form to send any data since I'm just loading the page and not actually submitting anything.
After the page is loaded and I click submit, this function is called. What I need is AJAX to send the form data via POST, then redisplay it (the script above outlines the function).
The form when submitted just calls the function:
action="javascript:getData()"
I don't quite understand what you're asking because if a form is submitted then the browser is loading a new HTTP response which may or may not know anything about an HTML form which led to its generation.
[Edit]
It looks like the "getData" function is doing too many things, I would create separate functions to handle the "get" and "post" requests, for example:
<body>
<form name="form" action="#">...</form>
<script type="text/javascript">
var getData = function() {
// XHR GET data and update DOM...
};
getData();
var sendData = function() {
// XHR POST form encoded data from form input elements...
};
document.form.onsubmit = function() {
sendData();
getData();
return false; // Block the actual form submit event.
};
</script>
</body>
The jQuery serialize() function demonstrates what is needed to encode the form data programmatically.
Hmm, I hope I'm understanding you correctly. You basically want to (conditionally) POST to one URL and GET from another one (or the same one) in serial?
If that's the case, your code would look something like...
var get = function(callback) {
var req = new XMLHttpRequest();
req.open = req.open('GET', url);
req.onreadystatechange = function() {
if (...) {
callback(req.responseText);
}
};
req.send();
};
var exec = function(callback) {
if (FORM_SUBMITTED) {
var req = new XMLHttpRequest();
req.open('POST', url);
req.onreadystatechange = function() {
if (...) {
get(callback);
}
};
req.send();
} else {
get(callback);
}
};
exec(function(data) {
console.log('request(s) complete, here's the response: '+data);
});
Since XHR is only really worth-while when using it asynchronously, you have to nest some callbacks to make sure everything happens in serial, otherwise, the GET may complete before the POST.

How do I use JS to execute a heavy PHP function after the page loads in order to speed things up?

I've got a web page that displays some content. The query itself is pretty slow (4000 ms).
I don't want my users to have to wait for the query to run before the rest of the page loads though.
Is there a way I can stick some code before and after the tag in my HTML template that will "delay" that function from executing until after everything else has rendered?
e.g.:
<javascript code that tells the page not to render what comes next until very last>
<?php my_heavy_php_function(); ?>
</javascript>
As I can understand from your question, you should go for AJAX: you first load the page without the heavy content, and when the page is ready you do an AJAX call to a webservice to fetch and display the data, while showing a "Processing, please wait" message to the user.
symbolic write:
document.onload = ajax call
Using Ajax
Using the jQuery Ajax request method you can post the email data to a script (submit.php). The $(function(){ }); executes when the dom is ready. Also, you might need to use the 'timeout' option if you are going to be executing an long query.
note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.
$(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
timeout: 10000,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
//response being what your php script echos.
}
});
});
Although, jQuery is by no means required do do an ajax request, I would highly recommend using some kind of framework to help ensure x-browse support.
If you are using a large dataset I would highly recommend using json to encode your repsonses. It makes parsing quite easy. Here's an example with jQuery $.getJSON() API and likewise how you can encode it with PHP
Either optimizing the query or doing an AJAX call. Here is a plain JS way of doing AJAX, I found this script in a Google search and modified to use a callback function so you can parse the data or do other things other than just load the content straight to a HTML element:
the ajax function: The Original function I found unmodified
function ajaxRequest(Url, callback) {
var AJAX;
try {
AJAX = new XMLHttpRequest();
}
catch (e) {
try {
AJAX = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX.");
return false;
}
}
}
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4) {
if (AJAX.status == 200) {
callback(AJAX.responseText);
}
else {
alert("Error: " + AJAX.statusText + " " + AJAX.status);
}
}
}
AJAX.open("get", Url, true);
AJAX.send(null);
}
Usage of it:
<div> some normal content </div>
<div id="loadlater">loading data...</div>
<div> more content that loads before the data</div>
<script>
ajaxRequest('/echo/html/', function( response) {
document.getElementById('loadlater').innerHTML = response;;
});
</script>
Working example here: JSFiddle

Categories