Skip to content

Instantly share code, notes, and snippets.

@tedshd
Last active August 29, 2015 14:13
Show Gist options
  • Save tedshd/fd1571a020d533fdd35a to your computer and use it in GitHub Desktop.
Save tedshd/fd1571a020d533fdd35a to your computer and use it in GitHub Desktop.
Ajax method with javascript
/*global $, jQuery, alert, console, angular*/
/**
*
* @authors Ted Shiu ([email protected])
* @date 2015-01-09 01:23:09
* @version $Id$
*/
/**
* [Ajax basic]
*
*/
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.html', true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('myDiv').innerHTML = xhr.responseText;
}
};
/**
* [Ajax formdata]
*/
var formData = new FormData();
formData.append('str', 'string');
formData.append('num', 123);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('myDiv').innerHTML = xhr.responseText;
}
};
xhr.send(formData);
/**
* [Ajax form with application/x-www-form-urlencoded]
*
*/
var obj = {
'user': 'ted',
'password': '123456'
},
jsonData;
jsonData = JSON.stringify(obj);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('myDiv').innerHTML = xhr.responseText;
}
};
xhr.send('json=' + jsonData);
/**
* [Ajax payload]
*
*/
var obj = {
'user': 'ted_shiu',
'password': '123456'
},
jsonData;
jsonData = JSON.stringify(obj);
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'rest.php', true);
xhr.onreadystatechange = function(e) {
if (xhr.status == 200) {
document.getElementById('info').innerHTML = xhr.responseText;
}
};
xhr.send(jsonData);
<?php
/**
*
* @authors Your Name ([email protected])
* @date 2015-01-13 23:39:47
* @version $Id$
*/
$request = file_get_contents("php://input");
$method = $_SERVER['REQUEST_METHOD'];
print_r($method);
switch($method)
{
case "PUT":
print_r(json_decode($request, true));
break;
case "GET":
print_r(json_decode($request, true));
break;
case "DELETE":
print_r(json_decode($request, true));
break;
case "POST":
print_r(json_decode($request, true));
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment