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.
Related
I realise I can solve the following problem by using AJAX. However, I didn't realise that a progress wheel would need to implemented so therefore I currently get results via an ActionResult method
#Html.Action("devExpressGridView")
And at the server...
return PartialView("devExpressGridView", Object);
So the problem is I need to call some javascript once the partial view has been returned
I know I can call some javascript on a button press or whatever to start to show the progress bar so this isn't no problem,
but once the results has been returned from the action method, I need to hide the progress wheel so the user knows the data retrieval has been done.
I basically need to fire ssomething like
// Once the action method has been completed, fire this...
function hideProgress() {
spinner.fadeOut("fast");
spinnerVisible = false;
};
is there a way to do this without AJAX?
Thanks
You can add a $(document).ready in the partial view.
<script type="text/javascript">
$(document).ready(function () {
//do something here
});
</script>
I have a problem with a AJAX call. I am trying to access the inputs of a HTML
form element and write this to a database with a PHP script.
My JS code looks like this....
function getWriteValues() {
var x = document.getElementById("eingabemaske");
var jqxhr = $.post( "source/form_handler.php",
$( "#eingabemaske" ).serialize() );
alert( 'Eintragung erfolgreich durchlaufen' );
}
The PHP part isn't interesting because there nothing except the database insert happens.
Now to my Problem. The Function makes what it should do. But when I delete the alert() statement, nothing works any more. That means that nothing is written to the database and the ajax call could not be made. I can't figure out where the problem is.
I use jQuery in Version 2.1.1.
When you click the submit button you:
Run the JS
Send the Ajax HTTP request
Submit the form
Leave the current page
Cancel the Ajax HTTP request because there isn't going to be anything left to handle it.
Either:
Prevent the default action of the submit button so you don't leave the page or
Get rid of the JS and do your database insertion in the program you specify in the action of the form
Do you call getWriteValues(), if the the form is submitted?
If so, don't forget to return false;
Check in your html "name" attribute is defined for each form elements or not as serialize() takes element name and its value.
Check whether you're getting the values in getWriteValues()
Verify these values are passed to form_handler.php script.
sample:
<form id="eingabemaske">
<input id="abc" name="abc" value="test" />
<input type="button" id="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function(){
$('#submit').on('click',function(e){
e.preventDefault();
getWriteValues();
});
});
function getWriteValues() {
console.log($( "#eingabemaske" ).serialize());
var jqxhr = $.post( "form_handler.php",
$( "#eingabemaske" ).serialize() );
//alert( 'Eintragung erfolgreich durchlaufen' );
}
</script>
in php script
print_r($_REQUEST);
It may be due to that alert message is giving time to ajax to perform its work. please check all the process that happens before and after the ajax. Also, as you are calling ajax from submit button (i suppose that that u have called this function from "onsubmit" attribute of the form), may be its submtting the form before ajax is completed. Please return false at the end of function in order to stop function processing further.
I'm have a simple form, when clicking the submit button the backend php file gets executed by my JavaScript file, results are returned via ajax, everything works great when manually clicking the button. However, when trying to use javascript to automatically submit the form every 120 seconds it is not working. The javascript never get's called which in turn causes the php to not execute...
html
<form id="send-with-ajax" name="ping">
<input type="submit" value="Execute Ping" />
<div class="ajax-response"></div>
</form>
<script type="text/javascript">
// refresh ping results every 120 seconds
var pingRefreshInterval = setInterval(function () {
console.log(
'submitting ping.php request after 120 second wait - time now:'+new Date());
document.getElementById("send-with-ajax").submit();
},120000);
</script>
<script src="js/portal.js"></script>
Again, there are not issues with my portal.js file or my php file -- The main thing to note here is that the document.getElementById("send-with-ajax").submit(); does not do anything... Any ideas?
Assuming that js\portal.js just executes a function when a POST event occurs, you could simply call that function from inside your interval.
If that won't work for some reason (maybe there's a lot of other stuff happening on your page that you didn't show us), and your call to submit() isn't working properly, you could also trigger a button click with $('input[type=submit]').click(); (assuming you only have one submit button on the page - otherwise add a class or an id and trigger on that instead).
Try using the submit() method. Or use AJAX.
If you are doing things on onsubmit event, document.getElementById("send-with-ajax").submit() doesn't trigger this event.
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;
}
I am trying to do a simple query for info from a database through an html page. I've got all the backend stuff working fine, but I'm having trouble on the client side. I currently have a form where the user submits their ID# to get some info on their case.
But with my current setup, it returns an entirely new page and I just want to read in a text string, process it and update the content on the current html page without opening up a new one and replacing the old one. How can this be done?
Here's my code so far:
function showInfo() { } // I want to make the request here instead
<form name="register" action="http://localhost:8080/testapp/authenticate" method="get">
<p><label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
<button id="checkButton" type="submit" onClick="showInfo()">Enter</button>
</p>
</form>
My guess is that you're actually submitting the form, which is posting back to the server. What you will want to do is cancel the form from submitting and submit it using AJAX (which is what I believe you want?).
To do so, your showInfo() function should do one of these three things (I can never remember which one)
return false;
cancel the event, something like e.preventDefault()
stop the propagation, something like e.stopPropagation()
Once you've successfully prevented the form from hard-submitting, you can then do what you'd like by submitting your data via AJAX and manipulating your response however you'd like.
1st - Jason is absolutely right that what you want for this situation is AJAX, below is an example in motion.
2nd - You should be using a Javascript library such as jQuery, which might look intimidating (as it did for me at first), but it is really easy and completely worth the small effort to get it going.
3rd - With jQuery, your application tidbits should look something like this, using the example you provided:
HTML -
<p>
<label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
// Please note that I removed the onClick section from the line below.
<button id="checkButton" type="button">Enter</button>
</p>
JQUERY -
// The default function you described to take information and display it.
function showInfo(data) {
// Insert your function here, probably using JSON as the Content Type
}
// This is the key AJAX function, using jQuery, that takes your info and gets a
// response from the server side, the sends it to the function above in order for it
// to be displayed on the page.
function processIdInfoCheck() {
$.ajax({
type: 'post',
url: '/http://localhost:8080/testapp/authenticate',
data: {
'id': $('#badge').val();
},
dataType: 'json',
success: displayIdInfoReturn,
error: function () {
alert("There was an error processing your request, please try again");
}
});
}
// When the page loads, the code below will trigger, and bind your button click
// with the action you want, namely triggering the AJAX function above
(function ($) {
$('#checkButton').bind('click', processIdInfoCheck);
})(jQuery);
Just remember, AJAX takes some effort to get the desired effect, but when you look at page load times, request numbers, etc... It is totally worth it. Please let me know if this was helpful and if you need any specifics.