1$.ajax({
2 url: 'ajaxfile.php',
3 type: 'post',
4 data: {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'},
5 success: function(response){
6
7 }
8});
1function makeRequest (method, url, data) {
2 return new Promise(function (resolve, reject) {
3 var xhr = new XMLHttpRequest();
4 xhr.open(method, url);
5 xhr.onload = function () {
6 if (this.status >= 200 && this.status < 300) {
7 resolve(xhr.response);
8 } else {
9 reject({
10 status: this.status,
11 statusText: xhr.statusText
12 });
13 }
14 };
15 xhr.onerror = function () {
16 reject({
17 status: this.status,
18 statusText: xhr.statusText
19 });
20 };
21 if(method=="POST" && data){
22 xhr.send(data);
23 }else{
24 xhr.send();
25 }
26 });
27}
28
29//POST example
30var data={"person":"john","balance":1.23};
31makeRequest('POST', "https://www.codegrepper.com/endpoint.php?param1=yoyoma",data).then(function(data){
32 var results=JSON.parse(data);
33});
1function postAjax(url, data, success) { var params = typeof data == 'string' ? data : Object.keys(data).map( function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) } ).join('&');
2 var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.open('POST', url); xhr.onreadystatechange = function() { if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); } }; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(params); return xhr;}
3// example requestpostAjax('http://foo.bar/', 'p1=1&p2=Hello+World', function(data){ console.log(data); });
4// example request with data objectpostAjax('http://foo.bar/', { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });