Why is body onload = javascript function executed continuously? - javascript

Sorry for the really newbie question, just starting to learn AJAX.
I'd like to understand what exactly in the following causes the divMessage content to change continuously when "myName" text is changed.
1) It would seem that the Javascript function process is constantly "listening", is this normal Javscript behavior, or are there any triggers to call "process" repeatedly?
2) Is it true that any function that we assign to "body onload" will be executed repeatedly? How often is this repeated execution?
3) What if we want a single execution of the function process, how to do this?
4) I'm confused because I'm thinking the body will only load once. But is it because after "body onload" the function "process" is called, and the function process in turn modifies the "body" by changing the divMessage, essentially letting it go thru "body onload" again, then "process" again, etc.. ?
Thanks a lot in advance for your help!
<head>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
Here's quickstart.js processing parts
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(
document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
}
// callback function executed when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
helloMessage = xmlDocumentElement.firstChild.data;
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage+ '</i>';
}
}
}
and the quickstart.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don't know you!';
echo '</response>';
?>

Found the answer by shutting down and trying to run this again.
It turns out there was additional code that I commented out
but was cached that calls "process" every 1 second from handleServerResponse():
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage+ '</i>';
setTimeout('process()', 1000);
Sorry about that. Lesson is to clear the browser cache before testing each code change :)
So I guess the advice to check if this function is called from any other place is correct.
Anyway, I read a great deal and learned a lot while trying to figure
this out. Thanks a lot #pst!

Related

POST with Javascript AJAX

I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:
function newoption()
{
var option = "";
while((option.length < 1)||(option.length > 150))
{
var option = prompt("Please enter the option value... ").trim();
}
var add = confirm("You entered " + option + ", are you sure?");
if(add==1)
{
var code = window.location.href.length;
var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{this.responsetext = option;}};
xhttp.open("POST", "../special/new.php", true);
xhttp.send("poll=" + poll + "&opt=" + option);
}
else
{
alert("OK... try again");
}
}
The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?
The code for new.php is:
<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
new_poll_option($connection, $poll, $option);
}
?>
From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.
You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome).
If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.
You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.

send content of dynamically changing div to database

I have a Server Send Event working and updating a webpage. I then assign the contents of the div receiving the SSE to a var so as to send it to a php file to insert into a database. The div's data is constantly changing in sseReceiving.php page, but how to send it and it's changing values to the database dynamically. Now it is only sending the div content to the database when the page is re-submitted. How to do it continually?
sseTriggering.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
//echo "data: New random number:". $new_data. "\n\n";
echo "data:".$new_data."\n\n";;
flush();
sseReceiving.php
<body>
<div id="serverData">Here is where the server sent data will appear</div>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("sseTriggering.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
var MyDiv = document.getElementById("serverData").innerHTML;
window.location.href = "findpair.php?pair=" + MyDiv;
};
}
</script>
</body>
findpair.php
$pair = $_GET['pair'];
$qX = "UPDATE product SET prod_name = '$pair' WHERE id = 1";
$rrr = mysqli_query ($dbc, $qX) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
I have researched this issue at the links below and some have helped me get it to the stage it is at now.
http://www.coderslexicon.com/the-basics-of-passing-values-from-javascript-to-php-and-back/
send javaScript variable to php variable
Get content of a DIV using JavaScript
Detect element content changes with jQuery
I have also put header('Refresh: 5'); in the php part of the various files and no change.
You should be able to send the request via AJAX for your main function which will allow the sse events to come to your client and then go to your findpair.php function.
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("sseTriggering.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
//Send AJAX request.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do something with 'xmlhttp.responseText' if you want.
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
} else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "findpair.php?pair=" + event.data, true);
xmlhttp.send();
};
}
More info here on submitting AJAX requests with javascript.

fwrite error - problems writing serial output rapidly

