1//Change the text of a <div> element using an AJAX //request:
2//using JQuery
3
4
5$("button").click(function(){
6 $.ajax({url: "demo_test.txt", success: function(result){
7 $("#div1").html(result);
8 }});
9});
10
11
12
13//To send a request to a server, we use the open() //and send() methods of the XMLHttpRequest object:
14// Javascript
15
16
17xhttp.open("GET", "ajax_info.txt", true);
18xhttp.send();
19
20//example below
21<html>
22<body>
23
24<h1>The XMLHttpRequest Object</h1>
25
26<button type="button" onclick="loadDoc()">Request data</button>
27
28<p id="demo"></p>
29
30
31<script>
32function loadDoc() {
33 var xhttp = new XMLHttpRequest();
34 xhttp.onreadystatechange = function() {
35 if (this.readyState == 4 && this.status == 200) {
36 document.getElementById("demo").innerHTML = this.responseText;
37 }
38 };
39 xhttp.open("GET", "demo_get.asp", true);
40 xhttp.send();
41}
42</script>
43
44</body>
45</html>
1 $.ajax({
2
3 url : "file.php",
4 method : "POST",
5
6 data: {
7 //key : value
8 action : action ,
9 key_1 : value_key_1,
10 key_2 : value_key_2
11 }
12 })
13
14 .fail(function() { return false; })
15 // Appel OK
16 .done(function(data) {
17
18 console.log(data);
19
20 });
1// For a plain JS solution, use these functions:
2
3function _GET_REQUEST(url, response) {
4 var xhttp;
5 if (window.XMLHttpRequest) {
6 xhttp = new XMLHttpRequest();
7 } else {
8 xhttp = new ActiveXObject("Microsoft.XMLHTTP");
9 }
10
11 xhttp.onreadystatechange = function() {
12 if (this.readyState == 4 && this.status == 200) {
13 response(this.responseText);
14 }
15 };
16
17 xhttp.open("GET", url, true);
18 xhttp.send();
19}
20
21function _POST_REQUEST(url, params, response) {
22 var xhttp;
23 if (window.XMLHttpRequest) {
24 xhttp = new XMLHttpRequest();
25 } else {
26 xhttp = new ActiveXObject("Microsoft.XMLHTTP");
27 }
28
29 xhttp.onreadystatechange = function() {
30 if (this.readyState == 4 && this.status == 200) {
31 response(this.responseText);
32 }
33 };
34
35 xhttp.open("POST", url, true);
36 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
37 xhttp.send(params);
38}
39
40// and apply like this:
41_GET_REQUEST('http://someurl', (response) => {
42 // do something with variable response
43});
44_POST_REQUEST('http://someurl', 'paramx=y', (response) => {
45 // do something with variable response
46});