5

I use $ajax requests in many parts of my PHP website everything was working perfectly until few days ago all my $ajax requests start giving error 500 - internal server error. I can see that error in the console and also I used error handler to get more information about the error. That is my Ajax request

window.setInterval(function(){
         $.ajax({
            type: "GET",
            url: "include-ajax/is_it_midnight.php",
            dataType: "json",
            success: function(data)
            {
                if(data == 1)
                {
                    //Reload website at midnight
                    location.reload();
                }   
            },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest);
                        alert(textStatus);
                        alert(errorThrown);
                        alert(XMLHttpRequest.responseText);
                    }
        }); 

    }, 10000);

that is what i get on my browser:

enter image description here

is_it_midnight.php:

<?php
$current_hour = date('H');
$current_minute = date('i');
$current_second = date('s');
//If the website was open between the 00:00:00 and 00:00:10 it will refresh automatically
//else it will not be open it will open after midnight so it will have aleardy the new day data 
if($current_hour == 0 && $current_minute == 0 && ($current_second > 0 && $current_second < 10))
{
    $is_it_midnight = 1;//This flag means it is midnight
}
else
{
    $is_it_midnight = 2;//This flag means it is not midnight
}
echo json_encode($is_it_midnight);
?>

Some Notes: 1. It is not giving this error all the time sometimes it works fine and bring the response correctly (I see the response and header information on the website and when I check network tab in the chrome console). 2. it does not matter if the type is GET OR POST it keeps giving me the same problem (I show this ajax example with GET type but I have also POST type requests in my website with the same problem). 3. I add the ini_set('display_errors',1);``ini_set('display_startup_errors',1);``error_reporting(-1); to the start of the is_it_midnight.php but no errors showed because i believe there is no syntax or any other php errors (because sometimes it works fine and correctly). 4. I check also the server error log but there is nothing related to this files or any other ajax file at all. 5. I tried to check if this is a timeout error but I did not get any timeout from textStatus it just alert error.

UPDATE :
I checked apache log and I found something like this: [Sat Feb 21 07:35:05 2015] [error] [client 176.40.150.195] Premature end of script headers: is_it_midnight.php, referer: http://www.example.com/index.php

I need any useful help or clue to understand why do I get this error is there anything I did not try it to get more information about that error???

Basel
  • 1,305
  • 7
  • 25
  • 34
  • 4
    Simply check your PHP error log. – Brad Feb 17 '15 at 21:46
  • http://stackoverflow.com/questions/5127838/where-does-php-store-the-error-log – epascarello Feb 17 '15 at 21:47
  • @Brad I said in the question that I check the log and contact the hosting company also but there is no information about this 500 error there. – Basel Feb 17 '15 at 21:48
  • I cannot reproduce the error with the supplied code. – showdev Feb 17 '15 at 21:50
  • 2
    Did you check your Apache error log? – Terry McCann Feb 17 '15 at 21:51
  • 1
    @showdev yeah that is what I am talking about . this error is not showing for me all the time. I am trying to understand why is it showing just sometimes??? – Basel Feb 17 '15 at 21:53
  • @TerryMcCann I checked apache log and I found something like this: `188.59.214.237 - - [01/Feb/2015:00:39:25 -0800] "POST /proxy.php HTTP/1.1" 500 205 "http://www.example.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0"` how could that help me ?? – Basel Feb 19 '15 at 08:25
  • 1
    Are you sure you are looking in the right place? This looks more like an access log entry than an error log entry. – Terry McCann Feb 19 '15 at 23:36
  • @TerryMcCann you are right that was access log I added one of the apache error log to the question – Basel Feb 21 '15 at 16:38
  • I suspect your host : CPU/RAM/SWAP restriction or file permissions, read this post it can help you. http://stackoverflow.com/a/18548854/4098311 – Halayem Anis Feb 22 '15 at 14:17
  • I would say you about memory limit, but your script it's simple, so I supose that could be a max requests problem. How often do you call this script? Maybe this will help you http://kb.sp.parallels.com/en/115971 – artberri Feb 22 '15 at 21:18
  • Have you checked the permissions? Try changing to 705 or 755. – Robert W. Hunter Feb 23 '15 at 10:32
  • Error 500 occurs when there is a fatal error inside of a php script, try to debug your request. – iamawebgeek Feb 24 '15 at 04:58
  • show php -m from console, or phpinfo() and say, have you enabled a json module? – Andrey Vorobyev Feb 24 '15 at 07:36
  • What about dumping the variable with `var_dump($is_it_midnight); exit(); ` – Marcel Djaman Feb 25 '15 at 17:25
  • If you know where all of the logs actually go, check to make sure their file sizes aren't crazy large. Apache on occasion acts a little off when it has to write to a file that's say > 1G for example (which would explain the intermittent issues if sometime it's trying to throw a warning and others it isn't, thus returning just fine). Probably not the case, but I've come across that on more than one occasion in the past. Actually, now that I think of it, a failing hard drive might do that too, but that's a serious long shot. – Patrick Webster Feb 27 '15 at 21:23
  • Why are you json encoding a digit? Just echo the digit and exit(); Remove the datatype:'json' from your ajax – greg_diesel Feb 27 '15 at 23:10

