How do I call a javascript function immediately from the vb code - javascript

This is my sciprt, it display a message box with an 'Ok' and 'Cancel' Button
<script type="text/javascript"> function Confirm() {
var confirm_value = document.createElement('INPUT');
confirm_value.type = 'hidden';
confirm_value.name = 'confirm_value';
if (confirm('Continue?')) {
confirm_value.value = 'Yes';
} else {
confirm_value.value = 'No';}
document.forms[0].appendChild(confirm_value);} </script>
On my program i'm running a query, if there are no results then i display this "Dialog" box
I want to call the function immediately after getting the query results but my current code seems to be running it after everything instead of immediately.
If reader.read = false then
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "alertscript") Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "alertscript", "Confirm();", True)
End if
Dim confirmValue As String = Request.Form("confirm_value")
If confirmValue = "Yes" Then
'Do stuff here
End if
End if

To me, this request usually represents a misunderstanding of what's going on. At the time your VB.Net code is running, the javascript doesn't exist. All server event handlers result in a full postback. That means the entire page is recreated from scratch. The VB.Net code here is part of a process that is generating an entirely new HTML document. That will involve the entire page lifecycle, including your server's Page_Load code. When the event was raised, any html already rendered in the browser was destroyed to make way for your response to a whole new HTTP request.
If you want this to respond differently, you need to build your whole HTTP response with that in mind. That means either changing how the event is raised from the outset (calling a WebMethod or other ajax request) or setting your response to call your confirm method in the javascript page load event.

Related

Lines of code before AJAX/XMLHttpRequest Call not executed

Here is the following code I have in Javascript:
document.getElementById("button").disabled = true;
document.getElementById("button").innerHTML = "Please Wait...";
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "MoodInput"+ "?moodValue=" + input, false);
xhttp.send();
When I submit the form to the Servlet, it seems like the xhttp.send() function executes first. However, I would want the the following two lines to be executed first:
document.getElementById("button").disabled = true;
document.getElementById("button").innerHTML = "Please Wait...";
What should I do to solve the problem? It has to be synchronous, because there is a thread.sleep method in the servlet in order for the Arduino to be connected with the Serial Port and set up.
While a JavaScript function is running, browsers won't do very much at all, and that includes repainting the DOM.
Your code is running in the order you want, and the DOM is being updated, the page just isn't being repainted with the changes you made.
It has to be synchronous
Synchronous XMLHttpRequests are deprecated because they cause the browser to lock up while it waits for the response. i.e. because they cause the problem you are experiencing.
because there is a thread.sleep method in the servlet in order for the Arduino to be connected with the Serial Port and set up.
That will not be affected by using a synchronous or asynchronous request.
You are probably wanting to run some other JS that you left out of your question after the response has been received.
If so, the real solution is to take whatever it is you want to do after the request has completed and move it to a function that you assign as the XHR object's load event handler.
button input type="button" does not use innerHTML for the text it uses value:
document.getElementById("button").value = "Please Wait...";
Are you using an input or a button element?

call PHP function inside JS [duplicate]

Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.

How does jQuery cause execution of JS code found inside script tags returned within an AJAX response?

What exactly is the magic that jQuery does that causes execution of JS code inside script tags found inside an AJAX response?
For example, when not using jQuery AJAX like below, I see use of eval() is frequently described as as a way to do this:
Calling a JavaScript function returned from an Ajax response
Can scripts be inserted with innerHTML?
So eval does the magic of code execution in those cases. I do not see the use of eval in jQuery AJAX calls.
jQuery Magic
$("#form").submit(function() {
$.ajax({
type : "POST",
url : 'process_form.php',
data : $("#form").serialize(),
success : function(data) {
$("#main_page").load('main_page.php');
}
});
return false;
});
Here jQuery sets up an event (form submit) to where clicking submit on a form submits the form and then it AJAX-loads the DIV with information returned from main_page.php (That page contains update information + JS + jQuery) into main_page div element. But, not just that.
It also triggers and runs and executes any JS/jQuery code located inside the script tags of the ajax-loaded data without any use of eval that I can see
Question: How does it do that?
Note:
I am using some 3rd party proprietary AJAX library, which properly loads up the response into main_page div but then it does not run any JS/jQuery.
Note 2:
to be clear, there is no problem at all with the jQuery code in question. It works and executes whatever JS was in the main_page.php. The proprietary AJAX library that I use loads up the page but does not execute any AJAX in it. I want to figure out what makes it not execute the code when jQuery executes the code.
3rd Paty Library that does not trigger script tag code execution
Delving into the library I see this:
http_req.open(method, url, true);
if (method == "POST") {
http_req.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
http_req.setRequestHeader("Content-length", post_str.length);
http_req.setRequestHeader("Connection", "close");
http_req.send(post_str);
} else if (method == "GET") {
http_req.send(null);
}
Library is called using something like this event on a submit button:
onclick="process_form(..., url, 'main_page'...)"
It also has this:
var responseObj = new getObject(response);
responseObj.obj.innerHTML = http_req.responseText;
Full code surrounding the above:
http_req.onreadystatechange = function() {
if (http_req.readyState == 4 || http_req.readyState == "complete") {
if (response != "" && redir == "") {
if (response == "document") {
document.write(http_req.responseText);
} else {
//Update of innerHTML (but without triggering execution)
//of code found in <script> tags of http_req.responseText
responseObj.obj.innerHTML = http_req.responseText;
loadingObj.style.display = "none";
}
} else if (response != "" && redir != "" && response != "over") {
load_page(redir, "", response, "GET", "");
}
}
}
My guess is that it updates innerHTML but does not ...
add it into the DOM?
do eval?
do the magic?
What is the magic that jQuery possesses that the above library skips out?
Is there a way I can fix the library to cause it to execute the code found in response script tag?
Do you know that this callback is executed in your browser, right? This have nothing to do with your server response. It only executes WHEN your server gives you data back.
You can see proper documentation on XHR here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
i hope i understand your question correctly:
success : function(data) {
$("#main_page").load('main_page.php');
}
this is the so called "success handler" - it is an event listener, that waits until the http response is received from the server. Javascript works a lot with callback functions which means, you call an action (like the ajax request) and once finished, it calls back another (often anonymous) function.
http://www.w3schools.com/js/js_events.asp
http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
jQuery uses its own Deferred's to implement callbacks including for its ajax implementation. See the code here: https://github.com/jquery/jquery/blob/master/src/ajax.js

Automatically Enable Submit button at particular time from server using PHP JS

What I'm looking for is this.
I have a simple PHP page with a submit button that is disabled by default.
I want the submit button to be enabled at a particular time for example 02:00:00
With PHP i can get the time from server with date("h:i:s") which i am using in a JS variable.
like
var time = "<? php echo date("h:i:s") ; ?>" ;
Now by using setInterval() method every millisec i am trying to compare the value of "time" variable with the
particular time i want the button to be enabled.
like if(time=="02:00:00")
{
button.disabled=false;
}
But the problem is "time" variable should also dynamically change to meet the conditions otherwise nothing will happen.I can't get any simple solution.Do i require AJAX for this?
Any help will be appreciated :)
Thanx!
I would update the time variable using JavaScript:
var curTime = new Date();
var firstColon = curTime.toString().indexOf(":");
time = curTime.toString().substring(firstColon-2, firstColon+6)
I'm a Python person, but I think PHP servers work similarly in that when going to a link, a GET request is sent, and then data is sent back, possibly a dynamically created webpage with Python code, but that webpage can't contain any Python or PHP. Those languages are strictly server-side. You could send a request to the server to get the time, but that would be really inefficient and it's better to do this client side then constantly dynamically change the webpage with requests to your PHP server.
Since this is about disabling a button, if the button sends a request to the server, remember to check that the time is right server-side just in case someone tampered with the webpage using their JavaScript console client-side.
Isn't this enable/disable done better at server side? Why do you need to enable the submit button in JavaScript at all? Will it be too bad of a solution to simply inform the user that they cannot submit operation is not available at the moment? They can always refresh the page or come back later to see if it is enabled.
Alternatively, you can simply have an ajax request that periodically pings the server to see if the button can be enabled or not. But know that a savvy user can use Web Inspector tools available in modern browsers to change DOM state. Always validate your operations at the server side. Hope this helps.
Try the following
/* ########## HTML file ######### */
<html>
<head>
</head>
<body onload="timer_function();">
<button type="submit" id="validateIt" style="none">Submit</button>
</body>
<script type="text/javascript">
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//document.getElementById("msg").innerHTML=httpxml.responseText;
//document.getElementById("msg").style.background='#f1f1f1';
}
if(httpxml.responseText == "02:00:00")
{
document.getElementById('validateIt').style.display = 'block';
}
if(httpxml.responseText >= "00:00:00" && httpxml.responseText < "02:00:00"
|| httpxml.responseText >= "02:05:00" && httpxml.responseText < "02:00:00")
{
document.getElementById('validateIt').style.display = 'none';
}
}
var url="server-clock-ckk.php";
url=url+"?sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
tt=timer_function();
}
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
} // Display server time ends
</script>
</html>
/* ########## PHP file server-clock-ckk.php ######### */
<?Php
echo date("H:i:s", time());
?>

How would we use Javascript to create a real-time feed?

I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript

Categories