Metoda ajax() se foloseste pentru a efectua o cerere AJAX (asynchronous HTTP) la server.
Toate functiile Ajax jQuery: load(), get(), post(); folosesc metoda ajax(). Aceasta contine mai multe optiuni de configurare si prelucrare a datelor, iar sintaxa ei este mai complexa.
$.ajax({ nume:valoare, nume:valoare, ...})- Parametri reprezinta una sau mai multe perechi nume:valoare, care configureaza cererea Ajax. Sunt prezentati mai jos, dar mai intai iata un exemplu simplu cu o cerere Ajax prin POST:
$.ajax({ type: 'POST', url: 'script.php', data: 'nume=un_nume&id=un_id', success: function(raspuns){ $('#result').html(raspuns); } });Datele: "nume=un_nume&id=un_id" sunt trimise pe server la "script.php" prin POST, apoi, raspunsul de la server e adaugat intr-un element HTML (cu id="result").
$.ajax({ url: "file.php", async: false });
$.ajax({
url: "file.php",
beforeSend: function() {
xhr.setRequestHeader("Accept", "text/javascript");
$('#resp').html('Loading...');
},
success: function(raspuns){
$('#resp').html('raspuns');
}
});
$.ajax({ url: "file.html", cache: false });
$.ajax({ url: "file.php", complete: function() { alert('Trimis complet'); } });
$.ajax({ type: "POST", url: "file.php", data: "{'nume1':'valoare', 'nume2':'valoare'}", contentType: "application/json; charset=utf-8", dataType: "json" });
$.ajax({ url: "file.php", context: $('#idd'), success: function(){ $(this).html('Succes'); // this va fi "#idd" } });
$.ajax({ type: "GET", url: "file.php", data: "id=78&nume=un_nume" });
$.ajax({ url: "file.php", data: {'json':'datas'}, contentType: "application/json; charset=utf-8", dataFilter: function(data) { var resp = eval('(' + data + ')'); return resp; }, success: function(raspuns, status, xhr){ $('#idd').html(raspuns.property); } });
$.ajax({ // Incarca si executa un fisier JavaScript type: "GET", url: "file.js", dataType: "script" });
$.ajax({ url: "file.php", error: function(xhr, status, error) { alert(error); } });
$.ajax({ url: "file.php", global: false, success: function(msg){ alert(msg); } });
$.ajax({ headers: { "Content-Type": "application/json", "Accept": "application/json" }, type: "POST", url: "file.php", data: {'json': 'data'}, dataType: "json", success: function(json){ // do something... } });
$.ajax({ url: "file.php", ifModified: true, success: function(data, status){ if(status!="notmodified") { $("#display").append(data); } } });
// jQuery va schimba adresa URL ca sa contina &jsonp=jsonpmethod $.ajax({ dataType: 'jsnp', data: 'id=10', jsonp: 'jsnp', url: "file.php", });
$.ajax({ url: "file.php", usernume: 'nume', password: 'parola', success: function(raspuns){ $("#display").html(raspuns); } });
// trimite un document XML la server var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: function(raspuns){ $("#display").html(raspuns); } });
$.ajax({ type: "GET", url: "file.php", scriptCharset: "utf-8", contentType: "application/x-www-form-urlenecodd; charset=UTF-8", data: "id=12&nume=un_nume", success: function(raspuns){ $("#idd").html(raspuns); } });
// alert cand raspunsul are codul HTML 404 $.ajax({ url: "file.php", statusecod: { 404: function() { alert('pagina nu e gasita'); } } });
$.ajax({ url: "file.php", data: 'id=un_id', success: function(raspuns, status, xhr){ if(status=="success") { $("#display").html(raspuns); } else { alert(status+ ' - '+ xhr.status); } } });
// asteapta raspunsul maxim 3000 milisecunde $.ajax({ url: "file.php", timeout: 3000, success: function(){ $("#response").text('Success'); } });
$.ajax({ type: "POST", url: "file.php", data: 'nume=un_nume&pass=parola', success: function(raspuns){ $("#idd").text(raspuns); } });
$.ajax({ url: "file.php", success: function(raspuns){ $("#idd").text(raspuns); } });
<?php // defineste un Array cu adrese pt diferite cursuri $crs = array( 'altu'=>'', 'php-mysql'=>'php-mysql', 'javascript'=>'javascript', 'actionscript'=>'flash/actionscript-3_e', 'jquery'=>'javascript/curs-jquery-tutoriale-js' ); // verifica daca sunt date trimise prin POST, cu iindice "nm", "cs", si "cmt" if(isset($_POST['nm']) && isset($_POST['cs']) && isset($_POST['cmt'])) { $_POST = array_map("strip_tags", $_POST); // sterge posibile tag-uri din POST // preia datele $nm = $_POST['nm']; $cs = $_POST['cs']; $cmt = $_POST['cmt']; // defineste o variabila ce va contine raspunsul returnat de script $rehtml = '<h4>Hy '. $nm. '</h4> Link-ul pentru Curs <b>'. $cs. '</b>: <a href="https://marplo.net/'. $crs[$cs]. '">'. $cs. '</a><br />Comentariul dv.: <i>'. $cmt. '</i>'; } else $rehtml = 'Date nevalide'; echo $rehtml; // returneaza raspunsul ?>
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>jQuery Ajax - PHP</title> <script type="text/javascript" src="jquery_1.6.1.js"></script> <script type="text/javascript"><!-- $(document).ready(function() { // cand formularul "#crs" e trimis $('#crs').submit(function() { // preia datele din formular var nm = $('#crs #nm').val(); var cs = $('#crs #cs').val(); var cmt = $('#crs #cmt').val(); // pune date din formular in format JSON, care va fi trimis la server var data_json = {'nm':nm, 'cs':cs, 'cmt':cmt}; // seteaza functia ajax() sa trimita datele prin POST la "script.php" // daca apare vreo eroare, afiseaza o fereastra Alert cu starea cererii (xhr.status) si eroarea // la "success", plaseaza raspunsul intr-un element HTML cu id="resp" $.ajax({ type: 'post', url: 'script.php', data: data_json, beforeSend: function() { // inainte sa trimita cererea, afiseaza o notificare de "Incarcare..." messaj in locul unde va fi adaugat raspunsul $('#resp').html('Incarcare...'); }, timeout: 10000, // seteaza timpul de expirare (10 secunde) error: function(xhr, status, error) { alert('Eroare: '+ xhr.status+ ' - '+ error); }, success: function(raspuns) { $('#resp').html(raspuns); } }); return false; // necesar ca sa nu deschida pagina cu adresa din formular cand e trimis }); }); --></script> </head> <body> <div id="resp"></div> <h4>Completati formularul:</h4> <form action="script.php" method="post" id="crs"> Nume: <input type="text" name="nm" id="nm" /><br /> Curs: <select name="cs" id="cs"> <option value="altu">Altu</option> <option value="php-mysql">PHP-MySQL</option> <option value="javascript">JavaScript</option> <option value="actionscript">ActionScript</option> <option value="jquery">jQuery</option> </select><br /> Comentarii:<br /> <textarea name="cmt" id="cmt" cols="20" rows="3"></textarea> <input type="submit" value="Trimite" /> </form> </body> </html>Demo:
<p>Adresa: <strong>http://CoursesWeb.net/</strong> - Tutoriale.</p>
#id { font-weight: 800; }
function someFunction() { alert("CoursesWeb.net"); } setInterval("someFunction()", 2000);
$vname = 8; echo $vname;
We have traveled in space. - Noi am calatorit (deja) in spatiu.
La niña pintaba un arco iris. - Fetita picta un curcubeu.