The problem:
I'm getting a 500 Internal Server Error when making an AJAX request, and am getting back this in the Chrome Console and I don't understand what I am doing wrong, I'm new to writing AJAX calls and handling them in PHP:
{"readyState":4,"responseText":"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>500 Internal Server Error</title>\n</head><body>\n<h1>Internal Server Error</h1>\n<p>The server encountered an internal error or\nmisconfiguration and was unable to complete\nyour request.</p>\n<p>Please contact the server administrator at \n webmaster#mywebdomain.com to inform them of the time this error occurred,\n and the actions you performed just before this error.</p>\n<p>More information about this error may be available\nin the server error log.</p>\n<p>Additionally, a 500 Internal Server Error\nerror was encountered while trying to use an ErrorDocument to handle the request.</p>\n<hr>\n<address>Apache/2.4.18 (Unix) OpenSSL/1.0.1e-fips mod_jk/1.2.37 mod_bwlimited/1.4 Server at mywebdomain.com Port 80</address>\n</body></html>\n","status":500,"statusText":"Internal Server Error"}
Here is the javascript (I would add that I find it odd that it seems to want 'http' when everything on our server is 'https', If I change to 'https', then it brings back 'No Access-Control-Allow-Origin is present'... nonsense, which isn' true, I specify that in the header, not sure if that's because this is the same domain):
$.ajax({
url: 'http://mywebdomain.com/admin/custom/modules/cac_customize_agent_comp/views/getID.php',
method: 'POST',
dataType: 'text',
data: {wnID: $("#wn_writing946b_number_ida").val(), pcgID: $("#aos_products_cac_customize_agent_comp_1aos_products_ida").val()}
})
.done(function(response) {
console.log("response");
$("#displayText").html(response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
$("#displayText").html("There was a problem retrieving the records...");
})
.always(function() {
console.log("complete");
});
And here is the php file:
<?php
header('Access-Control-Allow-Origin: *');
header('content-type: text/html; charset: utf-8');
$wnID = $_POST['wnID'];
$pcgID = $_POST['pcgID'];
function getDefaultPercentage($wnID, $pcgID){
$sql = "SELECT wn_writing_number_cstm.title_c
FROM wn_writing_number_cac_customize_agent_comp_1_c
RIGHT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number_cstm.id_c
WHERE wn_writing_number_cstm.id_c = '" . $wnID . "'";
$result = $GLOBALS['db']->query($sql);
while($row = $GLOBALS['db']->fetchByAssoc($result) ){
$titleWN = $row['title_c'];
} //end while
$sql = "SELECT pcg_product_comp_grid_cstm.title_c, pcg_product_comp_grid_cstm.percentage_c
FROM aos_products_pcg_product_comp_grid_1_c
LEFT OUTER JOIN pcg_product_comp_grid_cstm ON aos_products_pcg_product_comp_grid_1_c.aos_products_pcg_product_comp_grid_1pcg_product_comp_grid_idb = pcg_product_comp_grid_cstm.id_c
WHERE aos_products_pcg_product_comp_grid_1_c.aos_products_pcg_product_comp_grid_1aos_products_ida = '" . $pcgID . "'";
$result = $GLOBALS['db']->query($sql);
while($row = $GLOBALS['db']->fetchByAssoc($result) ){
$titlePCG = $row['title_c'];
$percentage = $row['percentage_c'];
} //end while
if($titlePCG == $titleWN){
$fullTitle = '';
switch ($titlePCG) {
case "TR":
$fullTitle = 'Trainee';
break;
case "SA":
$fullTitle = 'Sub-Agent';
break;
case "A":
$fullTitle = 'Agent';
break;
case "GA":
$fullTitle = 'General Agent';
break;
case "MGA":
$fullTitle = 'Managing General Agent';
break;
case "FMO":
$fullTitle = 'Field Marketing Organization';
break;
case "DM":
$fullTitle = 'District Manager';
break;
case "RVP":
$fullTitle = 'Regional Vice President';
break;
default:
"";
} //end switch
} //end if
if($titlePCG != '' && $titleWN != ''){
$textToOutput = $fullTitle . ": " . $percentage . "% is the default percentage.";
}
else {
$textToOutput = "There was a problem retrieving the records...";
}
return $textToOutput;
} //end getDefaultPercentage function
$textToOutput = getDefaultPercentage($wnID, $pcgID);
echo $textToOutput;
?>
Here is the php error I am getting from the error log:
[Tue Jun 14 14:25:37.752301 2016] [core:error] [pid 7823] [client XX.XX.XXX.XX:XXXXX] End of script output before headers: getID.php, referer: http://mywebdomain.com/admin/index.php
[Tue Jun 14 14:25:39.347480 2016] [:error] [pid 7822] [client XX.XX.XXX.XX:XXXXX] SoftException in Application.cpp:256: File "/home/mywebdomain/public_html/admin/custom/modules/cac_customize_agent_comp/views/getID.php" is writeable by group, referer: http://mywebdomain.com/admin/index.php
[Tue Jun 14 14:25:39.347557 2016] [core:error] [pid 7822] [client XX.XX.XXX.XX:XXXXX] End of script output before headers: getID.php, referer: http://mywebdomain.com/admin/index.php
The answer to my problem was a permissions issue.
I moved the file back to the core directory, and decided to forget trying to get permissions just right on every folder in between, and bam, worked like a charm.
Case in Point, when you are getting a 500 error from navigating directly to the actual url, permissions is a likely suspect.
Also, the headers I included were not needed.
There is some Syntax error in your code! That's why a 500 is shown.
Most probably you have to enable display_startup_errors=1 in the apache.conf or php.ini or do a ini_set();
P.S Look for some more blahblah_error=0 and change to blahblash_error=1 and you're done.
And don't forget to restart the apache too after doing any of these changes
Related
After long research and debugging i realized java-script was not the problem, I was rather having a cross origin resource exception which was thrown because some how the ajax request could not read my server script or rather did not have permission to access my server script.
So i tried the following codes below but still the same issue, I placed the issue in red block blow, my java script is also below and my server script
$('#send').on('click', function(e) {
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
alert("sending " + name + email + message);// this part is now working fine
$.ajax({
type: "POST",
url: "https://xxxxxx/xxxxx/php/contact/maincontact.php",
data: {
nme: name,
ema: email,
msg: message
},
dataType: 'json',
timeout: 10000,
async: true,
cache: true,// I removed the header which used to here before
error: function(jqXHR, textStatus, errorThrown) {
alert("error : " + errorThrown + " text :" + textStatus + " j :" + jqXHR.status);
alert(jqXHR.responseText);
},
success: Succeeded
});
});
function Succeeded(result) {
alert("Successing");
var data = JSON.parse(result[0]);
try {
$('#name').val(" ");
$('#email').val(" ");
$('#message').val(" ");
if (data == true) {
alert("We will Contact you shortly");
} else {
alert("OOpps! something went wrong");
}
} catch (e) {
alert("You may not enter " + e);
}
}
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxxxx/xxxxxx/php/contact/maincontact.php. (Reason: missing token 'access-control-allow-origin' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
<!-- php codes -->
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
require_once('contact.php');
if(!empty($_POST)){
$addcase = new contact();
$data['vlu'] = $addcase->add($_POST['nme'], $_POST['ema'], $_POST['msg']);
echo json_encode($data);
}else{
echo "Not properly parsed";
}
?>
The error message says:
missing token 'access-control-allow-origin' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel
So when you make the request you are trying to put access-control-allow-origin in the headers. (The message means that browser is asking the server if it is allowed to send that header in cross-origin Ajax and the server isn't saying that it is OK to do that).
This doesn't make any sense. Access-Control-Allow-Origin is a response header. There is no reason to put it on the request.
Now, the code you've provided doesn't try to set that header. This suggests that elsewhere in your code you are trying to set it universally (probably via ajaxsetup).
You need to find the point where you try to set it and remove that code.
I am trying to implement WebSocket communication between a client "web browser" and a Apache 2.4/PHP 5.6 server that is running on Windows 2008 R2.
My application is assume to be running on this URL "HTTPS"
https://myApllication.example.com
I am not sure if there is something I need to install on the server before this works or not.
My code so far looks like this
$(function(){
if(!("WebSocket" in window)){
console.log('your browser does not support WebSocket');
} else {
connect();
$('#disconnect').click(function(){
socket.close();
});
}
function connect(){
var socket;
var host = "ws://myApplication.example.com:8000/dev/icws/poll2.php";
try{
var socket = new WebSocket(host, {
protocolVersion: 13,
origin: 'https://www.example.com'
});
message('Socket Status: '+socket.readyState);
socket.onopen = function(){
message('Socket Status: '+socket.readyState+' (open)');
}
socket.onmessage = function(msg){
message('Received: ' + msg.data);
}
socket.onclose = function(){
message('Socket Status: '+ socket.readyState + ' (Closed)');
}
} catch(exception){
message(exception);
}
} //End connect()
function message(msg){
console.log(msg);
}//End message()
});
This code will give me this error in the console.
DOMException [SecurityError: "The operation is insecure."
code: 18
nsresult: 0x80530012
Here is how my poll2.php script looks like
<?php
header("Content-Type: text/event-stream" . PHP_EOL);
header("Cache-Control: no-cache" . PHP_EOL);
echo "data: {mykey: 'myvalue', eventName: 'eventName'}" . PHP_EOL . PHP_EOL;
?>
** Edited**
After changing the host from
var host = "ws://myApplication.example.com:8000/dev/icws/poll2.php";
to
var host = "wss://myApplication.example.com:8000/dev/icws/poll2.php";
I no longer get the security error but I get this in the console.
Socket Status: 0 (ready)
Socket Status: 3 (Closed)
Firefox can't establish a connection to the server at wss://myApplication.example.com:8000/dev/icws/poll2.php
What could be causing the connection not to be made?
Do I have to open the port 8000 on the server?
My question is NOT about how to solve the Access-Control-Allow-Origin issues. This errors will happen sometimes when performing requests, and other times the url's might be outdated. But I want to print different messages for the user depending on the different errors.
Currently I have the following code:
$.ajax(
{
url: link,
type:'HEAD',
timeout: 2000,
error: function(request, status, message)
{
console.log('ajax error');
console.log(request);
console.log(status);
console.log(message);
openPopUp("There was an error accessing the image. It can be because the address is invalid, "+
"or because the server where the image is stored is not allowing direct access to the images.");
},
success: function()
{
// More stuff here
}
});
Looking at the console it's easy to see if the file was actually missing, or if it was an Access-Control problem. But i'd like to print out two different messages to the user saying exactly what the problem was. Looking at the variables in error: function(request, status, message) they do not change, both cases result in a 404 error. Is there some other was to do this so that I can know what the problem was?
Thank you in advance for the attention.
Your browser console shows you
XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite.com' is therefore not allowed access.
but you cannot access this information yourself with JavaScript alone. When a browser detects a CORS violation, it will discard the header information as a matter of protocol.
One solution that works is to inspect the response headers using server-side code and pass the results back to your client page. For example, if the ajax request fails, you could call this script (let's call it cors.php) and know for certain if it contains "Access-Control-Allow-Origin" or not.
Example:
cors.php?url=http://ip.jsontest.com
cors.php?url=http://www.google.com
returns
Access-Control-Allow-Origin: *
None
Thus, you can do the following in your JavaScript code:
$.ajax({
url: "http://www.google.com",
timeout: 4000,
statusCode: {
404: function() {
// Simple not found page, but not CORS violation
console.log(this.url + " not found" );
}
}
})
.fail(function(jqXHR, textStatus) {
// Empty status is a sign that this may be a CORS violation
// but also check if the request timed out, or that the domain exists
if(jqXHR.status > 0 || jqXHR.statusText == "timeout") {
console.log("Failure because: "+jqXHR.status+" "+jqXHR.statusText+" error");
return;
}
// Determine if this was a CORS violation or not
console.log("Checking if this is a CORS violation at - " + this.url);
$.ajax({
url: "http://myserver.net/cors.php?url=" + escape(this.url),
})
.done(function(msg) {
// Check for the Access-Control-Allow-Origin header
if(msg.indexOf("Access-Control-Allow-Origin") >= 0) {
console.log("Failed bacause '" + msg + "'");
} else {
console.log("Failed bacause of CORS violation");
}
});
})
.done(function(msg) {
// Successful ajax request
console.log(msg);
}); /* Drakes, 2015 */
Customize this PHP script for your own needs:
<?php
/* cors.php */
$url = $_GET["url"];
if(isset($url)) {
$headers = getHeaders($url, "Access-Control-Allow-Origin");
header("Access-Control-Allow-Origin: *"); // Allow your own cross-site requests
echo count($headers) > 0 ? $headers[0] : "None";
}
// Get the response headers, only specific ones
function getHeaders($url, $needle = false) {
$headers = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // Only get the headers
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header_line) use(&$headers, $needle) {
if(!$needle || strpos($header_line, $needle) !== false) {
array_push($headers, $header_line);
}
return strlen($header_line);
});
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
return $headers;
} /* Drakes, 2015 */
You should be able to read the response header from the request object:
var acao = request.getResponseHeader('Access-Control-Allow-Origin');
then output the appropriate error based on whether the header exists and whether your url is in the value.
I'm trying to use phantomJS to capture a screenshot of a URL, however when I call phantomJS (from either the command line or web app) it hangs and seesm to never execute the "exit()" call. I can't seem to find any error messages and it remains running until I kill it. This is the JS file that is passed to the phantomjs command:
var page = require('webpage').create();
var system = require('system');
var script_address = '';
var page_to_load = '';
var members_id = '';
var activities_id = '';
var folder_path = '';
if (system.args.length < 5)
{
console.log('Usage: phantom_activity_fax.js script_address page_to_load members_id activities_id folder_path');
console.log('#Args: '+system.args.length);
phantom.exit();
}//END IF SYSTEM.ARGS.LENGTH === 1
//ASSIGN OUR ARGUMENTS RECIEVED
script_address = system.args[0];
page_to_load = system.args[1];
members_id = system.args[2];
activities_id = system.args[3];
folder_path = system.args[4];
console.log(system.args[0]);
console.log(system.args[1]);
console.log(system.args[2]);
console.log(system.args[3]);
console.log(system.args[4]);
//OPEN OUR PAGE WITH THE VALUES PROVIDED
page.open(page_to_load, function () {
console.log("Entering Anonymous Function, Beginning RENDER:\n");
page.render(folder_path+members_id+'_'+activities_id+'.png');
phantom.exit();
});
I see the values pushed to the console, but after that it just hangs :( I've tried the web inspector, but could not understand where to execute the __run() call, and didn't see any change when I added the debugger-autorun=yes to the call :(.
This is the output I get from the command line when it hangs (as root user):
[root#wv-wellvibe2 faxes]# phantomjs /var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php 397 0 /var/www/wv-wellvibe2-test/uploads/images/faxes/
/var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js
https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php
397
0
/var/www/wv-wellvibe2-test/uploads/images/faxes/
And this is the output I get when running it as my own user, but I don't see the image file in the designated folder (faxes):
[user#wv-wellvibe2 ~]$ phantomjs /var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php 397 0 /var/www/wv-wellvibe2-test/uploads/images/faxes/
/var/www/wv-wellvibe2-test/javascripts/phantom_activity_fax.js
https://wv-wellvibe2-test/manual_scripts/phantom_js_test_page.php
397
0
/var/www/wv-wellvibe2-test/uploads/images/faxes/
Entering Anonymous Function, Beginning RENDER:
[user#wv-wellvibe2 ~]$
Unfortunately, as I said, the command completed but did not save a .png in the faxes folder. Here is the permissions for that folder:
[root#wv-wellvibe2 faxes]# ls -la
total 12
drwxr-xr-x 3 root apache 4096 May 16 15:31 .
drwxr-xr-x 5 apache apache 4096 May 16 14:14 ..
drwxr-xr-x 6 apache apache 4096 May 20 15:05 .svn
Please let me know if there is anything else I can provide!
Thank you!
(As requested here is the PHP script that calls the Phantom JS process)
header("Date: " . date('Y-m-d H:i:s'));
//GET THE SMARTY CONFIG
include_once $_SERVER['DOCUMENT_ROOT'] . "/smarty/configs/config.php";
//VARS USED LATER
$process_script = $_SERVER['DOCUMENT_ROOT'] . '/javascripts/phantom_activity_fax.js';
$page_to_load = 'https://' . $_SERVER['HTTP_HOST'] . '/manual_scripts/phantom_js_test_page.php';
$members_id = $_SESSION['members_id'];
$activities_id = 0;
$folder_path = $_SERVER['DOCUMENT_ROOT'] . 'uploads/images/faxes/';
$system_response = '';
$call = "phantomjs --remote-debugger-port=65534 --remote-debugger-autorun=yes " . $process_script . " " . $page_to_load . " " . $members_id . " " . $activities_id . " " . $folder_path;
echo 'CallingSystemWith: ' . $call . '<br />';
try
{
$system_response = system($call);
echo '<br />SystemResponse: ' . $system_response . '<hr />';
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}//END TRY / CATCH
(The page it tells PhantomJS to "scrape" is a simple PHP script that outtputs a print_r() of $_SESSION and $_REQUEST)
If something goes wrong in your script (such as in page.render), phantom.exit() will never be called. That's why phantomJs seems to hang.
Maybe there is an issue in page.render but I don't think so. The most common causes of hangs are unhandled exception.
I will suggest you 4 things to investigate the issue :
add an handler to phantom.onError and/or to page.onError
encapsulate your code in try/catch blocks (such as for page.render)
Once the page is loaded, there is no test on callback status. It's better to check the status
seems to freeze when calling page.render. Have you tried a simpler filename in the current directory ? Maybe the freeze is because of the security or invalid filename (invalid characters ?)
Hope this will help you
Use :
$phantomjs --debug=true rasterize.js http://... test.pdf
In rasterize.js add a timeout on ressource, that was my problem:
page.settings.resourceTimeout = 10000; // Avoid freeze!!!
javascript
$('#send').on('click', function() {
$.ajax({
'url': $('#url').val(),
'type': 'post',
'complete': function (jqXHR, textStatus) {
var msg = "Status: " + jqXHR.status + " (" + jqXHR.statusText + " - " + textStatus + ")<br />";
msg += jqXHR.getAllResponseHeaders().replace(/\n/g, "<br />");
$('#results').html(msg);
}
});
});
php
header("HTTP/1.0 200 Some message here");
flush();
exit();
Results
Status: 200 (OK - success)
Date: Wed, 07 Dec 2011 21:57:50 GMT
X-Powered-By: PHP/5.3.6
Transfer-Encoding: chunked
Connection: Keep-Alive
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
Content-Type: text/html
Keep-Alive: timeout=5, max=100
Question
How do I get the "Some message here" part of the header?
http
http protocol
6.1 Status-Line
The first line of a Response message is the Status-Line, consisting of
the protocol version followed by a numeric status code and its
associated textual phrase, with each element separated by SP
characters. No CR or LF is allowed except in the final CRLF sequence.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
Got it. It's jqXHR.statusText.
$.get("test.php").complete(function(jqXHR) {
console.log(jqXHR.statusText);
});
Just tried it out in Chrome with your exact PHP code.
Have you tried xhrobject.getResponseHeader() yet? jQuery docs say it's also available there. If you don't know the header's name, try getAllResponseHeaders().
Also, can you see that message in your browser's debugging console (network tab, connection headers)? If it's not there, it will hardly be available from js.