HighDots Forums  

le mie piccole funzioni per ajax

Javascript (Italian) Il linguaggio JavaScript (it.comp.lang.javascript)


Discuss le mie piccole funzioni per ajax in the Javascript (Italian) forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
nintesa
 
Posts: n/a

Default le mie piccole funzioni per ajax - 02-08-2008 , 02:27 PM






Da qualche mese ho iniziato ad usare ajax con php... ho chiesto spesso
aiuto su questo e su altri ng e ho scopiazzato da tutorial e blog...

Alla fine copiando e copiando ho messo su un paio di funzioni che
sembrano funzionare!! Le posto nella speranza che a qualcuno siano utili
e magari che qualcuno posti delle migliorie.

Ecco qua:


Il tutto presume questa dichiarazione css (nel foglio di stile o dove
utile) relativa al box da visualizzare con l'iconcina che indica che
ajax sta lavorando. Questo è il css:

..ajax_loading {
position: absolute;
min-width: 64px;
min-height: 64px;
background: #F0F0F0;
border: 1px solid #C0C0C0;
background-image: url(css_images/ajax-loading.gif);
background-position: center center;
background-repeat: no-repeat;
z-index: 100;
opacity: 0.70;
}

questa funzione serve per creare il box dell'iconcina "ajax loading":

function ShowAjaxLoading (div_id) {
var MainDiv = document.getElementById(div_id);
var AjaxLoadingDiv = document.createElement("div");

var curleft = curtop = 0;
obj=MainDiv;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}

AjaxLoadingDiv.id = "ajax_loading_div";
AjaxLoadingDiv.className= "ajax_loading";
AjaxLoadingDiv.style.top = curtop + MainDiv.offsetTop;
AjaxLoadingDiv.style.left = curleft + MainDiv.offsetLeft;
AjaxLoadingDiv.style.width = MainDiv.offsetWidth+"px";
AjaxLoadingDiv.style.height = MainDiv.offsetHeight+"px";
AjaxLoadingDiv.style.visibility = "visible";
var MainDivParent = MainDiv.parentNode;
MainDivParent.appendChild(AjaxLoadingDiv);
}

quest'altra funzione elimina il box ajax loading.

function HideAjaxLoading (div_id) {
var MainDiv = document.getElementById(div_id);
var AjaxLoadingDiv = document.getElementById("ajax_loading_div");
var MainDivParent = MainDiv.parentNode;
MainDivParent.removeChild(AjaxLoadingDiv);
}

Questa è la funzione principale.
1) scripttocall è lo script php (con tanto di parametri) da chiamare in
background
2) div_id è l'id del div della pagina in cui verrà piazzato il risultato
(in termini di html) dello script chiamato

ad esempio:

abbiamo
<div id="box_saluti"></div>

e saluta.php così scritto:

<?
//saluta.php
echo 'Ciao bello!';
?>

se chiamiamo ajaxFunction('saluta.php','box_saluti')

all'interno del div 'box_saluti' verrà visualizzato "Ciao bello!":

Ecco la funzione:

function ajaxFunction(scripttocall,div_id){
var ajaxRequest; // The variable that makes Ajax possible!
var AjaxLoadingDivIsShown=false;

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
var response = ajaxRequest.responseText;
if (ajaxRequest.readyState==4 && ajaxRequest.status==200) {
if (response == '$command=window.reload;') {
window.location.reload();
} else {
var ajaxDisplay = document.getElementById(div_id);
ajaxDisplay.innerHTML = response;
HideAjaxLoading(div_id);
}
} else {
if (ajaxRequest.readyState==1 && AjaxLoadingDivIsShown==false) {
var ajaxDisplay = document.getElementById(div_id);
ShowAjaxLoading(div_id);
AjaxLoadingDivIsShown=true;
}
}
}

ajaxRequest.open("GET", scripttocall, true);
ajaxRequest.send(null);
}


Quest'ultima funzione serve per usare, all'interno di un div, un form
che lavori in background.
Si crea il form e nel bottone di conferma, nell'opzione onclick si
richiama questa funzione. I parametri sono quelli della precedente:
input_form è l'id del form.

