I'm creating HTML with a loop that has a column for Action. That column is a Hyperlink that when the user clicks calls a JavaScript function and passes the parameters...
example:
<a href="#" OnClick="DoAction(1,'Jose');" > Click </a> <a href="#" OnClick="DoAction(2,'Juan');" > Click </a> <a href="#" OnClick="DoAction(3,'Pedro');" > Click </a> ... <a href="#" OnClick="DoAction(n,'xxx');" > Click </a>
I want that function to call an Ajax jQuery function with the correct parameters.
Any help?
If you want to pass more than one parameter to the URL,use data as data:{id:'123' , name:"MyName"} where the 123 is the value of the parameter id myName is the value for the parameter name the value here can be string or variable having the value to be passed.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn.
Using POST
function DoAction( id, name ) { $.ajax({ type: "POST", url: "someurl.php", data: "id=" + id + "&name=" + name, success: function(msg){ alert( "Data Saved: " + msg ); } }); }
Using GET
function DoAction( id, name ) { $.ajax({ type: "GET", url: "someurl.php", data: "id=" + id + "&name=" + name, success: function(msg){ alert( "Data Saved: " + msg ); } }); }
EDIT:
A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.
<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a> <a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a> <a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a> ... <a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a> <script type="text/javascript"> $(function() { $('.ajax-link').click( function() { $.get( $(this).attr('href'), function(msg) { alert( "Data Saved: " + msg ); }); return false; // don't follow the link! }); }); </script>
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false
like this:
function DoAction(id, name) { // your code return false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With