php send ajax request code example
Example 1: how to send data using ajax in php
$.ajax({
url: "/something", // the url we want to send and get data from
type: "GET", // type of the data we send (POST/GET)
data: {p1: "This is our data"}, // the data we want to send
success: function(data){ // when successfully sent data and returned
// do something with the returned data
console.log(data);
}
}).done(function(){
// this part will run when we send and return successfully
console.log("Success.");
}).fail(function(){
// this part will run when an error occurres
console.log("An error has occurred.");
}).always(function(){
// this part will always run no matter what
console.log("Complete.");
});
Example 2: ajax to php call
//Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
//On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
//OR LEARN SOMTHING NEW https://api-tools.getlaminas.org/