function ajaxSubmitPostForm(input_form,scripttocall,div_id) {
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}

var num_elements = document.getElementById(input_form).elements.lengt h;
input_string= "";
for(var i = 0; i < num_elements; i++){
if(i < num_elements-1){
input_string +=
document.getElementById(input_form).elements[i].name+"="+encodeURIComponent(document.getElementBy Id(input_form).elements[i].value)+"&";
} else {
input_string +=
document.getElementById(input_form).elements[i].name+"="+encodeURIComponent(document.getElementBy Id(input_form).elements[i].value);
}
}

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
var response = ajaxRequest.responseText;
if (ajaxRequest.readyState==4 && ajaxRequest.status==200) {
if (response == '$command=window.reload;') {
window.location.reload();
} else {
var ajaxDisplay = document.getElementById(div_id);
ajaxDisplay.innerHTML = response;
}
} else {
if (ajaxRequest.readyState==1) {
var ajaxDisplay = document.getElementById(div_id);
ajaxDisplay.innerHTML ='<div class="ajax_loading"></div>';
}
}
}

ajaxRequest.open("POST",scripttocall,true);

ajaxRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;
charset=UTF-8");
ajaxRequest.send(input_string);
}

Spero di non avervi annoiato!
Saluti a tutti.

Reply With Quote
  #2  
Old   
whisher
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-08-2008 , 05:10 PM






On Feb 8, 9:27*pm, nintesa <nint... (AT) nomaaaaail (DOT) it> wrote:
Quote:
Da qualche mese ho iniziato ad usare ajax con php... ho chiesto spesso
aiuto su questo e su altri ng e ho scopiazzato da tutorial e blog...

Alla fine copiando e copiando ho messo su un paio di funzioni che
sembrano funzionare!! Le posto nella speranza che a qualcuno siano utili
* e magari che qualcuno posti delle migliorie.

Posto questo esempio secondo me è un metodo molto
+ elastico

function XHConn(){
var xmlhttp= window.XMLHttpRequest ? new XMLHttpRequest() : new
ActiveXObject("Microsoft.XMLHTTP");
this.connect = function(mURL, mMethod, data, fnDone, fnError){
xmlhttp.open(mMethod, mURL, true);
xmlhttp.setRequestHeader("connection", "close");
xmlhttp.setRequestHeader('User-Agent','XMLHTTP/1.0');
if(mMethod == "POST"){
xmlhttp.setRequestHeader("Method", "POST "+mURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-
urlencoded");
xmlhttp.setRequestHeader('Content-Length', data.length);
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
fnDone(xmlhttp);
}
else{
fnError(xmlhttp);
}
}
}
xmlhttp.send(data);
}
};
function errorHandler(xhr){
alert("HTTP error: "+xhr.status);
}
function onSuccess(xhr){
alert('Stop loading');
alert(xhr.responseText)
//si può mettere anche xhr.responseXML
}
function testXHConn(){
//qui puoi mettere i valori che recuperi dalla form dato che ci sei li
//potresti spedire con Json e se sei su php5 con json_encode uno
spettacolo !
new XHConn().connect('test_1.php', 'POST', 'id=pippo', onSuccess,
errorHandler);
alert('Loading ......');
}
testXHConn();
insomma ci puoi fare quello che vuoi non sei legato
ad una implementazione 'rigida'