Firstly, I apologize if this issue has been posted before, I couldn't find the answer anywhere.
I'm writing a one page website that uses JavaScript, Ajax and PHP to take key presses and send them out via serial port.
I'm testing it on EasyPHP and WAMP, I'm yet to test on a Linux server.
My problem is that when keys are pressed rapidly I get the error below.
Warning: fopen(com4): failed to open stream: Permission denied in \keypresstest.php on line 7
If I press keys slowly, around 500ms intervals, it all works fine.
Furthermore, following the error above, PHP does not set my $fp variable, so it also returns errors:
Warning: fwrite() expects parameter 1 to be resource, boolean given in \keypresstest.php on line 9
Warning: fclose() expects parameter 1 to be resource, boolean given in \keypresstest.php on line 10
I think that there is slow 'release' of the serial port resource which it's defining as 'Resource id #3' and if I could some how speed this up or spawn another instance when needed i might be able to resolve the issue.
I hope someone reading this might have some advice.
My code is below, I've removed some components to keep this code more concise
HTML File
<script> <!-- call php script here -->
function sendKey(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + xmlhttp.responseText;
}
}
xmlhttp.open("GET", "keypresstest.php?q=" + str, true);
xmlhttp.send();
}
</script>
<script> // page js key listener script
document.addEventListener('keydown', function(event) { // things happen as keys are pressed
if (!arrayContainsCheck(keysHeld, event.keyCode)) { // check if the key is already being held, this is so keydown events don't continue to propagate whilst a key is held
if(event.keyCode == 38 || event.keyCode == 87) { // up/w keys, send output to php script "f"
sendKey("f");
} keysHeld.push(event.keyCode);
}
});
document.addEventListener('keyup', function(event) {
document.getElementById("lightSwitch").style.backgroundColor = "blue";
if(event.keyCode == 38 || event.keyCode == 87) { // up/w keys, send output to php script "g"
document.getElementById("upArrow").style.border = "1px solid red";
sendKey("g");
}
keyRelease(keysHeld, event.keyCode);
});
</script>
PHP File
<?php
$q = $_REQUEST["q"]; // get the q parameter from URL
// Output q parameter to com4 serial port
echo "q is $q <br />";
echo "defining fp... <br />";
$fp = fopen("com4", "w");
echo "fp defined as " . $fp . " .<br />";
fwrite($fp, $q);
fclose($fp);
?>

How to send variable from javascript to PHP on azure websites?

To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!

Ajax Form Validation Problem

I've got my form validation almost working but I can't seem to figure this last problem out.
I'm trying to send back error messages and position them in their own div next to their relevant form fields.
I've got an error message coming back in its own div, but when I try to send multiple messages back nothing happens, any thoughts?
Here's most of my ajax
function regForm(thisform) { //Reg user form check
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request");
return;
}
var formdata = "";
formdata = "lname=" + thisform.elements['lname'].value + "&fname=" + thisform.elements['fname'].value + "&email=" + thisform.elements['email'].value + "&username=" + thisform.elements['username'].value + "&pass=" + thisform.elements['pass'].value + "&pass2=" + thisform.elements['pass2'].value; //send the data through the url - frist is the name i want to call it... second grad the content from the form using its id
xmlHttp.onreadystatechange=formSubmitted;
xmlHttp.open("POST", "adduser.php",true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", formdata.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(formdata);
return false;
}
function formSubmitted() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
xmlDoc=xmlHttp.responseXML;
//document.getElementById("feedback").innerHTML = xmlHttp.responseText;
document.getElementById("feedback1").innerHTML= xmlDoc.getElementsByTagName("lname")[0].childNodes[0].nodeValue;
document.getElementById("feedback2").innerHTML= xmlDoc.getElementsByTagName("fname")[0].childNodes[0].nodeValue;
}
}
and here is my simple adduser.php page so far
<?php
header('Content-Type: text/xml');
$lname = mysql_real_escape_string($_POST['lname']);
$fname = mysql_real_escape_string($_POST['fname']);
if($lname == NULL) {
echo "<lname>NEED TO FILL</lname>";
}
//if($fname == NULL) {
//echo "<fname>NEED TO FILL</fname>";
//}
else {
echo "<lname> </lname>";
//echo "<fname> </fname>";
}
?>
As you can see I've got the fname information commented out right now and my messaging is working for lname but as soon as I uncomment the fname stuff in hopes to send a message for both lname and fname nothing happens I don't understand why.
Any insight would be a big help! Thanks.
I don't entirely understand what you mean by "coming back in its own div" but you are aware that an element ID must be unique in the document? There doesn't happen to happen that you get two DIVs of the same ID if the error DIV comes back?
Try having only a single echo statement at the very end of the script (so have a variable to concatenate all your error messages and only echo it at the very end).
Also, I would very strongly recommend using a JS library (like jQuery) for all your ajax needs - will make your life a whole lot easier
ok I've got it figured out and like always it was stupid why it wasn't working.
in my adduser.php page I just need to wrap the error message in a xml tag.
echo "<errors>";
//error content
echo "</errors>";

Categories

Resources