简体   繁体   中英

JQuery Ajax Json Response Does not Work

Form part :

<script type="text/javascript" src="js/aboneol.js"></script>
                    <h4>haberdar olun</h4>
                    <div class="news_letter">
                        <span id="aboneolhata"></span>
                        <form action="" method="post" onsubmit="return false;" id="abone">
                            <input type="text" name="email" placeholder="E-posta adresiniz" />
                            <input type="submit" onclick="$.aboneol();" value="abone ol" />

                        </form>
                    </div>

Jquery part :

$.aboneol = function(){
    var deger = $("form#abone").serialize();
    $.ajax({
        url: "aboneol.php",
        data: deger,
        dataType: "json",
        type: "post",
        success: function(response){
            if(response.error == 0){
                $(".news_letter").html(response.message);
            }else{
                $("#aboneolhata").html(response.message);
            }
        }
    });
}

And here is php part :

<?php
$email = $_POST["email"];
$email = trim($email);

if(empty($email)){
    $response["error"] = 1;
    $response["message"] = "Boş Bırakamazsınız..";
}else if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
    $response["error"] = 1;
    $response["message"] = "Hatalı E-posta..";
}else{
    require "database.php";
    $pdo = Database::connect();
    $sql = "INSERT INTO aboneler (email) VALUES (:email)";
    $q = $pdo->prepare($sql);
    $q->execute(array(
                ':email'=>$email,
                ));
    $response["error"] = 0;
    $response["message"] = $email;
}
echo json_encode($response);
?>

Ajax sends the email to php, and http response code is 200. But success method does not work. Also i cant see any json response in success method. How to solve this problem?

You should set the response content-type to application/json . if you didn't set it, you can when receive the response, make json object (or dictionary) from it.

So:

1 - set php response header:

header("Content-type: application/json");

2 - or if you don't set header in php, parse response in javascript:

success: function(response){
        response = JSON.parse(response);
        if(!response['error']){
        ...

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