access html 5 data attribute in php

后端 未结 2 357
轻奢々
轻奢々 2021-01-22 06:28

I have a form which includes



        
相关标签:
2条回答
  • 2021-01-22 07:17

    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'].

    0 讨论(0)
  • 2021-01-22 07:21

    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.

    0 讨论(0)
提交回复
热议问题