Monday 15 April 2013

php - Pulling data from SQL database depending on form input -


I am working on a form where changing a "selective" element will mean the values ​​of the second "selection" element The change occurs because the values ​​of both elements come from the MSSQL database.

There are two ways that I can think of doing this.

  1. Store the table in one, modify the javascript variable and the changing element of the first element to the second element.

  2. Send a GET request to the page and modify it to reload it using PHP. / P>

    I do not like the first method because storing databases from PHP side on behalf of JavaScript is one way to hack and is really cumbersome. I do not like the other way too, because reloading the page hinders user experience and has to scroll again.

    You must use AJAX to drag data and another selection Elements should be populated In short, AJAX is simply a separate page request behind the scenes, you can use it to make a simple HTML page or partial load and display it in a DOM element, or You use it to dynamically retrieve the structural data You can.

    The best way to do this is to make JSON object notation) In this situation, you will use javascript to make an AJAX call on a PHP page, and that PHP page will take an argument in the query string which The selection represents the value of the element. With it, you will call your MSSQL database, so that you can get all the related options for the second selection, and then echo them. In turn, AJAX can parse the JavaScript response using the request and it can be javascript Can be interpreted as an object, allowing you to loop through the result and what you want to do with them.

    Here's an example (I'm using jQuery because it makes AJAX really easy)

    At the top of your form page:

      $ (document) .ready (function () {$ ('# Select1'). Changes (function () {var Select1val = $ (this) .val (); $ .getJSON ('/ path / to / response.php', 'select1 =' + select1val, function {$ ('# select2') empty (); if (Response to var option) {$ ('& lt; option / & gt;') Val (option.value) .html Option.label) .appendTo ($ ('# select2')) ;}}});});});   

    Then your response.php page should look like this:

         

No comments:

Post a Comment