AJAX works on localhost, but doesn't on live server

前端 未结 6 1243
滥情空心
滥情空心 2021-01-28 08:32

Below code works on localhost, but not on live server.

MAIN EDIT:

Only 1 thing remains which is not working:

<
相关标签:
6条回答
  • 2021-01-28 09:06

    From the code you posted, the comments below and the discussion ( actually was very helpful to jump to this conclusion ) .. i can point a couple of things, but first :

    adding error_reporting(0); in the begining of the controller right after <?php should solve your problem. ( if my guess is correct and it's just a notice, not an actual error)

    i'm guessing that you already have this in your localhost 's php.ini and on the live server you have the default error_reporting = E_ALL, due to two different installations of php.

    there's probably somewhere in the controller a notice of an undefined index or something, and php is trying to let you know by outputting this :

    <br />
    <b>Notice</b>:  Undefined index: ...
    {"calculated_score":10,"score_result":"1.75 pts"}
    

    it starts with a < and that's where this comes from

    SyntaxError: Unexpected token < in JSON at position 0 
    

    the $.ajax is unable to parse this because you have dataType="json" and this means that it is expecting a valid json back from the server, so you get the 200 status because the request was successful with no errors and console.log(data) will be empty because it was unable to parse it.

    a simple way to reproduce this is creating a test php file and send the request to it instead of controller.php like :

    <?php
        error_reporting(0); // try with and without this line.
    
        $data = [
            'city' => 'Montreal',
            'Country' => 'Canada'
        ];
    
        echo $_GET['something']; // this will trigger a notice of undefined index something
    
        echo json_encode($data);
    ?>
    

    you can remove dataType:"json" and put console.log(data) in the success function and look in the console to see what the server is really telling you.

    but here's something that bugs me ..

    var post = 'controller=QualityMonitoring&task=setScore&monitor_id='

    this looks like a query string you use for GET requests but you have type:"POST" in your ajax request ..

    i don't know how you're handling this in the controller but it should be type:"GET" to send data like this, but if you want to send the data with POST then var post should be an object, ( this could be the problem as it defaults to GET when not set and in the controller there's a $_GET['task'] instead of $_POST['task'] or vise-versa ) so here's a snippet to convert the query string to a json :

    function QueryStringToJSON(str) {
    	var pairs = str.split('&');
    	var result = {};
    	pairs.forEach(function (pair) {
    		pair = pair.split('=');
    		var name = pair[0]
    		var value = pair[1]
    		if (name.length)
    			if (result[name] !== undefined) {
    				if (!result[name].push) {
    					result[name] = [result[name]];
    				}
    				result[name].push(value || '');
    			} else {
    				result[name] = value || '';
    			}
    	});
    	return (result);
    }
    
    var string = 'controller=QualityMonitoring&task=setScore&monitor_id=5&q=blah&item_score=99&comment=hello';
    var obj = QueryStringToJSON(string);
    
    console.log(obj);

    i hope this helps or at least gives you an idea, and Good Luck.

    0 讨论(0)
  • 2021-01-28 09:10
    1. after function saveScore() add: var close = function() { $('#overlay').remove(); };

    2. after success: function (data) {} remove last comma

    0 讨论(0)
  • 2021-01-28 09:12

    Are you wrapping your js code in $(document).ready() ?

    A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

    Try enclosing everything in

    $(function(){
    //your code here
    })
    

    Like this:

    $(function(){
    $('.rating').on('rating.change', function () {
      var rating_id = $(this).attr('id');
      var res = rating_id.split("_");
    
      var comment = $("#comments_" + res[2]).val();
      var score = $("#item_score_" + res[2]).val();
    
      var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
        + <?php echo $query['monitor_id']; ?>
        + '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
    
      $.ajax({
        url: "controller.php",
        type: "POST",
        data: post,
        cache: false,
        dataType: "json",
        beforeSend: function () {
          saveScore();
        },
        success: function (data) {
          $(".FixedDiv").addClass("panel-danger");
          setTimeout(close, 500);
          $("#label_" + res[2]).html(data.score_result);
          $("#monitoring_score").html(data.calculated_score);
        }
      });
    });
    
    function saveScore() {
      var docHeight = $(document).height();
    
      $("body").append("<div id='overlay'></div>");
    
      $("#overlay")
        .height(docHeight)
        .css({
          'opacity': 0.4,
          'position': 'absolute',
          'top': 0,
          'left': 0,
          'background-color': 'black',
          'width': '100%',
          'z-index': 5000
        });
    }
    
    });
    
    0 讨论(0)
  • 2021-01-28 09:18

    Is your PHP code valid and not throwing extra code which is messing up your JSON object. When there is a notice the JSON object becomes a string instead of a JSON string and then javascript can't parse it anymore.

    Please make a new clean controller without any other code, post the data again and then check what is happening. Never return data but echo data with an exit.

    Javascript and Code looks valid but somewhere else in your MVC may throw HTML code in the exit statement or generating it before you enter the controller which is required to return the data.

    0 讨论(0)
  • 2021-01-28 09:19

    Try adding an error handler to your Ajax function and see what it returns:

    $.ajax({
        url: "controller.php",
        type: "POST",
        data: post,
        cache: false,
        dataType: "json",
        beforeSend: function () {
          saveScore();
        },
        success: function (data) {
          $(".FixedDiv").addClass("panel-danger");
          setTimeout(close, 500);
          $("#label_" + res[2]).html(data.score_result);
          $("#monitoring_score").html(data.calculated_score);
        },
        error: function(data) {
          console.log("ERROR: ", data);
        }
      });
    

    Share the result with us so we can trouble shoot your issue and help you.

    0 讨论(0)
  • 2021-01-28 09:24

    I think a few of the other posters are on to something about the invalid JSON,

    I would add however, this is something I like to do for JSON

    <?php
       ob_start(); //turn on output buffering
    
       //...other code
    
    
    $debug = ob_get_clean();
    $response['debug'] = $debug; //comment this when live in production
    
    header('Content-type: application/json');
    
    echo json_encode($response);
    

    What this does is turn on output buffering. Which traps any output and buffers it. This includes warnings, notices, echo, and print stuff. Then it stuffs it into the response as debug and forwards it to the client.

    Obviously you would not want to do this on live production server, but you can easily comment it out. It can be a security issue to include some errors and stack trace information to the client. But for debugging purposes it works great.

    The problem with JSON is if you are checking the value of something somewhere (printing it) or have any notices it will muck up your JSON. For example

     printed content
     {"foo":"bar"}
    

    So this takes away that problem entirely (assuming you output buffer before printing anything) like so:

     {"foo":"bar", "debug":"printed content"}
    

    And now you have valid JSON, and as a side bonus you can print out your debug info by simply doing

     $.ajax({
         url: "controller.php",
         type: "POST",
         data: post,
         cache: false,
         dataType: "json",
         beforeSend: function () {
           saveScore();
         },
         success: function (data) {
              if(data.debug) console.log(data.debug);
         }
     });
    

    It's simple and effective.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题