Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post Method to URL from a onclick function

I need help on something that sounds easy but is difficult for me. So when someone clicks on this div:

<div onclick="<go to url sending data using the post method>">Click Me</div>

I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.

like image 706
Techwizmatt Avatar asked Feb 19 '16 15:02

Techwizmatt


2 Answers

If you need to use div you can do it like this but I suggest that you use button or input of type submit.

<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>

Also you may use jQuery or some other JS library.

NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.

like image 151
Samuil Banti Avatar answered Oct 06 '22 01:10

Samuil Banti


Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.

//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input id="someInput">
<div onclick="sendData()">Click Me</div>

<script>
    function sendData(){
        //get the input value
        $someInput = $('#someInput').val();
        $.ajax({
            //the url to send the data to
            url: "ajax/url.ajax.php",
            //the data to send to
            data: {someInput : $someInput},
            //type. for eg: GET, POST
            type: "POST",
            //datatype expected to get in reply form server
            dataType: "json",
            //on success
            success: function(data){
                //do something after something is recieved from php
            },
            //on error
            error: function(){
                //bad request
            }
        });
    }

</script>
like image 36
m1alesis Avatar answered Oct 06 '22 01:10

m1alesis