Sylph
Sylph

Reputation: 1495

Jquery load dymanic content with parameter

I'm trying to load div content based on the a href being clicked and pass in a parameter. For example, Link 1 Clicking on Link 1 will pass value "3" to process.php, and return back the value "apple is good for you".

However, I can't seem to be able to pass the value without having a submit button. Anyway I can pass the parameter to another php file to process, and return the value?

$(document).ready(function(){
     $("#testing a").live("click", function(evt){
         var id= $(this).attr('id');
        $.post("process.php", { id: id },
        function(data) {
          alert(data);
                    $('#result').load(data);
        });
     })

});

Below is my HTML

<div id="testing">
<a href="" id="11"> hello </a>
</div>

<div id="result"></div>

Appreciate your help, thanks a lot!

Upvotes: 1

Views: 642

Answers (1)

Sampson
Sampson

Reputation: 268482

You shouldn't be using numbers for id values. Instead, prefix them with a letter, or consider adding them to a data- atribute on the element.

Additionally, $.live() is deprecated, and we are encouraged to use $.on() from here on out for event delegation. I've gone ahead and handled this in the code below, but the id issue remains.

Lastly, $.load() and $.html() aren't the same. If you want to load data into an element, you don't call the load method (though the name could lead to that confusion).

// Short-hand version of $(document).ready();
$(function(){
  // Handle anchor clicks on #testing
  $("#testing").on("click", "a", function(e){
    // Prevent links from sending us away
    e.preventDefault();
    // POST our anchor ID to process.php, and handle the response
    $.post("process.php", { 'id': $(this).attr("id") }, function(data){
      // Set the response as the HTML content of #result
      $("#result").html(data);
    });
  });
});

From your process.php file, you might have something like the following:

$msg = array( 
    "...chirp chirp...",
    "This is response number 1",
    "And I am the second guy you'll see!",
    "Apples are good for you!" 
);

$num = $_POST["id"] || 0;

echo $msg[ $num ];

Upvotes: 3

Related Questions