Julio
Julio

Reputation: 483

Use form select value in PHP function

I understand PHP is server side, and Javascript is client side.

I am trying to update a table on the screen (without causing a reload) on a changed selected value in a dropdown using form select:

            <form method="post" action="search.php" role="form">
                <div class="form-group">
                  <select name="minPrice" class="form-control" style="height:50px;" id="minPrice">
                    <option value="0">Min Price</option>
                    <option value="10000">$10,000+</option>
                    <option value="20000">$20,000+</option>
                    <option value="30000">$30,000+</option>
                    <option value="40000">$40,000+</option>
                    <option value="50000">$50,000+</option>
                    <option value="60000">$60,000+</option>
                    <option value="70000">$70,000+</option>
                    <option value="80000">$80,000+</option>
                    <option value="90000">$90,000+</option>
                    <option value="100000">$100,000+</option>
                  </select>
                </div>
            </form>

In order to update the screen, I must access a 3rd party API in PHP.

I am using the following function in Javascript in order to update the search results when the user selects a different value in the dropdown.

$("#minPrice").on("change", function(){
    updateSearchResults(this);
});

However, I cannot access the selected option value when I make a call to PHP.

So my question is:

Is there a way to access the selected option value when I make the PHP call to the server WITHOUT reloading the current page?

Upvotes: 1

Views: 399

Answers (1)

schellingerht
schellingerht

Reputation: 5796

Do an ajax post with your changed selected value:

$("#minPrice").on("change", function() {
   updateSearchResults(this);
});

function updateSearchResults(minPrice) {
    $.ajax({
        type: 'POST',
        url: 'urlToYourPhp',
        data: 'minPrice=' + minPrice.val(),
        success: function(response) {
            console.log(response);
            // Handle the response from your php without the need to reload
        },
        dataType: 'html' // or: 'json' if your API returns json
    });
}

Upvotes: 2

Related Questions