7 Answers7

3

First of all you must be sure that the error log mechanism it's well configured.

To do that add the following code or similar:

ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "Php Errors!" );

An other issue that I notice it's that your php script it's not returning 100% valid JSON and I also think that you can refactor the code to return the result without the necessity to create any variable (better performance, faster, lees code) avoiding any kind of memory allocations problems.

In some cases very loaded shared servers or unscalable VPS can experiment very low memory and can randomly generate errors when try to allocate memory for variables.

I don't know if you use some kind of Framework or not but a different way to write your script in pure php can be something like this:

header('Content-Type: application/json');
return (date('H') == 0 AND date('i') == 0 AND (date('s') > 0 AND date('s') < 10)) ? json_encode(['res' => 1]) : json_encode(['res' => 2]);

This code will always return valid JSON format like {"res":1} or {"res":2} and you can easily access this trough JS like this res = data.res; console.log(res); and you'll evaluate this like this: (data.res === 1).

In your case, you are using dataType: "json" and this in almost all cases it's not woking well if your php it's not returning valid JSON. Maybe you consider to remove it, it's not very important here if you are not enferced to expect only valid JSON.

You can give it a try and see what is happening. If the error persist you can see it inside the /tmp/php-error.log file. and comment it with your hosting company.

As a parentheses, I would like to add that your script should return 1 or 0, true or false instead of 1 or 2. It's just a more pragmatic way to doit.

Let me know if my answer was helpful or if you can't fix the problem and I will try to help you.

Bye Bye! Suerte!

Catalin Cardei
  • 304
  • 4
  • 15
1

My guess is that the PHP process is killed by the server due to some (mis)configuration on your host (I suspect that mod_fastcgi/mod_fcgid is used; you can check this with phpinfo()). Also, you execute the call on each 10 seconds which could hit some limit. What I would do in your case:

  • Check if PHP works with mod_fastcgi/mod_fcgid (Server API field in phpinfo()).
  • Check the Apache access_log and see if a pattern exists for 500 status code for script is_it_midnight.php.
  • Try to increase the setInterval refresh time to 15s, 20s, 25s, 30s and etc. to see if there is any improvement.
  • Place error_log (memory_get_usage()); before echo json_encode($is_it_midnight); to see what is the memory usage allocated to the script (although it is very unlikely that the memory usage is a problem given the small script).
VolenD
  • 3,592
  • 18
  • 23
1

It is very possible that your host has done a recent update on their servers which causes the problem.