Quote:
* *ajaxRequest.onreadystatechange = function(){
* * *var response = ajaxRequest.responseText;
Questo mi è saltato all'occhio
perchè recuperi ajaxRequest.responseText
prima di readyState == 4 e status == 200


Ciao.




Reply With Quote
  #3  
Old   
nintesa
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-08-2008 , 05:18 PM



Quote:
Posto questo esempio secondo me è un metodo molto
+ elastico
me lo studio con calma...

Quote:
Questo mi è saltato all'occhio
perchè recuperi ajaxRequest.responseText
prima di readyState == 4 e status == 200
perché sono distratto!


Reply With Quote
  #4  
Old   
Gufo Rosso
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-08-2008 , 11:23 PM



whisher ha scritto:
Quote:
On Feb 8, 9:27 pm, nintesa <nint... (AT) nomaaaaail (DOT) it> wrote:
Da qualche mese ho iniziato ad usare ajax con php... ho chiesto spesso
aiuto su questo e su altri ng e ho scopiazzato da tutorial e blog...

Alla fine copiando e copiando ho messo su un paio di funzioni che
sembrano funzionare!! Le posto nella speranza che a qualcuno siano utili
e magari che qualcuno posti delle migliorie.


Posto questo esempio secondo me è un metodo molto
+ elastico

function XHConn(){
var xmlhttp= window.XMLHttpRequest ? new XMLHttpRequest() : new
ActiveXObject("Microsoft.XMLHTTP");
this.connect = function(mURL, mMethod, data, fnDone, fnError){
xmlhttp.open(mMethod, mURL, true);
xmlhttp.setRequestHeader("connection", "close");
xmlhttp.setRequestHeader('User-Agent','XMLHTTP/1.0');
if(mMethod == "POST"){
xmlhttp.setRequestHeader("Method", "POST "+mURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-
urlencoded");
xmlhttp.setRequestHeader('Content-Length', data.length);
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
fnDone(xmlhttp);
}
else{
fnError(xmlhttp);
}
}
}
xmlhttp.send(data);
}
};
function errorHandler(xhr){
alert("HTTP error: "+xhr.status);
}
function onSuccess(xhr){
alert('Stop loading');
alert(xhr.responseText)
//si può mettere anche xhr.responseXML
}
function testXHConn(){
//qui puoi mettere i valori che recuperi dalla form dato che ci sei li
//potresti spedire con Json e se sei su php5 con json_encode uno
spettacolo !
new XHConn().connect('test_1.php', 'POST', 'id=pippo', onSuccess,
errorHandler);
alert('Loading ......');
}
testXHConn();
insomma ci puoi fare quello che vuoi non sei legato
ad una implementazione 'rigida'

ajaxRequest.onreadystatechange = function(){
var response = ajaxRequest.responseText;

Questo mi è saltato all'occhio
perchè recuperi ajaxRequest.responseText
prima di readyState == 4 e status == 200


Ciao.



dove trovo un esempio di json
(salva form) ?
uso php5 e javascript
molto banale

sono molto INCAZZATO perche ajax non fa l'upload dei file se non con
stratagemmi assurdi
















Reply With Quote
  #5  
Old   
whisher
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-09-2008 , 01:49 AM



On Feb 9, 6:23*am, Gufo Rosso <spaaaaaamaaa... (AT) libero (DOT) it> wrote:
Quote:
whisher ha scritto:



dove trovo un esempio di json
(salva form) ?
uso php5 e javascript
molto banale
http://www.blogial.net/old/index.php?view=13
Quote:
sono molto INCAZZATO perche ajax non fa l'upload dei file se non con
stratagemmi assurdi
http://forum.html.it/forum/showthrea...readid=1177950


Ciao.


Reply With Quote
  #6  
Old   
whisher
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-09-2008 , 02:02 AM



Dai pure un occhio a questo thread
http://www.sitepoint.com/forums/showthread.php?t=529226
nell'esempio c'è Jquery ma basta toglierlo
in validator.values ci sono tutti i valori che puoi spedire
con Json.

Ri-ciao m ma siete nottambuli

Reply With Quote
  #7  
Old   
whisher
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-09-2008 , 02:08 AM



Ho ritrovato il codice senza Jquery
http://forum.html.it/forum/showthrea...d ator+system
(nel primo c'è anche l'esempio di utilizzo)
sono ancora addormentato stamani !


Reply With Quote
  #8  
Old   
whisher
 
Posts: n/a

Default Re: le mie piccole funzioni per ajax - 02-09-2008 , 02:15 AM



Un po di pubblicità
http://www.blogial.net/index.php?p=3
nella form per i commenti ho utilizzato
quel sistema.

Ri-ciao.

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.