Button onclick Javascript function fails, but function works - javascript

In my html document I have this:
<button onclick="doFunction()" type="submit" ...>Button</button>
The function looks like this:
doFunction() {
var goToThisUrl = "www.spring_controller_method.com?redirectUrl=this_page";
window.location.href = goToThisUrl;
}
The the url in the doFunction() is the url of a Java Spring controller method. In that method it manipulates the database and returns a string to redirect to the page it came from: return "redirect:" + redirectUrl.
The problem is that the button doesn't work. When I click the button, the page refreshes but the data in the database isn't manipulated. The reason I know this isn't a problem with the spring controller method is because of two reasons:
I have a breakpoint in the controller method and it isn't being hit.
When I take the same doFunction() code and run it on the Chrome developer console, the controller method breakpoint is hit, and the data in the database is changed.
Is there any idea as to why this would be happening?

Remove type submit from button like
<button onclick="doFunction()" type="button" ...>Button</button>
type="submit" is used for form submission that's why onclick not working.

Add return false; to prevent the default form submission.
doFunction() {
var goToThisUrl = "www.spring_controller_method.com?redirectUrl=this_page";
window.location.href = goToThisUrl;
return false;
}

Related

How to add text input variable to URL in javascript

I'm having the weirdest problem right now. I have this JS code:
function CreateChat() {
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
Thing is, as it is, I can't make it work. It obviously should be calling a controller method, but it just won't work. If I hit that url with the project running and put anything at the end of it, like https://localhost:44321/CreateNewChat/CreateChat?ChatName=TestName, that test name variable will get to the controller without a problem. If I hardcode to the code the "TestName" instead of passing the chatName variable I define earlier, it will get to the controller, no problem. Hell, if I debug the script, the chatName variable gets loaded correctly with my input, and if I console.log the url it will show up correctly (in fact, I can copy/paste that url and it will hit the controller method correctly). But, as the code is presented above, it will never, by any means, hit the controller. It will reach that point, and cut the execution as if there was an error in the JS code. Do you guys have any ideas on this? It's driving me mad, really.
Just in case, this is how I define the text input in the HTML:
<input type="text" required class="form-control" id="chatName" aria-describedby="nameHelp" placeholder="Name your chat!">
Edit: encodeURIComponent on the chatName doesn't work either.
try using window.open with _self instead:
window.open ('https://localhost:44321/yadayada','_self',false);
You have a submit button (and I assume this button is inside a form)... when you click on the submit button the form is submitted to the submit action of the form, this is the default behavior for the submit action.
Now if you don't want your page to be submitted, you can change the button type to button:
<button type="button" onclick="CreateChat()" class="btn btn-primary">Create a New Chat!</button>
Alternatively if you actually need a submit button then you need to prevent the default behavior in order to change window.location:
function CreateChat(event) {
e.preventDefault(); // <-- don't submit the form
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
You need to pass the event to CreateChat function:
<button type="submit" onclick="CreateChat(event)" class="btn btn-primary">Create a New Chat!</button>

Javascript function excute automatically in web2py

I have a checkbox in the frontend, and would like to update database according to the status of checkbox, I also have save button to submit.
Now I got confused. Everytime I turned to changeActive/id page, without clicking the button, it updates database directly.
alert works fine.
this is the code in controller:
def changeActive():
post=db.student(request.args(0,cast=int))
def change(value):
changeStatus=db(db.student.id==post.id).update(is_active=value)
return changeStatus
return locals()
This is the code in changeActive.html
{{extend 'layout.html'}}
<h1>it is a test</h1>
<h2>{{=post.name}}</h2>
<h2>{{=post.id}}</h2>
<h2>{{=post.is_active}}</h2>
<input type=checkbox id=is_active>
<input id="save" type="button" value="save"/>
<script type="text/javascript">
window.onload=function()
{
var saveButton=document.getElementById('save');
saveButton.onclick=function()
{
var changeSt=document.getElementById('is_active');
if (changeSt.checked)
{
alert('active')
{{change('T')}}
}
else
{
alert ('not active')
{{change('F')}}
}
};
};
</script>
It appears you are expecting Python functions to be executed by the browser after the page has been loaded. This is not how web2py templates work. The templates include Python code, which is executed on the server before the page is sent to the browser. Therefore, the calls to the change() function are happening before the page ever reaches the browser.
What you probably want to do instead is trigger an Ajax call in the browser, which would call a separate function on the server to handle the update. You can handle that via jQuery (or other suitable Javascript options), or use web2py's built-in Javascript ajax() function, as described here.

Changing the form action, when a submit button is pressed using JavaScript

I have a submit button like as follows.
<input type="submit"
name="btnDelete"
id="btnDelete"
value="Delete"
onclick="this.form.action='${pageContext.request.contextPath}/Country/DeleteMany'"/>
I causes the form action to change, when it is pressed.
I however, need to invoke another function before this action is changed. This another function returns a boolean value based on a confirm dialog of JavaScript.
I have tried the following.
onclick="return confirmDeleteMuliple(); this.form.action='${pageContext.request.contextPath}/Country/DeleteMany'"
The action however, did not change on submit (when confirmDeleteMuliple() returns true).
I have tried placing the code that changes the action in a separate JavaScript function like as follows.
function deleteManyAction()
{
document.dataForm.action='${pageContext.request.contextPath}/Country/DeleteMany';
}
And the onclick attribute is changed as follows.
onclick="return confirmDeleteMuliple();deleteManyAction();"
The deleteManyAction() function however, never invoked. It works only when the function confirmDeleteMuliple() is removed from onclick.
How to invoke these two functions in the defined sequence?
The expression ${pageContext.request.contextPath} evaluates to a context path of the application on load time like /Example (when this file (JSP) is parsed).
Code placed after a return will never be reached. The return basically means stop working and give me what you have.
This should do what you want:
onclick="return submit();"
function submit(){
if(confirmDeleteMuliple()){
deleteManyAction();
return true;
}else{
return false; //Otherwise the form will be submitted anyway.
}
}
Try to keep code (JS) out of your presentation layer (HTML). I assign all of my event handlers in my JS files. Try this approach, which I think will make your code :
$("#btnDelete").click(function() {
if ( confirmDeleteMuliple() ) {
this.closest("form").attr("action",
${pageContext.request.contextPath} + '/Country/DeleteMany');
# Here, returning true will allow the form submission to complete with the new
return true;
} else {
# This will stop the form from being submitted
return false;
}
});

Not opening new page throught JavaScript

I have a script that gets throught parameter the new page andthe redirects to this page.
my function:
function openPage(page) {
alert("Pressed the button!"); //working
window.location.href = "http://localhost:8080/Edas/" + page; //not working
}
and my button:
<button id="btnViewMonthlyPurchaseReport" onclick="openPage('monthlyPurchaseReport.html')">View Monthly Purchase Report</button>
I think my problem is in my base URL ("localhost:8080/Edas/"), but really don't know how to fix it.
Thanks!!
Out of the comment the problem was that the button was inside of a form element.
The problem is that a button without a type attribute will submit the form, which would (not sure if in every browser) result into the described problem, that the window.location.href = ... has no effect and that the page would be redirected to the url defined in action. If action is not defined in the form then it is the the current url.
You have different options to solve this:
You could move the button out of the form (if it would not affect usability)
Change the type of the button to button (<button type="button">View Monthly Purchase</button>) - the default behavior without a type is submit
You could place a return false; at the end of your openPage function to prevent the default behavior (this is similar to 2. but with the difference that the button would still be marked as a submit button which could be important for usability in some situations).
Do this:
JS
var url = window.location.href;
var dirnames = url.split('/');
function openPage(page) {
alert("Pressed the button!"); //working
window.location.href = "http://"+ dirnames[2] +"/Edas/" + page;
}
I imagine you're correct in saying that your issue is in the URL.
Where is your monthlyPurchaseReport.html? If it is in the same directory as where the html with your button is, simple use:
function openPage(page) {
alert("Pressed the button!");
window.location.href = page;
}
My problem was: my button was wrongly inside a form, which #t.niese clearly explained why.
Thank you all for the help!

Difference between form.submit and window.open() in Javascript

I have a javascript function which redirects to another page with the parent page contents. My issue is when i used form.submit,I am getting redirected to error page. When I tried with window.open, it works. Please help me what is the exact difference between these two. And whether form.submit also works here? Please see the Javascript code below. When I uncomment the window.open and comment the frm.submit, it works.
function Check() {
var frm = document.forms[0];
var target = frm.target;
var action = frm.action;
var HPPSFeild='<%=HPPSURLFeild.ClientID%>';
var HPPSValue=document.getElementById (HPPSFeild).getAttribute('value');
frm.target = "_blank";
frm.action =HPPSValue;
alert (frm.action);
frm.submit();
frm.target = target;
frm.action = action;
//window.open(HPPSValue);
}
form.submit();
window.open('url');
is same when you using form submit method=GET
because window.open(); always makes GET request
but if you are using POST method to submit your form then it different from window.open() method.
Form.Submit will pass input type controls with value to the action URL defined in form and windows.open will open new window with given URL
if you want value to be passed to new page I will suggest you to use form.submit method
<form method='post' action='URL'>
<input type=""
....
....
....
</form>
In script when you write form.submit it will open URL and value of input type will be passed in query string
See this below code
<form action="file.php" method="post" target="foo" onSubmit="window.open('', 'foo',
'width=450,height=300,status=yes,resizable=yes,scrollbars=yes')">
That onSubmit is helps to call any server side event or javascript function (like Post to a method) , but the windos.open is helps to open next page (same as Response.Redirect in c#`,Like GET a Method )
You need to change
//,......code
frm.submit()
{
window.open(HPPSValue);
}:
//,......code

Categories

Resources