Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Excuse me, I try to catch my guest and save it using javascript ajax post..

It is different host (between the js and php server). This is the javascript:

<script language="Javascript" src="http://www.codehelper.io/api/ips/?js"></script>
<script language="Javascript">
    var myip = codehelper_ip.IP;
    var mycountry = codehelper_ip.Country;
    var myurl = document.URL;
    $.ajax({
        type: 'POST',
        url: 'http://myhost.com/guest-catcher/guest-post.php',
        crossDomain: true,
        data: '{"ip":"'+myip+'", "country":"'+mycountry+'", "page":"'+myurl+'"}',
        dataType: 'json',
        success: function(responseData, textStatus, jqXHR) {
            alert("success");
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
</script> 

And the server side code:

<?php

$ip = "";
if ($_POST['ip']) {
    $ip = $_POST['ip'];
}
$country = "";
if ($_POST['country']) {
    $country = $_POST['country'];
}
$page = "";
if ($_POST['page']) {
    $page = $_POST['page'];
}

//Start Save DB
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
$sql = "INSERT INTO blog_guest (ip_address, country, page) VALUES ('" . $ip . "', '" . $country . "','" . $page . "')";
if ($ip != "" || $country != "" || $page!= "") {
    if ($conn->query($sql) === TRUE) {
    } else {
        echo '<script>alert("' . $conn->error . '")</script>';
    }
}
$conn->close();
//End Save DB

Error at Browser console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at myhost.com/guest-catcher/guest-post.php. This can be fixed by moving the resource to the same domain or enabling CORS.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your data option is wrong. It should be a Javascript object, not a JSON string.

data: {"ip": myip, "country": mycountry, "page": myurl},

Also, your server script doesn't return JSON, so you should not have:

dataType: 'json',

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...