You should advice them to look at the memory consumption, and maybe try to increase Apache memory limit parameter: "RLimitMEM" to upper value, which is a common factor for this kind of error.

Adam
  • 17,838
  • 32
  • 54
1

I don't know if this would help you, but i had the same issue a while ago, the only action i did was removing this from my jquery ajax functions

dataType: "json"

Here is some functions i made ("mostrar_alert_ui" is a modal alert windows function, same as "MostrarVentanaBoton" wich is a confirm alert function)

//Función ajax con alert
function Funciones_Ajax_conAlert(urlx, datax, callback, phpencode) {
    var TodoBien = false;
    $.ajax({
        type: "POST",
        url: urlx,
        data: datax,
        async: true,
        success: function (data) {
            if (phpencode == true) {
                data = $.parseJSON(data);   
            }
            console.log(data) //Solo para propositos de debug
            if (data.success) {
                MostrarVentanaBoton(data.titulo, data.mensaje, data.boton, callback);
            } else {
                mostrar_alert_ui(data.titulo, data.mensaje)
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Failed " + urlx);
            alert(xhr.responseText);
            alert(thrownError);
        }
    });
}

And just in case, double check the directions

Ricardo Rios
  • 255
  • 7
  • 23
1

Have you checked the file permissions on the server? The webserver user must be able to read the file, you want to access. See also (https://stackoverflow.com/a/17626018/3972213)

Update: If you are using apache2 and have access to the configuration, you can get more information about each request by turning on the forensic log (http://httpd.apache.org/docs/2.2/mod/mod_log_forensic.html). Hope this helps.

Community
  • 1
  • 1
skroczek
  • 2,289
  • 2
  • 16
  • 23
0

Well, the "Premature end of script headers" is pretty common, and there's few possibilities. It indicate that PHP script has been stopped for some reason before sending any output. It's nothing to do with AJAX itself.

Possibilities:

1. Apache misconfiguration

Upgrading or downgrading to a different version of PHP can leave residual options in the httpd.conf. Check the current version of PHP using php -v on the command line and search for any lines mentioning another version in the httpd.conf. If you find them, comment them out, distill the httpd.conf and restart apache.

Check your Apache configuration for any changes and revise PHP's module list (try to disable them one by one).

2. Resource limit

The RLimitCPU and RLimitMEM directives in the httpd.conf may also be responsible for the error if a script was killed due to a resource limit.

3. Third party extension

A configuration problem in suEXEC, mod_perl, or another third party module can often interfere with the execution of scripts and cause the error. If these are the cause, additional information relating to specifics will be found in the apache error_log.

4. SuPHP crashing

If suphp’s log reaches 2GB in size or larger you may see the premature end of scripts headers error. See what the log contains and either gzip it or null it. Restart apache and then deal with any issues that the suphp log brought to light. The suphp log is located at: /usr/local/apache/logs/suphp_log

5. File permissions

The script’s permissions may also cause this error. CGI scripts can only access resources allowed for the User and Group specified in the httpd.conf. In this case, the error may simply be pointing out that an unauthorized user is attempting to access a script.

As you can see, there's few possibilities. You mentioned that it crashes only sometimes, so it may be something with resources or configuration. For example - if your server is under heavy load, Apache can reject your request and throw this generic "Premature end of script headers" error.

What have you tried already?

Paweł Tomkiel
  • 1,974
  • 2
  • 21
  • 39
0

If it's not happening every time the script runs, then my guess is:

  1. Running out of memory. (Unlikely looking at your code)
  2. Reaching maximum connections on the server where your file is hosted. (Your host should have some tool that you can use to get stats)
  3. Your PHP script is deployed on more than one servers, running behind a load balancer, and one of the servers has a corrupt version of your PHP file, or a corrupt PHP installation, or a faulty web-server(or web-server config). Whenever client request ends up on that corrupt server, you get the 500.
MegaAppBear
  • 1,220
  • 1
  • 9
  • 11