twan twan - 3 months ago 27
Ajax Question

Posting variable to ajax script

I got a function which displays an amount of products depending on a value that is selected in a dropdownlist. This is done with ajax, but for everything to work correctly I need to pass a variable.

On my catalog.php I got:

$pid = $productcatcr[0]['id'];


Which contains the page id.

On the same page I got the dropdownlist:

<select class="form-control showcount" name="showcount" id="showcount">
<option value="100" selected>Alle</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="12">12</option>
<option value="16">16</option>
<option value="20">20</option>
</select>


Which works like this in ajax.js :

$("#showcount").on('change', function() {

$.post("ajax/getproducts.php", {start: ($("#showcount").val() - 4), end: $("#showcount").val()}, function(result){
$("#productviewajax").html(result);
});
});


Finally in getproducts.php I use the following query:

$product = "SELECT * FROM `web_content` WHERE `catid` = ".$conn->real_escape_string($_GET['id'])." AND state = 1 order by ordering LIMIT ".$_POST['end']."";


I need to post id from the initial page, through ajax to the query. What would be the best way to do this? My ajax is not very good.

I got another filter on the initial page on which I can just pass the variable in an url, but the other option element doesn't work like that.

Example:

<option value="highlow" data-post-url="prijshooglaag.php?id='.$pid.'">Prijs: Hoog naar laag</option>

Answer

Create one hidden input with class name as pageId (not mandatory with same class name, but if you are changing class name here. Change in Ajax code id:$(".pageId").val() here too. Both are related.)

catalog.php

<?php

$pid = $productcatcr[0]['id'];
?>

<input type='hidden' value='<?php echo $pid;?>' class='pageId'>

<select class="form-control showcount" name="showcount" id="showcount">
  <option value="100" selected>Alle</option>
  <option value="2">2</option>
  <option value="4">4</option>
  <option value="8">8</option>
  <option value="12">12</option>
  <option value="16">16</option>
  <option value="20">20</option>
</select>

Use pageId to get current page id. And, pass it to getproducts.php page.

Ajax

$("#showcount").on('change', function() {
    $.post("ajax/getproducts.php", {start: ($("#showcount").val() - 4), end: $("#showcount").val(),id:$(".pageId").val()}, function(result){
        $("#productviewajax").html(result);
    });
});

getproducts.php

Instead of $_GET['id'] use $_POST['id'] as $.post being used in AJAX.

$product = "SELECT * FROM `web_content` WHERE `catid` = ".$conn->real_escape_string($_POST['id'])." AND state = 1 order by ordering LIMIT ".$_POST['end']."";