开发者

Submit external form without leaving the page/site

I looked through the site for answers to this, but nothing's spot on to what I need (this is close, except it doesn't actually submit the form: Prevent form redirect OR refresh on submit?).

I'm trying to incorporate a mailing list sign-up (code borrowed from a sign-up page hosted on ReverbNation) to a website.

The form submits properly, but the signee is r开发者_如何学Pythonedirected to a hideously rendered page on ReverbNation's site. I cannot modify their script and don't think there's an API I can use to keep things tidy.

Is there a way I can submit the form in the background, without the user being redirected?


Here's an example in PHP for tunneling a POST.

//set POST variables
$url = 'http://domain.com/url-to-post-to';
$fields = array(
            // Add the fields you want to pass through
            // Remove stripslashes if get_magic_quotes_gpc() returns 0.
            'last_name'=>urlencode(stripslashes($_POST['last_name'])),
            'first_name'=>urlencode(stripslashes($_POST['first_name'])),
            'email'=>urlencode(stripslashes($_POST['email']))
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));

// returns the response as a string instead of printing it
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;


If you're posting to the same domain, you can use an AJAX post. However, it seems you're trying to POST to different domain, so the browser's same origin policy will prevent you from doing so (http://en.wikipedia.org/wiki/Same_origin_policy). (JSONP can get around this but it doesn't work for POST)

Another way to get around this is to have your server do the POST and tunnel the response back to your page.

<form id='yourForm' action="" onsubmit="javascript: doPostToTunnelPage(); return false;">
    <!-- inputs...-->
</form>

Make sure to return false, or your page will be redirected.


in my understand, you need send a form without redirect?

consider my example

$(function() {
    $('#myForm').submit(function (e) {
        e.preventDefault();

        $.ajax({ /* params to send the form */ });

        return false;
    });
});

IIT it will work just because of the e.preventDefault.

If this method is called, the default action of the event will not be triggered. 

See jQuery documentation here for more information.

Hope it help you

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