Home > Back-end >  HTTP response status is 200, but no response shows
HTTP response status is 200, but no response shows

Time:01-25

I have this simple code to fetch a list of values from my sql table and show them in my <select> dropdown.

My html:

<select  id="sel1" name="sel1" style="width: 7em;"></select>

My Javascript:

const from = document.getElementById("sel1");
from.addEventListener("click",function(){
  let $select = $("#sel1");
  $.ajax({
    url: '/paydetails_server.php',
    type: 'POST',
    data: { "input": "from_periods" }, 
    dataType: 'json',
    cache:false, 
    success: function(response) {
      //console.log(response);
      response.sort();
      let selectedValue = $select.val();
      let html = response.filter((e, i, a) => a.indexOf(e) === i).map(item => `<option value="${item}">${item}</option>`);
      $select.html(html).val(selectedValue);
    },
    complete: function() {}
  });
})

My PHP:

if(isset($_POST["input"])){
   if(!$connection)
      echo "Connection to database failed! Please try again";
   else{
      $periods=array();
      $sql = "SELECT DISTINCT `YEARMM` from `emp_pp`";
      $result = $con->query($sql);
      if ($result->num_rows > 0) {
         while($row = $result->fetch_assoc()) {
            if((!str_contains($row["YEARMM"],"S"))&&(!str_contains($row["YEARMM"],"B")))
               array_push($periods,$row["YEARMM"]);
            }
            echo json_encode($periods);
         }
      }
 }

Now, when I execute the code in my localhost XAMPP server, it works perfectly. But surprisingly, it doesn't work in my live server. I've double checked everything including variables such as host, servername, database name, etc.

I've tried checking for errors in the Network tab, but all I get is response status 200. Even when I tried console.log(response) nothing shows in the console. Why is this same code working in local server and not in live? Please help me.

CodePudding user response:

For some reason, the statement if((!str_contains($row["YEARMM"],"S"))&&(!str_contains($row["YEARMM"],"B"))) was causing this problem, although, it was running fine in the localhost.

CodePudding user response:

Check what you get form database, str_contains only verify if result contains letter S or B

CodePudding user response:

When you tell jQuery to parse the data as JSON, it will run the success function only if:

  • It gets an OK response
  • It can parse the response body as JSON

In your PHP you have echo json_encode($periods) inside a while loop.

If there are more than one values that get looped over, then you have multiple JSON texts mashed together — which isn't valid JSON.

If there are zero entries that get looped over, then you have no JSON — which isn't valid JSON.

Move the echo json_encode($periods); statement so it is after the while loop.

  •  Tags:  
  • Related