Search code examples
phpjqueryajaxpostresponse

jQuery Ajax replaces the div by whole .php page


I'm using jQuery Ajax function for populating my select box. Here is the code:

    $(function(){             
        $("#maker").change(function(){            
        var selected_value = $("#maker").val();      

        $.ajax({
            type: "POST",
            url: "search.php",
            data: ({_maker: selected_value}),
            success: function(response){
                $("#models").html(response);
            }
        });        
        });
    });

The problem is this replaces the div "models" by whole search.php page!!! I only want to populate the option values within "models".

Here is the HTML:

<div id="models">
<select id="model" name="model" style="width:170px">
<option value="Any">Any</option>
<?php
    foreach($current_models as $model) {
?>
    <option value="<?php echo $model; ?>"><?php echo $model; ?></option>

<?php
    }
?>
</select></div>

Any help is appreciated. Thanks in advance.


Solution

  • So it looks like you're returning the entire HTML page, and not searching through it to find the specific part of the page. Try something like this:

    $(function(){             
        $("#maker").change(function(){            
        var selected_value = $("#maker").val();      
    
            $.ajax({
                type: "POST",
                dataType: "html",
                url: "search.php",
                data: ({_maker: selected_value}),
                success: function(response){
                    $("#models").html($(response).find('#someDiv').html());
                }
                error: function(){
                      $("#models").html('Uh oh! Something went wrong and we weren't able to process your request correctly.');
                }
            });        
        });
    });
    

    You'll notice 2 things:

    1. I specified a dataType property. This tell jQuery what to expect. Additionally the html data type, tells jQuery to execute any JavaScript on the loaded page before rendering the page into the response object.

    2. I'm creating a jQuery object using the response, and then using jQuery's .find() method to get the inner HTML of a specific div in the response.

    Here is an example JS Fiddle, with some slight modifications for proof of concept: http://jsfiddle.net/rvk44/1/

    I also just wanted to note that you may want to add an error property so that if the page ever comes back as an error, the user knows that and isn't just sitting there staring at a blank screen expecting something to happen. (I've added a basic error message in the example, see the jQuery docs for further info on what the error property is returned).