简体   繁体   中英

Form Cross domain POST request using PHP

I am trying to send data from a form to a php file so I can store it in a database, but its not working...

The code for the form is not on the same server as the php file, because the form will be on a mobile app.

html

<div data-role="page" id="createclub">

<div data-role="content">
    <form id="cname" align="left" action="post">
        <label for="name">Enter Name:</label>
        <input type="text" id="name" value=""  />
        <input type="submit" value="Submit" data-inline="true">
    </form>

    <div id="result"></div>
</div>

    <script type="text/javascript">
       $(document).ready(function(){
        $("#cname").submit( function () {
        $.post(
        'http://www.clubbedin.isadcharity.org/createclub.php',
        $("#cname").serialize(),
        function(data){
        $("#result").html(data);
        alert("Data " + data);
        }
        );
        return false;
        });
        });
    </script>

php file

$name = $_POST['name'];

THANK YOU!!!

Add this at the beginning of your PHP file:

header("access-control-allow-origin: *");

More info on cross domain policy here .

I think you need to prevent the default function of the submit button using .preventDefault() because as I look on your code you want to submit your form using ajax

 $("#cname").submit(function (e) {
    e.preventDefault();
    $.ajax({
        url: 'http://www.clubbedin.isadcharity.org/createclub.php',
        crossDomain: true, //set as a cross domain requests
        type: 'post',
        data: $("#cname").serialize(),
        success: function (data) {
            $("#result").html(data);
            alert("Data " + data);
        },
    });
});

and please use .ajax() so that you can set your ajax request to a cross-domain request

http://api.jquery.com/jQuery.ajax/

Your input element <input type="text" id="name" value="" /> must set up the name attribute as name="name" .

form #cname after edited

<form id="cname" align="left" action="post">
    <label for="name">Enter Name:</label>
    <input type="text" id="name" name="name" value=""  />
    <input type="submit" value="Submit" data-inline="true">
</form>  

You can gather more informations from the jQuery API Documention:
http://api.jquery.com/
http://api.jquery.com/serialize/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM