Reputation: 51
So basically what I want is when you click on a link, the $limit variable in my MySQL Query should be increased by 10 without refreshing the page. I know there are many similar questions, but I just couldn't work it out.
<?php
$limit = 10;
mysql_connect("localhost", "root", "");
mysql_select_db("database");
$query = mysql_query("SELECT * FROM news ORDER BY news_id DESC LIMIT $limit");
?>
<a href="#" id="more">Show more...</a>
$('#more').click(function(){
//Now here some jQuery / AJAX that changes the PHP $limit variable?
});
Is this possible in any way? I know that Javascript is on the client and PHP on the server side and my MySQL is up to date so the variable inside the query works. The title could've been 'How the change a PHP variable with jQuery' aswell, but if that's not possible I really need another solution to dynamically change the query (maybe even with refreshing).
Thanks :)
Upvotes: 0
Views: 1829
Reputation: 51
I finally fixed it, Thanks for the help guys! :)
<?php
$limit = $_POST['limit'];
include('/connect_db.php');
$sql = "SELECT * FROM news ORDER BY news_id DESC LIMIT $limit";
$sth = $dbh->prepare($sql);
$sth->execute();
?>
<a href="#" id="more">Show more...</a>
var limit = 10;
$('#more').click(function() {
limit += 10;
ajax();
});
var news = document.getElementById('news');
function ajax() {
$.ajax({
url: 'index.php',
type: "POST",
data: {limit: limit},
success: function(data){
news.innerHTML = data;
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}
ajax();
Upvotes: 1
Reputation: 11233
You have a lot to learn mate!
First look into AJAX (including jQuery if you don't know already). With both you can do "dynamical" calls / updating to content on a webpage (no refreshing). Second look into PHP 'mysql_real_escape_string' and PDO and understand what "SQL injections" are to better security your database and server.
Upvotes: 2
Reputation: 1565
You will need use ajax (and JSON for a good job), you have code examples here :
http://www.lennu.net/2012/06/25/jquery-ajax-example-with-json-response http://www.jquery4u.com/json/ajaxjquery-getjson-simple
Upvotes: 0