500 error from ajax request (jQuery) to Code Igniter controller - javascript

Was wondering if anyone had encountered this problem.
I am calling a CI controller that runs a model (on the server) and takes longer (about 5 minutes) for a specific scenario. The problem is that I am getting a 500 error after a long request but I do not get any errors when the request is shorter (about 1 and a half minutes).
Some things that I already checked:
CI's 'csrf_protection' is OFF
I've set a long timeout in my ajax call (900000)
I've set max_execution_time in PHP to 900
I've set Idle Time-Out in IIS to (20 minutes)
Here's my ajax call:
$.ajax({
type:'POST',
url:"run/runScenario/" + saveOrUpdate + "/" + scenarioname + "/" + units + "/" + stateid + "/" + climatestationid + "/" + soiltexture + "/" +
moisturecontent + "/" + modsoilflag + "/" + slopelength + "/" + slopeshape + "/" + slopesteepness + "/" + vegcommunity + "/" +
basalcover + "/" + canopycover + "/" + rockcover + "/" + littercover + "/" + cryptogamscover,
data: {scenarioDescription: scenariodescription},
timeout:900000,
statusCode: {
500: function() {
alert( "page not found" );
}
},
success: function(runData){
$('#progressBar').append('<p>Done running scenario.</p>');
$('#progressBar').append('<p>Saving scenario...</p>');
saveScenarioResultsTable();
$('#progressBar').append('<p>Creating output table...</p>');
printScenarioResultsTable(scenarioname);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
// stop timer
var end = new Date().getTime();
var execution_time = end - TIMER;
runTimeMessage = "<br/><b>Ran scenario in " + (parseInt(execution_time) * 0.001) + " seconds.</b>";
alert(runTimeMessage);
}
});
UPDATE I created a test function (as part of my run controller) and set a sleep(300) inside the function. I got the same 500 error.
But, when I change to sleep(299), the function runs successfully. Obviously, there is a 5 minute limit per request.
I have already changed the *max_execution_time* in php.ini. Any other suggestions?
UPDATE #2 I have found the solution to my problem. The problem was that because "safe_mode" was not enabled in my PHP settings, the PHP timeout was being overwritten in CodeIgniter.php (line 107). I am running CodeIgniter 2.1.4. I hope this helps someone else. :)

Just as an idea, but not a fixing of the code:
What if you will use two different ajax requests:
Request for processing and writing the result of processing in some buffer like file or sql record. This request may or may not return a random descriptor of future resource.
Request for getting results of processing by descriptor or just by availability of resources. This request have to be joined to the timer.
Timeline:
-------------------------------------------------------------------
Step Local server processing
-------------------------------------------------------------------
1. Request for processing >>> Server >>> Thread for processing
2. Descriptor of resource <<< Server >>> Descriptor of resource
3. Server <<< Result of processing
4. Request by descriptor >>> Server
5. Result <<< Server >>> Deletion of file or record
-------------------------------------------------------------------
There:
1, 2 - Ajax #1, fires by demand.
4, 5 - Ajax #2, fires every 10sec.

Related

Cordova app has internet connection via emulator, but not on device [update: ajax problem]

I am trying to build a small app via cordova that sends data to a PERL-Script on a server. The debug and release build work fine on the genymotion emulator, however sending the data from Android phones does not work. There is no error message from the app (either, which is supposed to show up when the connection fails).
Running USB debugging, I do get the follwoing invoke error message (the savedataLastpage funtion is supposed to send the data):
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.3.min.js:4)
at Ac (jquery-2.1.3.min.js:4)
at Function.n.param (jquery-2.1.3.min.js:4)
at Function.ajax (jquery-2.1.3.min.js:4)
at Object.saveDataLastPage (index.js:631)
at Object.renderLastPage (index.js:461)
at Object.recordResponse (index.js:597)
at HTMLButtonElement.<anonymous> (index.js:357)
at HTMLButtonElement.dispatch (jquery-2.1.3.min.js:3)
at HTMLButtonElement.r.handle (jquery-2.1.3.min.js:3)
The pertaining code is the following:
index.js:631
saveDataLastPage:function() {
$.ajax({
type: 'post',
url: '/URL/',
data: localStore,
crossDomain: true,
success: function (result) {
var pid = localStore.participant_id, snoozed = localStore.snoozed, uniqueKey = localStore.uniqueKey, pause_time=localStore.pause_time;
localStore.clear();
localStore.participant_id = pid;
localStore.snoozed = snoozed;
localStore.uniqueKey = uniqueKey;
localStore.pause_time=pause_time;
$("#question").html("<h3>Thank you, your responses have been sent.</h3>");
},
error: function (request, error) {
console.log(error);
$("#question").html("<h3>Error: Please check your internet connection.</h3><br><button>Send again</button>");
$("#question button").click(function () {app.saveDataLastPage();});
}
});
},
index.js:461
else {
var datestamp = new Date();
var year = datestamp.getFullYear(), month = datestamp.getMonth(), day=datestamp.getDate(), hours=datestamp.getHours(), minutes=datestamp.getMinutes(), seconds=datestamp.getSeconds(), milliseconds=datestamp.getMilliseconds();
localStore[uniqueKey + '.' + "completed" + "_" + "completedSurvey" + "_" + year + "_" + month + "_" + day + "_" + hours + "_" + minutes + "_" + seconds + "_" + milliseconds] = 1;
app.saveDataLastPage();
}
As stated before, on the genymotion emulator the ajax script works fine without the error and sends the data to the script.
I'm not sure why the emulator would work just fine but the error Uncaught TypeError: Illegal invocation suggests that it is a problem with the ajax post call. Specifically, the default setting of processing the data into a query string likely fails.
From the ajax documentation:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
That means you can either turn off the processing processData: false which will post the data in the body of the request or you have to transform the localStore data into a proper object (from whatever it was before).
If it is like an object you can do the following:
var data = {};
for (var elem in localStore) {
data[elem] = localStore[elem];
}
or possibly in brief:
var data = {};
localStore.each(function(elem) { data[elem.name] = elem.value; });

