-1

I was wondering whether it is possible in JavaScript (preferably jQuery) to pull data from a database using MySQL after clicking on a button? I currently pull data when the page loads, but I don't want to load 100's of items at the beginning as I want to be able to pull certain rows with different buttons?

Michael Jarvis
  • 1,115
  • 3
  • 10
  • 17
  • Is it possible to get specific rows with AJAX, or does it just pull the table? – Michael Jarvis Jan 21 '15 at 14:54
  • 1
    Not without server-side code, no. – Blazemonger Jan 21 '15 at 14:54
  • You can if you use a server side language like PHP between your javascript and MySQL database. But you already have that I guess as you state you are able to show data on page load. So yea I guess -> AJAX – Nathan Q Jan 21 '15 at 14:55
  • 1
    Yes, it is possible. You'd either post some form which would return the updated page (a page reload) or you'd request the data in the background from client-side code and add it to the page (AJAX). As it stands this question is a bit broad. We'll be happy to help with any problems you encounter while developing this, but "is it possible" questions are generally either answered with simply a "yes" or "no". – David Jan 21 '15 at 14:55
  • I don't want the page to reload after pulling from the database, so AJAX is the best option? Martijn below suggested `$.get()` – Michael Jarvis Jan 21 '15 at 14:58
  • `$.get()` is a jQuery AJAX function. – j08691 Jan 21 '15 at 14:58
  • @j08691 I'd prefer using `$.get()` as it seems consistent with my `$.post()` method. Is there a difference performance-wise? Sorry for the noobish questions – Michael Jarvis Jan 21 '15 at 15:01
  • Made an edit with some documentation when to get/post. Simply punt: Will calling the url with parameters *change* your database? In case it just gets content, use GET. Does it delete/insert/update? Then POST. – Martijn Jan 21 '15 at 15:07

1 Answers1

1
<button class="AjaxTrigger" data-example="abc">I do ABC </button>

$('.AjaxTrigger').on('click', function(){
    $.get("your-file.php", {example: $(this).data('example')}, function(result){
        alert( "This is what php gave me: " + "\n" +result );
    }
});

And now you let your-file.php do whatever you want, just like you normaly program you php files. Echo the outcome, and in javascript you will get exactly that in the returnfunction (which now alerts your result).

And if you feel like upping your game:

Community
  • 1
  • 1
Martijn
  • 15,791
  • 4
  • 36
  • 68