I have am HTML form in a PHP page. The form has various inputs. One of the inputs has an onchange event:
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value);showWhse(1, this.value)">
This calls the following function:
<script type="text/javascript">
function showUser(userNumber, str)
{
if (str=="")
{
document.getElementById("txtHint" + userNumber).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("txtHint" + userNumber).innerHTML=xmlhttp.responseText;
var responseText = xmlhttp.responseText;
var description = responseText.substring(12, responseText.indexOf(",Warehouse:"));
var warehouse = responseText.substring(responseText.indexOf(",Warehouse:")+11, responseText.indexOf(",SellingUnits:"));
var sellingUnits = responseText.substring(responseText.indexOf(",SellingUnits:")+14);
document.getElementById("whse" + userNumber).innerHTML = warehouse;
document.getElementById("txtHint" + userNumber).innerHTML = description;
document.getElementById("su" + userNumber).innerHTML = sellingUnits;
}
}
xmlhttp.open("GET","getdata1.php?q="+str,true);
xmlhttp.send();
}
</script>
This works 100%. if however, the input is populated by a session variable, and the page is refreshed, how can I get the script to execute again onload, without an onchange event?
so when the page is first visited, id the input has a value, execute the script?
Just execute the function onload?
window.onload = function init() {
showUser(1, document.getElementById("sku1").value);
}
You may also use the onload attribute of your document's body, or add the init function as an event handler to DOMContentLoaded. But I'm sure you already have some functions which are executed onDOMready.
you can also use the ready function from the jquery
$(document).ready(function() {
showUser(1, $("#sku1").val());
});
Well, you can use the onload event. You may also want to consider using Jquery's document.ready functionality. The difference can be found here. Also, Jquery provides a much more concise syntax for accessing your form elements
In either case, you would probably simply need function that does something like checking the field has a value.
<script type="text/javascript">
function showUserOnLoad()
{
var inputValue = $('#sku1').val();
if(inputValue != '' && inputValue != null)
showUser(1, inputValue);
}
function showUser(userNumber, str)
{
...
}
</script>
Related
Here I posted one variable to PHP script. Response from php script I am writing to some div. But after button click, instantly the response disappears:
When I do alert(arabic); it displays but as I close prompt, it disappears.
Why does it reload the page after response from php script?
$( "#submit" ).click(function() {
var cat = $("#cats option:selected").html();
// alert(test);
var arabic = document.getElementById("arabic").value;
//alert (arabic)
dataInsert(arabic);
});
function dataInsert(arabic)
{
var xmlhttp;
//alert("hi");
show.innerHTML = '';
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
//document.getElementById("old-records").innerHTML = "";
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var div2 = document.getElementById("show");
div2.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","koove_insertpost_db.php");
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('arabic=' + arabic ) ;
//alert(arabic);
}
It looks like your button is trying to submit something, thus overlapping your callback function. You might want to use the parameter event to stop it's propagation.
Check this code:
$( "#submit" ).click(function(event) {
event.stopPropagation();
var cat = $("#cats option:selected").html();
//alert("test");
var arabic = document.getElementById("arabic").value;
//alert (arabic)
dataInsert(arabic);
return false;
});
}
You should also return false at the end of the callback function, in order to completely stop processing the event after your instructions. This is the key to perform your dataInsert() function without interruption.
Are you using jQuery? looks like it with the $( "#submit" ).click(function() {});
why not make life easy and just use
$( "#submit" ).click(function() {
var arabic = $("#arabic").value();
$.post("koove_insertpost_db.php",{"arabic" : arabic}, function( data ) {
$('#show').html(data);
});
});
http://api.jquery.com/jquery.post/
you can also check the success status etc for data validation from the server.
I cant comment yet so i believe #feijones has the answer! ( especially return false; )
p.s. Alert works because it halts the execution of the JavaScript until you close the dialog, which then submits the form and reloads the page.
Im currently in the learning process with AJAX & JavaScript..
I have a quick question to the wise..
How can i turn the code below into a timed event instead of an OnClick event.
**For Example i would like to refresh the "showlist" DIV every 5 seconds...
I understand that this is working code and goes against the rules of the site but if i were to post my non working code it would just confuse things as it has me..
I am trying to slowly understand the basics :)
Any guidance would be greatly appreciated
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showlist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>
</html>
You can change loadXMLDoc function to make use of setTimeout. Consider this example:
function loadXMLDoc() {
var xmlhttp,
timer;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("showlist").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.onerror = function() {
clearTimeout(timer);
};
xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
xmlhttp.send();
timer = setTimeout(loadXMLDoc, 5000);
}
Function issues AJAX request and set up a 5s timeout. I also added basic onerror callback to clear timer just in case.
I once made a kind of tv, which automatically changed the 'screen' after 3 seconds.
Maybe you can re-use my code?
// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
if(i > (totalPics - 1)){
i = 0;
}
myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
i++;
loopTimer = setTimeout('loop()',3000);
}
loop();
I hope you can re-use this for your project, and I hope you kind of understand what I mean, if I need to clarify, just ask me :).
So what you need to do, is refresh the array when you got new item in your showlist.
This function (if placed inside the same script tag after your loadXMLDoc fn) will execute and call your function and then itself again every 5 seconds (recursively). You could call setInterval instead, but that runs the risk of occasionally missing a cycle if the js engine is busy:
(function doMeSelf(){
setTimeout(function(){
loadXMLDoc();
doMeSelf();
},5000);
})();
Enclosing the function def inside parens, and then followed by () is called an immediately invoked function expression.
See this question for some background: What do parentheses surrounding a object/function/class declaration mean?
I am working on a program using python, HTML and javascript. I have two images that works as a button changin colors onmouseover and onmouseout. It also has a function that works when the onclick event happens. Everything is working very well on Internet Explorer (which is extrange) but the onclick event is not working on safari,chrome or firefox. The error console doesnt mark any error, neither the error.log on console.
Do you see anything wrong with the code? Are there some functions like onmouseover or onmouseout or onclick that does not work on those browsers?
<td><img src="/RH/images/tacha.png" onclick="eliminarRenglon('eliminar','%s');testing()"
onmouseover="this.src='/RH/images/tacha_2.png'" onmouseout="this.src='/RH/images/tacha.png'" /></td>''' % variable
function testing(){
alert("JUST TESTING");
}
not even the "testing" function works. The "eliminarRenglon" function works very well on IE, and also the "testing" function. Here is the code of the "eliminarRenglon", but as it works very well on IE i dont know if the problem is with it.
function eliminarRenglon(tipo,id) {
var nivel = "No"
var divPrincipal = document.getElementById("divPrincipal");
var idReq = document.getElementById("req" + id).value;
var claveProyecto = document.getElementById("claveproyecto").value;
var url = 'actualizarRenglonAjax.py?nivel='+nivel+'&tipo='+tipo+'&idReq='+idReq+'&claveProyecto='+claveProyecto;
if(document.getElementById("selectReq" + id).value == ""){
xmlhttp = GetXmlHttpObject(nivel);
if(!xmlhttp) {
alert("Browser does not support HTTP Request");
return;
}
var xml = xmlhttp;
xmlhttp.onreadystatechange = function() {
if(xml.readyState == 1) {
loading.innerHTML = "<img src='/RH/images/loading_4.gif' />"
}
if(xml.readyState == 4) {
divPrincipal.innerHTML = xml.responseText;
actualizarTodo();
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
return true;
}
else
alert("No se puede eliminar");
}
I would really appreciate the help
Thanks a lot!
I'd suggest adding a selector value to the image, then binding events the unobtrusive way (makes maintenance a bit easier later on).
Do it like this:
<img src="/RH/images/tacha.png" class="myImage" />
then, after the DOM is loaded, attach your events (jquery here for simplicity)
$('img.myImage').bind('click', function() {
alert('testing!');
eliminarRenglon('eliminar','%s');
});
var xmlhttp;
//Set up ajax first so he knows which guy to play with
function loadXMLDoc(url,cfunc)
{
//Code to catch modern browsers
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//Code to catch crap browsers
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//Set up
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
//Set a function to deploy when something calls myFunction()
function myFunction()
{
loadXMLDoc("../../../support/ajaxTest.txt",function()
{
//Fires off when button pressed
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("statusRefresh").innerHTML=xmlhttp.responseText;
setInterval( "alert('Hello I did something but i needed to be invoked by a button first')", 5000 );
}
});
}
I want to call restful java service to refresh a 'status'. I need ajax to auto refresh the this status once the page has been hit. The Refresh method isnt instantaneous, for it has to talk with other machines.
function autoRefresh()
{
var url = "../../../support/ajaxTest.txt";
var target = document.getElementById("statusRefresh");
var doRefresh = function()
{
loadXMLDoc(url, function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
target.innerHTML=xmlhttp.responseText;
}
}
});
setInterval( doRefresh, 5000 );
}
and
document.onload = autoRefresh;
more information is needed such as what is your goal, what do you currently have......what are you trying to do......If its a script thats triggered by something from example a user viewing your page or click a button then use that button to triiger the function to auto refresh
Another way is to use a crob job
After pressing a button, I'm sending the whole HTML content from a webpage (the part within the <html> tags) to a CGI script which manipulates the content and sends it back.
Now I'm trying to replace the existing content with the new one. Unfortunately after assignment, every single <head> or <body> tag (as well as the closing ones) will be killed.
By using some alerts I looked through the returning value as well as the original HTML stuff. Both are absolutely as expected.
But after the assignment there is some magic going on. Please help me to figure out what's going on.
Here is the used JavaScript code I used:
var originalBodyInnerHTML = document.body.innerHTML;
var htmlNode = document.getElementsByTagName('html')[0];
var post_parameters = encodeURIComponent(htmlNode.innerHTML);
makePOSTRequest("POST", "http://whatever.com/cgi-bin/doit.cgi", post_parameters, htmlNode);
function makePOSTRequest(method, url, parameters, htmlNode) {
var http_request = getRequestObj();
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function()
{
if (http_request.readyState < 4)
{
var waitingPageBody = '< img src="/img/ajaxloader.gif" alt="in progress..."/>';
document.body.innerHTML = waitingPageBody;
}
else //if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
alert('1response: ' + http_request.responseText);
alert('2innerhtml: ' + document.getElementsByTagName('html')[0].innerHTML);
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText;
}//end of if (http_request.status == 200)
else
{//other http statuses
alert("There was a problem (" + http_request.statusText + ", " + http_request.status + ' error)');
bodyNode.innerHTML = originalBodyInnerHTML;
}
}//end of else if http_request.readyState == 4
}
http_request.open(method, url, true); //async
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function getRequestObj() {
var http_request = false;
if (window.XMLHttpRequest)
{ // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject)
{ // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return http_request;
}
This is a simple solution that worked for me. Just as a reference.
document.clear();
document.write(newHtml);
where newHtml is the complete html of new web page.
well, with this
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText
you are replacing everything insidee the html, "killing" body, head and everything...
maybe you wanted
document.body.innerHTML = http_request.responseText
Also, I'd use jquery, it makes your life sooo much easier
You cannot do that. It's not possible to replace the contents of the whole html tag. You can get away with replacing only the contents of the body tag. The head element is kind of magical and browser generally don't support replacing it.
If you want to change the whole document, redirect to it.
If you want to change only parts of the head, try sending them in a different form (like JSON), and make appropriate changes using javascript APIs.
Thanks qbeuek for your answer!
To change only the header, Firefox in fact will allow something like this:document.getElementsByTagName('head')[0] += "e.g. some scripts"
But for Internet Explorer it is necessary to add each element separately to the DOM tree.
var script = document.createElement("script");
script.setAttribute('type','text/javascript');
objHead.appendChild(script);
However, it is really weird that Firefox behaves like this and not popup with some error...