POST works with alert message but doesn't without it - javascript

I am making a post request to google app script with the code below
var url ="MY WEBAPP EXEC"
function submitForm() {
var postRequest = {}
postRequest.name = $("#inputName").val();
postRequest.email = $("#inputEmail1").val();
postRequest.message = $("#inputMessage").val();
alert(JSON.stringify(postRequest)); // this alert
$.post(url, postRequest, function(data,status){
alert('success')
});
}
I am very confused why the post is working with the alert but doesn't work without it. Thank you.
===
OK I guess my question was not clear enough sorry.
I have a form accessing GAS remotely. I assumed the url implied that I was accessing GAS remotely. At the moment I am working on my localhost and on my JS above it works if the alert statement is present and does not do anything if alert is not there.
I was watching the execution list on GSuite Developer Hub to see if the request failed or completed. I observed if the alert statement is in the script the execution status is completed but if the alert statement is not there nothing happens. I assume that my post script is not working if alert is not there. Any idea why?

You haven't shown exactly how that function is called, but it's likely to be because, if this is truly a "form submit" action, the result of submitting a form is to "load a new page" (which can be the same page you're on, and is so by default with no action attribute in the form tag
Since you want to perform AJAX on form submit, you need to "prevent" the "default" form submit action - this can be achieved as shown in the second and third lines below
var url ="MY WEBAPP EXEC"
function submitForm(e) { // if this function is called using an event handler, it gets an event as the first and only argument
e.preventDefault(); // prevent the "default" form submit action
var postRequest = {}
postRequest.name = $("#inputName").val();
postRequest.email = $("#inputEmail1").val();
postRequest.message = $("#inputMessage").val();
alert(JSON.stringify(postRequest)); // this alert
$.post(url, postRequest, function(data,status){
alert('success')
});
}

Related

Google Recaptcha V3 double submit issue (timeout-or-duplicate error)

I have an issue somewhat similar to this scenario :
I got "timeout-or-duplicate" error using ReCaptcha v3
In may scenario i have a form and a button that perfrom submit of the form. Inside the form a setInterval keep the recaptcha fresh :
<script src="https://www.google.com/recaptcha/api.js?render=<%=ServiceLocator.AppConfigProvider.Instance.RecaptchaPublicKey%>"></script>
<script>
onSetupDone(function () {
getReCaptcha();
setInterval(function () { getReCaptcha(); }, 90000);
function getReCaptcha() {
grecaptcha.ready(function () {
grecaptcha.execute('<%=ServiceLocator.AppConfigProvider.Instance.RecaptchaPublicKey%>', { action: globals.currentPage }).then(function (token) {
document.getElementById("reCAPTCHAResponse").value = token;
});
});
};
/**
* Get a previously stored RecaptchaToken
* */
window.getReCaptchaValue = function () {
var result = document.getElementById("reCAPTCHAResponse").value;
getReCaptcha();//refresh the value
return result;
};
});
</script>
the OnSetupDone() is a function equivalent to document ready (it's called once per page, when document is ready and all setup phase is done).
My problem is that when user click twice the button that cause form submit, multiple form are submitted (and then cancelled when a next click occured)
But if the cancellation occurred only after the server use of recaptcha token, i end up using a token twice. And so request is declined (timeout-or-duplicate error).
What is not clear to me is which is the whay to handle situation like that (avoid use a recaptcha token twice in a from submit).
Should i add an handler in the form submit event and take another captcha? (this does not guarantee me that the next submit will be processed after the form sumbit event enqueued by javascript.. so i guess answer is still no)
PS : as shown in the picture, the page (an asp.net page) does not reload while the submit is processed. This also contribute to the fact that the old token is retained by the alredy submitted form.

document.getElementById(..) gives null even though element is present

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?
I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.
I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

Page redirect in jQuery fails randomly. Race condition?

Elaborating on an example from the very good post by Felix Kling I wrote some jQuery code to authenticate a user. If the authentication is successful the window.location object should be assigned/replaced to a new URL.
The redirection occasionally fails, even though the user is authenticated correctly: based on the values of sessionStorage('Auth') the looks of the menus for an authenticated user are modified by some other JS code, so I know when the credentials were entered correctly.
Here is my code.
$(document).ready(function() {
$('#submit').click(function() {
var webServiceHref = window.location.href;
var webServicePath = webServiceHref.slice(0,webServiceHref.lastIndexOf("/"));
var serviceUrl = webServicePath + "/login.php";
$.post(serviceUrl,
{
Email: $("#Email").val(),
Password: $("#Password").val()
}).done(function(data, status) {
var json = JSON.parse(data);
if (json.valid == true){
sessionStorage.setItem('Auth', true);
sessionStorage.setItem('FirstName', json.FirstName);
sessionStorage.setItem('Email', json.Email);
$("#messageLine").val("Authentication succeded");
$(location).attr('href', webServicePath + "/welcome.html");
// window.location.href = webServicePath + "/welcome.html";
} else {
sessionStorage.clear();
$("#messageLine").val("Incorrect Username or Password");
}
});
}); // click
}); // ready
This behavior does not depend from the way the redirection is called:
I left in my code, commented out, some of the JS and jQuery
combinations of methods (window.location.assign, window.location.replace etc.) suggested in numerous posts on SO.
I have even tried .reload() without success.
In Chrome inspector I can even see the callback statements being executed, the assignment of the new URL being made, but when the function returns the window object sometimes does not change, and sometimes ... it does.
Perhaps the assignment of the URL is queued after other event which causes the original login.html page to be reloaded?
What am I missing? Am I using the deferred object incorrectly?
Thank you in advance for your help.
If your "#submit" element is actually submitting a form (e.g. it is an input of type "submit" within a form), that could cancel the page redirection. E.g. when no action is specified on the form, it just reloads the same page, preventing your modification of window.location.href from having any effect.
See also that post: javascript redirect not working anyway
You have 3 easy possible solutions:
Turn your element/button into a normal one (not a submit).
Prevent the element/button from submitting the form (function (event) { event.preventDefault(); /* rest of your code */}).
Attach your main callback on the form submit event. The user is then able to trigger the action by hitting "Enter", not just by clicking on the submit button.

Checking for duplicate username

I am doing a registration page, for my mobile app, and want to check for duplicate usernames entered by the user/client
I have a button on the page that when clicked, checks availability of the username. However I would like to also incorporate that automatically, if not already done so, when the client clicks submit/go to step 3,
I want to perform the check for duplicate usernames using Ajax and if there exists a duplicate, then refresh the SAME page with the error message for duplication, else proceed to step 3.
In my HTML file I have some js that does the following:
$("#check-username").click(function() {
(...this works as I am able to click the CHECK button
and see if the username exists)
I have another js file, that is sourced in my HTML that does the following:
submitHandler : function() {
$("#reg1").hide();
$("span#step").html("2");
$("#check-username").click;
$("#reg3").show();
scrollTop();
}
When I click on Go to next step which is reg3, It does not do the validation for check-username. Is my method/syntax for calling check-username correct?
$("#check-username").click;
^^----- Missing Braces
supposed to be
$("#check-username").click();
The problem is you need to go to step 3 only after the validation ajax request returns from the server. You also are going to need to look at the response from the server to see if it's a duplicate. For example:
$("#check-username").click(function() {
validateUser();
});
function validateUser(){
return $.ajax({
url: '/path/to/validate'
});
}
And your submit handler stuff:
submitHandler : function() {
$("#reg1").hide();
$("span#step").html("2");
validateUser()
.done(function(r){
//for example...
if(r.isValidUser){
$("#reg3").show();
scrollTop();
}
});
}

What is the Difference between submit() function and send() JavaScript functions?

I have been studying JavaScript from one book. Once I was playing with the codes concerning the client-server site communication, I wanted to do a POST request with the code below (which uses IE ActiveX object XMLHttpRequest):
<script type="text/javascript">
var oRequest = HTTPRequestUtil.getXmlHttp();
var sRequestType = "post";
var sURLofRequest = "MyPage.aspx";
var bAsnychronously = false;
oRequest.open(sRequestType, sURLofRequest, bAsnychronously);
oRequest.send(null);
alert ('Status is '+oRequest.status+' ('+oRequest.statusText+')');
alert ('Response text is '+oRequest.responseText);
</script>
I have breakpoint on the PAGE_load eventhandler of the MyPage.aspx" page. I was expecting the execution will stop at that place when this HttpRequest occurs above. (It is called on a html button click).
The thing is, the request is done, the responseText is obtained (which was the xml content of the page) and no stop at the Page_Load method where I have put a breakpoint.
So, now I cannot understand the difference between calling .send() function with POST request type and submit() function on the call.
I would appreciate if you can explain the main differences briefly.
thanks!
The difference is that using send will send the data back to the JavaScript calling routine without reloading the page, but calling submit on a form submits the form to the server and then reloads the results from the server as if the user had clicked on the submit button of the form.
The "send" is what is known as Ajax, and it is, for example, how the Stackoverflow voting buttons work to send the votes back to the server without reloading the entire page.

Categories