MartynW MartynW - 1 year ago 124
PHP Question

Sending hidden value of html5 datalist to database

I'm relatively new to html5 and I'm trying to put together a webpage using a datalist object. I populate my datalists from a database, an example is shown below:

What I want to achieve is for the user to see the list of dates in the dropdown box and when they click a button to post the associated data-value number to a database (this is a primary key). The question is how do I get hold of the data-value to use in php to send to a database (I can get hold of the value in javascript but I don't want to use javascript to connect to the database as I'm told this is not good practice). Thanks very much in advance. Martyn

<input type="text" list="eventList" autocomplete="off" id="searchEvents" name="searchEvents">
<datalist id="eventList">
<option data-value="1" value="2016-06-02">2016-06-02</option>
<option data-value="2" value="2016-06-09">2016-06-09</option>

Answer Source

You shouldn't get your Primary Key from user submitted data. Better to calculate or auto generate that on the server-side based on the user-provided data.

Anyway, you can add hidden fields in your form using something like this:

<input type="hidden" name="hiddenvar" value="some secret" />

You would put this in an HTML Form. You can have JavaScript insert that element into the form when the user selects an option from the dropdown.

The form's submitted data goes to the script/url provided in the action attribute of the form. On the server side, PHP gets the data in the var $_POST.

Edit based on OP's comment:

You will still need to add the hidden element as above but you can do it with an element like this:

<input type="hidden" name="searchEventsID" value="" />

Leave it empty first and then have JS set the value to the corresponding data-value attribute.

Note that both examples are for a hidden element so the user won't see it. But it will be submitted to the server when the user submits it.

Edit 2:

Set the onchange attribute of the select <input> tag to a JS function which will do the necessary. See the links above on how to do that. And maybe google for some tutorials. This SO answer has a similar "structure" but you'll need to figure out what you need to do. Specifically,

var hidden_val = document.getElementById('eventList').getAttribute('data-value');
document.getElementById('searchEventsID').value = hidden_val;
// done in two lines for clarity but you can do it in one.