I am looking for a script that calls for a JavaScript function automatically when reaching the maxlength of a text field.
I tried to modify this piece of Script which I found here ajax call after x characters
$("input#zipcode").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
if(!$(this).data('triggered')) {
// set the 'triggered' data attribute to true
$(this).data('triggered',true);
if ($(this).valid() == true ) { loadXMLDoc(); }
}
} else { $(this).data('triggered',false); }
});
This is the part of code containing the loadXMLDoc part:
function loadXMLDoc()
{
var xmlhttp;
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()
{
if (xmlhttp.readyState==4)
{
document.getElementById("state_insert").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","state_insert.asp?zipcode="+document.getElementById('zipcode').value,true);
xmlhttp.send();
}
When the maxlength is reached, I want it to call for a "LoadXMLDoc" function which requires no additional parameters to be passed on.
At the moment I have it set to onblur="LoadXMLDoc()"
Like this:
[input name='zipcode' type='text' class="form_elements" id='zipcode' tabindex='11' autocomplete='off' onchange="this.value=extractNumeric(this.value)" onkeypress="return isNumericKey(event)" value='' size="4" maxlength="5" onblur="loadXMLDoc()" /]
I used the [ and ] because < and > are not allowed.
in the text field properties, but I would like that it loads as soon as the 5 digits of the Zip Code have been entered.
Thanks in advance :)
Robert.
You can do it with onkeypress event like:
onkeypress="return isNumericKey(event,this)"
along with the number it should also check for the max length. And the code should be like:
function isNumericKey(evt,zip) {
// your Number
// check here
var zipLen=zip.getAttribute('maxlength');
var zipValueLen=zip.value.length;
if(zipValueLen>=zipLen) { LoadXMLDoc(); return false;}
}
Related
My goal is to more or less send out requests to a php file, giving it parameters like so;
<!DOCTYPE html>
<html>
<head>
<script>
function onsubmit()
{
var id = $_SESSION['user']['id'];
var xmlhttp;
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
window.WhateverVariable = xmlhttp.responseText;
}
}
xmlhttp.open("GET","clientrequest.php?id="+id,true);
xmlhttp.send();
}
</script>
</head>
<body>
</body>
</html>
and keep sending out requests untill my php script returns x value, which will be passed into the window.WhateverVariable, and when the WhateverVariable is equal to 'x' I wish to execute some code;
however, I can achieve this, but when the code is executed, the request is still going meaning the response text will be 'x' and will continuously destroy then re-execute the code, any way to get past this?
if ( the_mini_game_is_not_open() )
{
// send the regular ajax request
} else {
// send the ajax request but with the message that the mini game is open through parameters maybe like ?open=1
}
And on server side deal with this like:
if ( isset ( $_GET['open'] ) && $_GET['open'] === 1 )
{
// pause it or whatever...
} else {
// show the regular results
}
This was what I understood. Sorry if that's not what you want
UPDATE Sorry I should have asked how would I do this is Jquery and is there any benefit in doing so.
Thanks
I'm currently using this code which sends the characters a user enters in an input field to a php script which checks a DB to see if an ID value is in use or contains any invalid characters.
It works fine, but I'm curious if I would be better doing it a different way.
<input type='text' name='id' id='id' onkeyup="id(this.value)" /><span id='id'></span>
function id(str)
{
if (str.length==0)
{
document.getElementById("id").innerHTML="";
return;
}
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("id").innerHTML=xmlhttp.responseText;
if (xmlhttp.responseText.indexOf("set") != -1) {
document.getElementById("submit").disabled = false;
} else {
document.getElementById("submit").disabled = true;
}
}
}
xmlhttp.open("GET","go.php?val="+str,true);
xmlhttp.send();
}
go.php is passed the individual characters and checks what is being submitted and returns the live results using :
echo stripslashes($response);
So as the user types into the text box there input is checked as they type. Is there a better way to do this ?
Thanks :)
I have a website that uses a javascript function below to populate List 2 when an item from the drop down List 1 is chosen. What I would like to achieve is to have List 2 and List 3 updated. The function is shown below works for both List 2 and List 3 separately but using an alert I can see that it stops after the first send if I put them together. How can I am make them both work together?
This is the Select that calls the function checkTeacherList which is working fine.
<select name="department_list" id="department_list" selected="All" onchange="checkTeacherList(this.value, '<?php echo $user_login;?>');" >
Th eJavaScript function checkTeacherList
<script type="text/javascript">
function checkTeacherList(departmentName, schoolName)
{
var xmlhttp;
//populating List 2
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("departmentTeachers").innerHTML=xmlhttp.responseText;
}
}
var d = new Date();
xmlhttp.open("GET","http://website/getTeachers1.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);
xmlhttp.send();
xmlhttp.send();
//populating List 3
alert("Is it getting this far?"); // this alert does not get reached
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("nondepartmentTeachers").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://website/getTeachers2.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);
xmlhttp.send();
xmlhttp.send();
}
</script>
The alert is not called because you are calling "xmlhttp.send();" twice.
The second call yields an error.
it is not really a good way to solve this problem. I should focus on setting up ONE AJAX connection , that the script just have to ask one connection.
The major advantage of using this method is the time required to gather all data. It will be double faster then doing it twice.
However, i am not sure if you can modify the php files.
If so, please edit it. I have noticed that both requests contains of same parameters.
in js;
// function to fill option
var fillOptions = function(data) {
// use data to fill drop down boxes
var teacher1 = data["teacher1"]; // get $teacher1 which is in 'teacher1'
var teacher2 = data["teacher2"]; // get $teacher2 which is in 'teacher2'
}
// function to check teacher list
function checkTeacherList(departmentName, schoolName)
{
// create object by browser type
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
// for IE6, IE5
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// event when request is done
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// get data
var data = JSON.parse(xmlhttp.responseText);
// send to function to handle it
fillOptions(data);
}
}
// open link
xmlhttp.open("GET","http://website/getAllTeachers.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);
// send
xmlhttp.send();
}
and in getAllTeachers.php ( a new php file, but you can wrap your two php file in one if you want)
$teacher1 = ... // teacher1 list
$teacher2 = ... // teacher2 list
// return with a JSON type
header('Content-Type: application/json');
// reply with json format
echo json_encode(array('teacher1' => $teacher1, 'teacher2' => $teacher2));
The php file will reply with data in JSON-format. In the js, you can see that the response is being handled with JSON.parse() function and being passed to fillOptions(data) function. There, you can access data submitted by php and use the same data to fill in your dropdown box.
(i don't know the response content, but
document.getElementById("nondepartmentTeachers").innerHTML = data["teacher2"];
should achieve the same result as intended )
If you want to go with your solution, you have called .send() function twice, which the second one will return into errors.
i have an input text , and i want when i click in a button it takes that value and pass it in a parameter in a url , this is my code so far :
<div id="landmark-1" data-landmark-id="1">
<form name ="data">
<label>enter your name :</label>
<input type= "text" placeholder="ID" name="ID" value="" style="width:206px;" />
<input type="submit" value="Suivant" onclick="showUser(this.form)" >
</form>
</div>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
and this is my javascript code :
<script>
function showUser(frm)
{
var str = frm.ID.value;
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
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() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/filename/page.php?q="+str,true);
xmlhttp.send();
}
</script>
but when i enter a name, it just add : ?ID=name in the url of the current page ! it doesn't send the parameter in the url i want ..
Change your code from: onclick="showUser(this.form)" to onclick="return showUser(this.form)"
and
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
to
if (str==""){
document.getElementById("txtHint").innerHTML="";
return false;
}
Your form is being submitted even if there is no ID entered. The return false prevents the form submission.
Here is a revised AJAX call. It is a bit more complicated than the w3schools example but it is more functional and complete. First the AJAX routine:
function AJAX( url, processFunction ) {
var XHR;
try{
// Opera 8.0+, Firefox, Safari/Chrome
XHR = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
XHR = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser doesn't support AJAX!");
return false;
}
}
}
if( XHR.onreadystatechange ) {
if( XHR.readyState == 4 ) {
if( XHR.status == 200 ) {
//--- we've got the data so process it
processFunction( XHR.responseText );
}
if( XHR.status != "OK" ) {
alert( 'Error : '+XHR.responseText);
}
}
}
//--- open
XHR.open( 'GET', url ); // --- url is from the function call
//--- send
XHR.send();
}
Now the function that will handle the returned data. In this case you simply want to display the text:
function processMyData( data ) {
document.getElementById("txtHint").innerHTML= data;
}
Now for the modified showUser function
function showUser(frm) {
var str = frm.ID.value;
if (str==""){
document.getElementById("txtHint").innerHTML="";
return false;
} else {
AJAX( "http://localhost/filename/page.php?q="+str, 'processMyData' )
}
}
If there is an error in you php file it should show up in the alert box.
If your code still isn't returning anything and there is no error the only other thing that I can think of is that you are not echo/print-ing your data for the AJAX routine to retrieve your text.
The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html