Scriptino Ajax che non funge

camionistaxcaso

Nuovo Utente
14 Mag 2015
11
0
1
Ciao a tutti, come da titolo sto creando questo script per fare una richiesta asincrona. Diciamo che funzionerebbe a parte l' ultima parte dove, in base al parametro passato, invia le variabili con get o post. Insomma da proprio problemi nell' if finale. Grazie a tutti.

HTML:
function ajaxRequest(method, page, div, urlEncode)
  { 
  //alert('Funzione ajaxRequest() caricata correttamente');  
    
    objxmlhttp = xmlhttp();
    objxmlhttp.onreadystatechange=function()          
         {  
         //Simbolo di attesa          
           var caricamento="<img src='../../image/loading.gif' height='40px'>"            
           document.getElementById(div).innerHTML=caricamento;                     
           if (objxmlhttp.readyState==4 && objxmlhttp.status==200)            
           {                           
            setTimeout(
                  function()
                      {
                       document.getElementById(div).innerHTML=objxmlhttp.responseText;
                     }
                     ,2000
                        );                       
             }          
  
      }
     
     //mi si inchioda in questa parte   
     objxmlhttp.open(method, page, true);        
     if(method == "POST")
     {
     objxmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     objxmlhttp.send(urlEncode);
     }
     else
     {
       objxmlhttp.send();
     }
      
  }
       </script>
      
<input type="button" name="delete_jobs_input" value="Elimina" 
onclick="ajaxRequest('GET', 'test_3.1.php', 'divPostDel', 'id_jobs=3')">


<div id="divPostDel"></div>
 

marino51

Utente Attivo
28 Feb 2013
3.203
207
63
Lombardia
ciao, per simpatia e solidarietà cambierò il mio nick in "tutanKamion", però lascio a te confrontare il mio esempio con il tuo
Marino
HTML:
<!DOCTYPE html>
<html>
<head>
  <title>ajaxRequest</title>

  <script type="text/javascript">