window.onerror line number always 1

I want to get a mail if an error occurs in my program. This works fine:
window.onerror = function(msg, url, line, col, error) {
prog = "fehler";
var urlJ = server + prog + querystrJsonO + "&qu=" + qu + "&msg=" + msg + "&line=" + line + "&col=" + col;
$.getJSON(urlJ, function(data) {});
};
But I get only linenumber 1.
My code is not minified. What can I do to get the linenumber of the error?
Try creating a XMLHttpRequest inside the function and send a get request to your server with a phone script ready to receive the parameters. Then you can use mail() function to send yourself mail regarding problem. Am using it hope it sounds well to you

NodeJS HTTP response max size reached?

I stumbled on a very strange issue recently concerning my Node.JS REST API. It's aim is to convert HTTP requests to SQL requests and the SQL response to HTTP response so I can then transfer everything over SSL/TLS and it's encoded.
The problem is that when the response size is small, it all works fine but when it exceed a certain size (about 255.37 KB), the response body is cutted right in the middle of the JSON. After multiple tests it appears that the issue is related to the HTTP response total size (including the headers) because when some custom headers are removed, more of the body is sent. I wrote a similar code in PHP and the response in JSON from the PHP API is fine so I assumed that the issue was originating from a bug in the Node.JS web server. Also, the Content-Lenght header is fine and has the right value (like the PHP API response does).
I'm using Node.JS v6.11.0 with the last release of Express. All my dependencies are up to date thanks to npm.
Here is the code of the function that handle the GET HTTP requests and proceed in doing SELECT SQL requests, then parse to json string the answer
function SelectData(connection){
return function (req, res) {
let tableName = req.params.table;
let id = req.params.id;
console.log("GET request received with tableName = " + tableName + " and id = " + id);
// Should match this regex
if (!tableName.match(/^[\-\_\s0-9A-Za-z]+$/)){
console.log("Error: Invalid table name provided : " + tableName);
badRequestError(req, res);
return;
}
if (id !== undefined){
if (!id.match(/^[0-9]+$/)){
console.log("Error: Invalid id provided : " + id + " (table name was valid : " + tableName + ")");
badRequestError(req, res);
return;
}
}
// if id is empty, then don't use any condition, else, add SQL condition
idPart = (id == undefined) ? "" : ('WHERE id="' + id + '"');
// TODO: try to replace " + var + " by question marks and bind params, find a way to do it w/ id
connection.query("SELECT * FROM " + tableName + " " + idPart + ";", function(err, result){
res.setHeader('Content-Type', 'application/json');
console.log("Request executed successfully !");
// Works too but I prefer the .send() method
// res.status(200).write(JSON.stringify(result)).end();
res.status(200).send(JSON.stringify(result));
req.connection.destroy();
return;
});
}
}
function badRequestError(req, res){
res.setHeader('Content-Type', 'text/plain');
res.status(400).send("Bad Request");
req.connection.destroy();
}
exports.SelectData = SelectData;
Edit: After researching yesterday I found similar issue resulting of the use of the HTTPS module so I removed it but it still happens.

"Start" and "end" parameters with the Indeed API

I'm making a call to the Indeed API to get back a list of jobs. According to their (limited) documentation, it accepts start and end as parameters. When I try that, as here:
var api_request = 'http://api.indeed.com/ads/apisearch?publisher='
+ config.API_KEY
+ "&format=" + format
+ "&limit=200"
+ "&start=10"
+ "&end=20"
+ "&userip=" + ip
+ "&useragent=" + user_agent
+ "&v=2"
+ "&q=" + req.params.query
request(api_request, function(err, response, body){
if(!err && response.statusCode == 200){
res.json(body)
}
})
what happens is the start parameter remains at its default value (0), and the end value takes the start value I passed. I have absolutely no idea how or why that's happening. Any ideas? Thanks!

400 Bad Request from Yahoo Finance API

Here's my code in a javascript function in a HTML file
var url = 'http://query.yahooapis.com/v1/public/yql';
var startDate = '2012-01-01';
var endDate = '2012-01-08';
var jsonData = encodeURIComponent('select * from yahoo.finance.historicaldata where symbol in ("YHOO","AAPL","GOOG","MSFT") and startDate = "' + startDate + '" and endDate = "' + endDate + '"');
$.getJSON(url, 'q=' + data + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
When i open the file in the browser, my other functions work except the above as it produces:
GET http://query.yahooapis.com/v1/public/yql?q=[object%20Object]&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json 400 **(Bad Request)** jquery-1.8.3.min.js:2
send jquery-1.8.3.min.js:2
v.extend.ajax jquery-1.8.3.min.js:2
v.(anonymous function) jquery-1.8.3.min.js:2
v.extend.getJSON jquery-1.8.3.min.js:2
drawChart
Should this:
$.getJSON(url, 'q=' + data + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
be this?
$.getJSON(url, 'q=' + jsonData + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
Just a heads up - I have a couple of projects (Java and JavaScript) which call this API. They usually work but occasionally fail with a 400 without any change to the code then work a few hours/days later, again, without changing the code. I think if there is some problem with the server it may return this rather than a correct error in the 500 range (server error - It's me, not you)
Errors in the 400 range should be a message from the server along the lines of "it's you, not me - fix your request before you send it again" but I don't think this is the case with this API.
In short - it may be them not you!

Categories