access html 5 data attribute in php

狂风中的少年 提交于 2019-12-02 05:44:55

问题


I have a form which includes

<input id="user-id" type="text" data-user-id="" name="message" placeholder="type and send..." class="form-control">

data-user-id HTML5 data attribute. When I submit the form, I want to use the value of data attribute in a php class. How to access this data attribute in php?


回答1:


Your user ID should be in a separate hidden field, such as:

<input type="hidden" name="user_id" value="123">
<input type="text" name="message" placeholder="type and send..." class="form-control">

Your message input shouldn't have an id of user-id and shouldn't need data-user-id at all.

Data attributes are used by JavaScript. Hidden inputs pass values to PHP that the user doesn't need to see. Neither are truly hidden to the user.




回答2:


If you are posting this form directly to a PHP script, you cannot access the data attributes. If you want to be able to do this you'd need to listen for the form submission in Javascript, then on submit grab the data you need and post it to the PHP script to handle it.

Here is some example code (untested!), using jQuery.

$('#form_name').on('submit',function(){

   var user_id = $('#user-id').attr('data-user-id');

   $.post('form_handle.php',{'user_id':user_id,[...],[...]});

});

Where [...] is any other form data to be posted to the handler. The handler can then retrieve posted values in the normal way, e.g. $_POST['user_id'].



来源:https://stackoverflow.com/questions/32286184/access-html-5-data-attribute-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!