1

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?!

1
  • 2
    .load is 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. Commented Sep 28, 2011 at 18:45

2 Answers 2

5

Both ways do pretty much exactly the same thing.

Internally, $(selector).load() uses $.ajax() to get the data, then $(selector).html() to set the html of the selected element to the response of the $.ajax() call.

If you are loading html into an element, use $(selector).load() because it is more readable. One is just as secure and as fast as the other.

Note: Internally jQuery now uses $.parseHTML() rather than $(selector).html() to convert the string to html. This doesn't really change anything though.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't know the specifics but I dont't think there is a difference in security. load() and get() are "optimized" versions of ajax() so they will always be faster and better but I don't you or your visitors will ever feel the difference in a query like yours

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.