function ajaxRequest(AjaxMethod, AjaxFile, AjaxHtml, AjaxParams)
{
//  alert('Funzione ajaxRequest caricata correttamente\n\r'
//	+ '\n\r'+AjaxMethod + '\n\r'+AjaxFile + '\n\r'+AjaxHtml + '\n\r'+AjaxParams); 

  var xhr, AjaxText;
  AjaxText = document.getElementById(AjaxHtml);

  AjaxFile = AjaxFile + "?timestamp=" + new Date().getTime();

  try
  {
    window.XMLHttpRequest 
      ? xhr = new XMLHttpRequest()
      : xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch (e)
  {
    AjaxText.innerHTML = "AJAX non funziona sul tuo browser";
  }
  xhr.onreadystatechange = function()
  {
    /* Gli stati di una richiesta possono essere 5
     * 0 - UNINITIALIZED
     * 1 - LOADING
     * 2 - LOADED
     * 3 - INTERACTIVE
     * 4 - COMPLETE
     */

    AjaxText.innerHTML="<img src='loading.gif' height='40px'>"; 

    if (xhr.readyState == 4)
    {
      setTimeout ( function() {
        xhr.status == 200 
          ? AjaxText.innerHTML = xhr.responseText 
          : AjaxText.innerHTML = "Si è verificato un errore nel tentativo di usare AJAX";
      }, 2000 ); 
    }
  }

  if (AjaxMethod == "GET")
  {
    AjaxFile = AjaxFile + "&" + AjaxParams;
    xhr.open(AjaxMethod, AjaxFile, true);
    xhr.send(); 
  }
  else
  {
    xhr.open(AjaxMethod, AjaxFile, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(AjaxParams); 
  }
}

</script>
</head>
<body>
  <h1>ajaxRequest</h1><br /><br />

  <input type="button" name="delete_jobs_input" value="EliminaGET" 
    onclick="ajaxRequest('GET', 'esempio_5.php', 'divPostDel', 'id_jobs=3')" />

  <input type="button" name="delete_jobs_input" value="EliminaPOST" 
    onclick="ajaxRequest('POST', 'esempio_5.php', 'divPostDel', 'id_jobs=3')" />

  <br /> <br /> 

  <div id="divPostDel"> </div>
</body>
</html>

PHP:
<?php
$id_jobs = "NON DEF.";
$tabella  = "";

if(!empty($_GET))
{
  extract($_GET,  EXTR_OVERWRITE);

  $tabella.= '<h3>GET</h3>';
  $tabella.= '<table width="800" border="0" cellspacing="5" cellpadding="5">';
  while(list($chiave, $valore)=each($_GET))
    $tabella.= "<tr><td>".$chiave." : </td><td>".${$chiave}."</td></tr>";
  $tabella.= "</table>";
}

if(!empty($_POST))
{
  extract($_POST, EXTR_OVERWRITE);

  $tabella.= '<h3>POST</h3>';
  $tabella.= '<table width="800" border="0" cellspacing="5" cellpadding="5">';
  while(list($chiave, $valore)=each($_POST))
    $tabella.= "<tr><td>".$chiave." : </td><td>".${$chiave}."</td></tr>";
  $tabella.= "</table>";
}

echo "ho cancellato il job ".$id_jobs."<br />".$tabella;
?>
 

camionistaxcaso

Nuovo Utente
14 Mag 2015
11
0
1
Leva il 5 dal nick perchè sei il numero 1! :D
Mi hai risolto anche un altro problema che mi dava e cioè che se facevo 2 richieste insieme la seconda non mi andava a buon fine. Non ho capito perchè l' open va messo per forza dentro ad ogni condizione :) Grazie sei stato superfantastico.
 

marino51

Utente Attivo
28 Feb 2013
3.203
207
63
Lombardia
la open ho preferito inserirla nella condizione perché GET vuole i parametri nella url, POST li vuole nella send,
avrei dovuto quindi aggiungere altre condizioni, ma lo script era così "lineare" ("bello")

poi ho inserito anche il time nell'url per evitare problemi di cache, già affrontati in passato
ciao
Marino
 
Discussioni simili
Autore Titolo Forum Risposte Data
R valore value di un id da passare in chiamata ajax Ajax 3
R jquery che cambia css di un elemento non mi funziona sulla pagina caricata da ajax Ajax 5
M Fullcalendar in Codeigniter, un aiuto per la chiamata $ajax ? jQuery 0
R Aggiornare record mysql con Ajax, jQuery e php Ajax 2
P Funzione jQuery Ajax invio file a php jQuery 1
E Php select option e ajax PHP 23
Emix Select concatenate php sql ajax PHP 2
MarcoGrazia Valori di ritorno json via ajax non visti. jQuery 1
felino ASP.net MVC: Exception e chiamata AJAX ASP.NET 1
motleyrulez Ricerca filtro con Ajax PHP 1
max1974 Grafico Ajax Javascript 4
max1974 Struttura $.ajax Ajax 7
C la chiamata ajax non ritorna alcun dato Ajax 1
max1974 Lettura Risultato $.ajax Javascript 1
motleyrulez Chiamata ajax per tabella php PHP 3
max1974 [Javascript] Grafico chartjs con dati da J.ajax Javascript 3
O [PHP] inviare dati da form e script ajax PHP 0
F limit show datatable ajax Ajax 1
Domenico_Falco1 Rendere dinamico un sito web con chiamate ajax e php e variabili json PHP 12
G Eseguire codice solo al termine della chiamata ajax Ajax 1
L Problema jQuery validation AJAX (PHP 7) PHP 6
max1974 [Javascript] Grafico ajax non funziona Javascript 0
WorldWideWeb Ajax POST con risposta JSON Ajax 2
M leggere con jquery/ajax in una function javascript record di database sql server Javascript 0
A [Javascript] Ajax, Jquery e PHP Javascript 1
D [Javascript] pulsanti per comandi shell con php e ajax Ajax 7
X Problema con jquery e ajax jQuery 2
B [PHP] variabili globali in chiamate ajax PHP 0
B DEBUG - PHP+JS+AJAX PHP 10
M Inserimento dati checkbox multipli in db da ajax a php PHP 1
Axis18 Creare una barra di avanzamento con $.ajax Ajax 7
otto9due Chiamata ajax su due url è possibile? Ajax 0
G [Javascript] Problema parametro passato con ajax Javascript 4
G Chiamata ajax restituisce errore random Ajax 1
paloppa [PHP] paginazione con ajax PHP 1
filomeni Ajax e https Ajax 4
bubino8 Ajax con risultato si/no Ajax 16
A redirect da pagina php chiamata da ajax PHP 2
L Aggiungere contenuto con ajax durante lo scroll jQuery 1
M Ajax funziona in alcuni siti, in altri no! Ajax 2
otto9due Risposta ajax -> json con php Ajax 3
bubino8 [PHP] split con ajax non funziona PHP 7
C Problema chiamata Ajax Ajax 2
A Visualizzare div quando le immagini sono state uploadate con successo (Ajax) Ajax 0
S Select Concatenate Ajax, php, sql Presentati al Forum 16
otto9due Error anomalo durante invio dati $.ajax Ajax 20
F Interazione tra i form html ajax e php PHP 3
D Come salvare scelta della select "dinamica" ajax-php? Come dato php o attributo value tag option? Ajax 5
D Sono disperato: Menu select dinamici con Ajax e PHP PHP 1
D Sono disperato: Menu select dinamici con Ajax e PHP Ajax 2

Discussioni simili