Error 500, AJAX to PHP using $_POST [duplicate] - javascript

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
EDIT:
This is solved. Thank's to everyone who pointed me towards the error log files. Amazing community, this got answered so much faster than I expected.
I'm embarred to say... it was a semicolon.
As a study project, I'm working on a home automation based on a Raspberry Pi.
I installed Apache and built a small website that functions as a GUI. On click, data will be sent via POST-request to ajax.php (in the root folder) which then writes stuff into text files (that then will be read by a python script to do things with the GPIOs - not very elegant, but that's the task now).
Some relevant code:
$("#R0Light1_on").click(function(){
var Value = $(this).val();
var data = {'id': 'R0Light1_on', 'value': Value};
$.ajax({
type: 'POST',
url: 'ajax.php',
data: data,
success: function(){
console.log("#R0Light1_on", data);
$("#R0Light1_on").addClass("on");
$("#R0Light1_off").removeClass("off");
},
error: function() {alert('ERROR: $.ajax #R0Light1_on');}
});
});
<?php
if (isset($_POST['id'])) {
switch ($_POST['id']){
case 'R0Light1_on':
R0Light1_on();
break;
case 'R0Light1_off':
R0Light1_off();
break;
}
}
function R0Light1_on() {
$content = "Not relevant to this Question";
$fp = fopen("/var/www/html/shares/pi/R0Light1_on.txt","wb");
fwrite($fp,$content);
fclose($fp);
exit;
}
function R0Light1_off() {
...
}
?>
<button type="button" id="R0Light1_on" value="1">an</button>
AJAX worked for a month now. 200 ok, all the time and $_POST['id'] did it's job. Then yesterday, it stopped doing so. I don't know what I did, but now it's throwing 500 Internal Server Error messages at me. Even using back-up files doesn't help me and I feel like I read everything Google could find me.
One Thing do I know, though: when I remove the if(isset($_POST['id']))-part, the HTTP-request is successful again (it just also make's the php-script useless, as obvious).
Btw, changing everything to GET doesn't help either (data is visible in URL, but the error stays the same).
Thanks for your time, I'd really appreciate any kind of help.

A 500 error is an internal server error.
You can check your PHP error_log file in the root directory of where the script runs or alternatively at the top of your script, add this to enable error reporting and see the real error that the 500 error translates to:
error_reporting(E_ALL);
#ini_set('display_errors', 1);
It is most likely a PHP fatal error or syntax error.

The issue might be related permissions on the text file, or that it's failing to write to it. Adding permissions to the file would help resolve the issue.
One way to fix this yourself is by checking your apache/php error logs. That should give you a pretty clear indication where the problem lies.

Related

Codeigniter 4 enviroment make JSON.parse fail

I'm new in codeigniter 4
I just started a new project in Codeigniter 4, and i got an error using JSON.parse,
Unexpected token < in JSON at position 30
I get two different results from using different enviroments:
Default// did not make any change to codeigniter config
-The code run totaly fine, though for a second i manage to see a bug in console
-The bad thing, in this enviroment most of debugging tools are deactivated something that i would like to have while working.
SetEnv CI_ENVIRONMENT production // which makes the debugging tools from CI4 appear, this line is in .htacess
-The code stops at JSON.parse and get the error described before in console
So here it is how my code is estructured:
//controller
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//response rgets data from callback from a controller
console.log(response);//{status:0,message:'Access denied'}
data=JSON.parse(response); //error
//Other fixes i already tried
data=JSON.parse(JSON.stringify(response)); //Works fine, but returns a string, need an object
data=JSON.parse(JSON.parse(JSON.stringify(response))); //error
data=JSON.parse("{status:0,message:'Access denied'} "); //Even trying to use directly a JSON format throws error
data=JSON.parse({status:0,message:'Access denied'}) //error, without the comas
data=JSON.parse([{status:0,message:'Access denied'}]) //error
The debbuging tools seem to stop the loading when they find a bug, but i have not managed to find what i am doing wrong. Hope you can help me with this and thanks in advance.
EDIT
I´m using webix libraries for request, but they return string format.
I tried manually what you suggested,but the result was the same. It works if use CI4 in production env, but fails at development mode.
//Solutions tried
response = JSON.parse({"status":0,"message":"Access denied"});//error
response = JSON.parse("{'status':0,'message':'Access denied'}");//error
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//the response should be like this
{"status":0,"message":"Access denied"}
and then use like this
data=JSON.parse(response);
and kindly check your datatype during the post and it should be a json

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

Looking for a list of JavaScript error codes

Is there a list of JavaScript or jQuery error codes (the kind which, for example, MySQL and MariaDB have)?
I have received an Error 5001, and I have no idea what it means. Will elaborate, if it turns out to be necessary.
EDIT
The reason I'm asking is this. A webapp which I'm partially involved in has recently started returning unusual responses from jQuery AJAX calls. Response is
Error 5001
I have never seen something like this before, and googling for a solution returned this old link.
Even after receiving steps to reproduce the error, my team and I haven't been able to do so.
The code is setup like this:
jQuery
$('#someId').on('change',function() {
var id = $('#otherId').val(); // this is a hidden input field
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {valId:id}
async: true,
success: function(data) {
if(data=="ok") {
$('#someId').removeClass('blue').addClass('green');
} else {
$('#someId').removeClass('green').addClass('blue');
}
},
error: function(desc, err) {
console.log("Details: "+ JSON.stringify(desc) + "\r\nError: " + JSON.stringify(err);
}
});
});
PHP
$id = preg_replace('/\D/','',(int)$_POST['id']);
if($id < 1 || $id != $_POST['id']) {
echo "no";
die();
}
$date = date('Y-m-d H:i:s');
$mysqli->query("UPDATE mytable SET dateupdated = '".$date."' WHERE id = $id");
if($mysqli->affected_rows < 1) {
echo "no.";
die();
}
echo "ok";
Error logging has been disabled globally, and there's nothing from the PHP side of things, which would printout this error.
If it's of any relevance, the server on which the app is hosted has recently started responding sluggishly, and returning a query such as
SELECT * FROM users ORDER BY datemodified DESC LIMIT 10
requires the users to wait for up to 3 minutes. The database has been optimized and repaired when these issues starting happening, but that didn't help. DB has also been tested on two other unrelated servers (same PHP and MariaDB version), and the same query performed quickly, as expected.
After doing an extensive search through all the files in the entire webapp, it turned out that the error came from a custom error handler in an old custom JS library. Apologies for wasting everybody's time.
https://learn.microsoft.com/en-us/scripting/javascript/reference/javascript-run-time-errors - This might be what you are looking for if you are doing something with Windows Apps.
In your case Error 5001 could be - 5001 Number expected

post request returns ok but no data and function not working

Ok, I've been putting together a website for the las couple of weeks.
I got everything working before moving on to next phase. Made a lot of changes but none to the functions that I'm talking about.
basically I have a code:
var grabbedItems = [];
function grab(){
$.post(questions.php, {"grab":"grab"}, function(data){
grabbedItems = data;
console.log(grabbeditems);
}, "json");
}
The function gets called on page load. The problem is that network tab says 200 ok for questions.php, but console.log() doesn't even log anything. I can't think what i've done wrong. i haven't even changed the page that the function is on. What could be the problem, apache says no errors network says 200 ok. But functions are not working. I don't think there is anything wrong with my JQuery file, that returns 200 ok aswell.
Any help would be appreciated.
The problem was with the data in one of the mysql fields. I used a £ sign. for some reason the JSOn didn't like it. Maybe I should look into the coding of the database entries.

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Categories

Resources