简体   繁体   中英

JavaScript/PHP: Get referral key URL

I'm working on an ajax (native JavaScript) form. I'm having trouble getting the referral key and sending it to the PHP back-end.

The idea is that the ajax request sends the entire URL (with the form data) as string to the PHP engine. I can then break down the URL in the PHP and extract the key.

Here is what I have so far:

Page url:

http://example.com?ref=gr84r34ijg98g

JS:

// Send the form data with the URL
function getquerystring() {

    var email = document.getElementById('email').value;
    var URL = document.URL;
    qstr    = 'email=' + email + '& URL=' + URL;
    return qstr;
}

Then, in my PHP, I can retrieve the form data and url:

   $email = $_POST['email'];
   $url   = $_POST['URL'];

How can I then break-down the URL, so as I only have the code at end as string? I was thinking I could break-down the URL in JavaScript before sending it, although I thought it might be easier to do that part with PHP.

Something like a preg_match() that removes " http://example.com?ref= " would probably do. Although not really sure how to do that.

Yes, you can get the value of ref in Javascript

function getquerystring() {
    var email = document.getElementById('email').value;
    var URL = document.URL;

    var URL_arr = URL.split('ref='); //<-- URL_arr[1] will give ref string

    qstr    = 'email=' + email + '&URL=' + URL;
    return qstr;
}
function getquerystring() {

    var email = document.getElementById('email').value;
    var URL = document.URL;
    qstr    = '?email=' + email + '& URL=' + URL;
    return qstr;
}

try this.

$email = $_GET['email']; $url = $_GET['URL'];

There is an extra space before URL .. and you should encode it with encodeURIComponent. Update this line

qstr    = 'email=' + encodeURIComponent(email) + '&URL=' + encodeURIComponent(URL);

And on php side

$url = url_decode($_POST['URL']);
$email = url_decode($_POST['email']);

Try this:

var query = window.location.search.substring(1).split('&');
var ref = '';
$.each(query, function(i, v) {
    v = v.split('=');
    if (v[0] === 'ref') {
        ref = v[1];
        return false;
    }
});
console.log(ref);

Why don't you just do the following in PHP (place it in either a header (if you want it to work on all pages) or at the top of index.php after all your includes :

<?php
$ref = (isset($_GET['ref']) && strlen($_GET['ref']) > 0) ? trim($_GET['ref']) : null;
//Process what ever you wanted to process from the beginning if you had a referral code
if(!is_null($ref)) {
   // do your action
}
?>

Using the above you don't really need any kind of javascript.

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