简体   繁体   中英

Ajax/Jquery drop down menu, Javascript to get variable, variable is then used in PHP. Can't get it to work?

I am using Ajax/Jquery to display a dropdown menu with results from my SQL database. I'm using javascript to get a variable and then that variable is used within PHP. However it does not work.

I used Jquery .val() to get the variable from a select html tag when the user clicks the choices available.

Then, .on() to execute some php code depending on what the selected value from the dropdown box is.

My scenario is I have car classes (Sports, Hatchback) and cars available. What I am trying to do is, put the car classes in a dropdown box and then display the cars available dependent upon what the user has selected. I'm trying to do this using the above methods. (All this information is taken from a SQL database).

Has anyone got any solutions?

This is my my javascript code here:

<script>
var carid = $("#carid").val();

$("select[name='carid']").on("select",function(){$.post( "sDn.php", x, function( data ) {  $( ".availablecar" ).append( data );});});
</script>

It appears to me that you are not using the carid variable anywhere. I think you mean to use carid instead of x

<script>
var carid = $("#carid").val();

$("select[name='carid']").on("select",function(){$.post( "sDn.php", carid, function( data ) {  $( ".availablecar" ).append( data );});});
</script>

Also I would suggest parsing you form input if you don't already on the php side.

Try this:

$("#carid").on("change",function(e){
    e.preventDefault();

    var value = $(this).find("option:selected").val();

    var $avaliable = $( ".availablecar" );

    $.ajax({
        url:'sDn.php',
        type:'post',
        data:{
            'carid':value
        },
        dataType:'html',
        success:function(result){
            $avaliable.append( result );
        }
    });
});

Changed the $.post to $.ajax , passing the ' cardid ' value.

Getting the selected option, on ' change '.

You probably want something like this

JavaScript

$("select[name='carid']").on("change", function() {
  $.post(
    "sDn.php",
    { carId: $("#carid").val() },
    function(data) {
      $(".availablecar").append(data);
    }
  );
});

PHP

$carId = $_POST['carId'];

You need to send the car id in the request and you probably need to bind to the change event, not select

You also need to get the car id value when the id has been changed, otherwise it will always remain the same value and never get updated when you change it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM