Jackymamouth
Jackymamouth

Reputation: 149

reloading page with new function AJAX

i have a page that displays the latest images.
i am using an AJAX request to sort these images :

$('#trier').on('click', function() {        // When i click on button to validate Sort out
var b = document.getElementById('genre').value;  // parameter Sort out : genre 
$.post('index.php', {y: b}, function(data) {
location.reload(); // reload page with pictures sorted out
});
});

and this is what my function that sorts the images out looks like :

if(isset($_POST['y'])){              // if they is a sorting out request
function latest($n) {
$genre= $_POST['y'];
$dbCon = mysqli_connect("localhost", "artlibr1_default", "azerty123", "artlibr1_01");
$sql = "SELECT * FROM general WHERE genre='$genre' ORDER BY date_added DESC LIMIT $n, 1";
$query = mysqli_query($dbCon, $sql);
while ($list = mysqli_fetch_assoc($query)) {
 return $list['path'];
}
}}else{                             // default display 
function latest($n) {
$genre= $_POST['y'];
$dbCon = mysqli_connect("localhost", "artlibr1_default", "azerty123", "artlibr1_01");
$sql = "SELECT * FROM general ORDER BY date_added DESC LIMIT $n, 1";
$query = mysqli_query($dbCon, $sql);
while ($list = mysqli_fetch_assoc($query)) {
 return $list['path'];
}
}

( only the sql statement changes)
So the problem is that i need the page to reload with the $_POST['y'] data; but at the moment the page is just reloading and doesn't have $_POST['y'] data.

Upvotes: 0

Views: 59

Answers (4)

Kelvin
Kelvin

Reputation: 690

Hmm, you don't use ajax correctly. Maybe you should edit your code

$('#trier').on('click', function() {        // When i click on button to validate Sort out
    var b = document.getElementById('genre').value;  // parameter Sort out : genre 
    $.post('index.php', {y: b}, function(data) {
        $('#div-need-load-image').html(data) // reload page with pictures sorted out
    });
});

Or if you want append image to div, you can try .append() instead of .html()

$('#div-need-load-image').append(data)

Upvotes: 1

Quentin
Quentin

Reputation: 943561

Your code:

  1. Makes an HTTP request from JavaScript
  2. Gets some data from a database with PHP
  3. Sends that data from PHP to the JavaScript
  4. The JavaScript ignores that data and reloads the page (with the original GET request)

If you want to reload the page. Don't use Ajax. The point of Ajax is that you make an HTTP request without reloading the page.

If you want to use the data you get back, then don't use location.reload, take the value of data and do something with it.

Upvotes: 3

Alain Nisam
Alain Nisam

Reputation: 680

Instead of using

location.reload();

you should use

location.href = %Construct the URL you want to reload%

Upvotes: 0

Mike Resoli
Mike Resoli

Reputation: 967

Instead of reloading the entire page you could clear the content of of #genre and replace it with the data returned from your ajax function.

Upvotes: 0

Related Questions