简体   繁体   中英

AJAX return code 200 but fired error

HTML part:

<a href="javascript:void(0)" onclick="$.join_group(<?=$USER_ID?>, <?=$groups[$i]["id"]?>)"><?=$language["join"]?></a>

Js part :

  $.join_group = function(user_id, group_id) {
      var input = "user_id=" + user_id + "&group_id=" + group_id + "&mode=join_group";
      alert(input);
      $.ajax({
         url : "handlers/H_GroupHandler.php",
         data : input,
         type : "post",
         dataType : "json",
         success : function (response) {
             if (!response.error) {
                 alert("asds");
             } else {
                 alert("asds");
             }
         },
         error: function(jqXHR,error, errorThrown) {  
           if(jqXHR.status&&jqXHR.status==400){
                alert(jqXHR.responseText); 
           }else{
               alert(jqXHR.status);
               alert("Something went wrong");
           }
      }
      });
      return false;
  }

H_GroupHandler :

$mode = $_POST["mode"];
if ($mode == "join_group") {
        $user_id = $_POST["user_id"];
        $group_id = $_POST["group_id"];


        $response["error"] = true;
        $response["error_text"] = "Error !";
        echo json_encode($response);
}

Remote Address:[::1]:80 Request URL: http://localhost/xxx/handlers/H_GroupHandler.php Request Method:POST Status Code:200 OK

It returns 200 but ajax fired error function and occure something went wrong.

Form Data in browser :

user_id:1

group_id:6

mode:join_group

Your Ajax working fine but as seen you use dataType : "json" and your php file returning string that's why error block execute

adding header before echo your json will solve you problem

`header('Content-Type: application/json');`
echo json_encode($response);

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