I have PHP file named "content.php" prepared for both kind of requests, just as an example:
<?php
// Id params passed via GET method
$get = $_GET['param'];
switch ($get) {
case "param_value":
?>
<div data-param="<?php echo $get; ?>">
// My HTML content here
</div>
<?php
break;
case default:
break;
}
// Id params passed via POST method
$post = $_POST['param'];
if ($post != "") {
$data['output'] = '
<div data-param="<?php echo $get; ?>">
// My HTML content here
</div>
';
echo json_encode($data);
}
?>
And than I have Javascript file, from which I am making an AJAX call to PHP:
var oWrapper = jQuery("#wrapper"),
// Loading HTML via jQuery.load() function
sParams = jQuery.param({ param: "value" });
oWrapper.load("/content.php?" + sParams, function () {
console.log("content loaded via load()");
});
// Loading HTML via jQuery.ajax() function
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/content.php",
cache: false,
data: { "param": "value" },
success: function (data) {
oWrapper.html(data.output);
console.log("content loaded via ajax()");
}
});
Which way is faster?
Besides the speed of requests and returns, I wish to know which way is better for security of the app?!
.loadis just shorthand for$.ajax(and$(element).html(data)), there's no other difference. You can also use$.post('/content.php', { "param": "value" }, function(){}, 'json');or$.getJSON("/content.php?" + sParams, function(){});which are also just shorthand for$.ajax.