-1

I am a student and im currently working on a php project. When the below code is executed im getting an error 500.
project.js

$('#project[enter image description here][1]Modal').on('show.bs.modal', function (event) {
        var projectid = el.data('id');
        $.ajax({
            type:'GET',
            url: 'project.php',
            data: {'projectid':projectid},
            dataType : 'json',
            success : function(data) {
                if (data.success) {
                    var tot = data.amount+parseFloat(amount);
                    modal.find('#totalAmt').html(tot);
                }
            },
            error: function (jqXHR, exception) {
               alert(exception);
            }
        });
    });

project.php

<?php
include_once '../config.php';
if (isset($_GET['projectid'])) {
    $projectId = strip_tags($_POST['projectid']);
    $query = "SELECT SUM(amount) as sum FROM pledge WHERE project_id=$projectid";
    $amount = mysqli_query($mysqli, $query) or die(mysql_error());
    return $amount;
}
?>

Below is the config.php

<?php

$databaseHost = 'localhost';
$databaseName = 'lyceum';
$databaseUsername = 'root';
$databasePassword = 'la#3478';

$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);

?>

Below is the project structure,
lyceum
     js
       project.js
     project
       science_project.php
       project.php
config.php

Can anyone please help me with the error? Thank you in advance

  • just return json_encode on php part – david Aug 21 '18 at 04:41
  • 1
    couple of errors i see: its $_GET['projectid'] not $_POST['projectid']. mysqli_query returns an object, not the value from the select. strip_tags() has no use here, has no security features, dont use this code in prodcution –  Aug 21 '18 at 04:41
  • https://stackoverflow.com/q/1053424/7362396 how to enable errors (then check full response in DevTools). And as others have mentioned you need to convert the DB result object to JSON. – Tobias K. Aug 21 '18 at 04:46
  • 2
    The reason for the 500 error will be in your HTTP server's error log – Phil Aug 21 '18 at 04:46
  • **Warning:** You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use parameterized [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of manually building your queries like that. Specially since you're not escaping the user inputs at all! – Magnus Eriksson Aug 21 '18 at 04:56

3 Answers3

1

Your issue here is you are attempting to return your values. PHP can't be returned like that, your Javascript and PHP are part of entirely separate callstacks. Whilst this isn't causing your 500 error, you've got other errors in here will.

At the beginning of your project.php you'll need to add header('Content-type: application/json'); Your AJAX call automatically expects JSON, and will treat any response it gets as JSON. However if you wished to use this elsewhere this may prevent errors.

Also, your $amount gives you a mysqli_result object, you'll need to use something like $values = mysqli_fetch_assoc($amount) to get the values required.

Then, instead of returning you'll need to echo json_encode($values['sum']) and if you do not want program execution to continue (like return does) you'll also need to exit() or die() after the echo.

Your die() on your $amount line also has an error and should take mysqli_error() instead mysql_error()

I also suggest looking at prepared statements to protect your queries from SQL injection here: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Avoid posting your database details. You never know how long your project, or this question will be around for. If your database is used for something publicly used, and you store sensitive information, someone could've taken this password a long time ago and could get write access to it.

Funce
  • 50
  • 6
  • 1
    Adding a `Content-type` response header is fantastic advice but it's worth pointing out OP has `dataType: 'json'` in their client-side code which overwrites any default handling – Phil Aug 21 '18 at 04:48
  • I see! I'll amend that now. – Funce Aug 21 '18 at 04:49
  • Also, `$amount` will be a `mysqli_result` object and not something that can be encoded as JSON. Data will need to be _fetched_ from the DB – Phil Aug 21 '18 at 04:49
  • Thanks for the answer but even if I do the above changes I get the below error jquery.min.js:4 GET http://localhost/lyceum/projects/project.php?projectid=1 500 (Internal Server Error) jquery.min.js:4 XHR failed loading: GET "http://localhost/lyceum/projects/project.php?projectid=1". – Yasal Rathnayake Aug 21 '18 at 04:52
  • Having `return` won't trigger a 500 error though so that shouldn't be the reason for the OP's error. It should simply result in an empty response. The OP needs to check the servers error log (or enable "display_errors" and read the response of the request) to see what actually happens. – Magnus Eriksson Aug 21 '18 at 05:01
  • Amended. Hopefully this should fix it a little more. May I recommend getting some debugging software like XDebug. It saved me in times like this. – Funce Aug 21 '18 at 05:01
0

To make project.js work your project.php should look like

include_once '../config.php';
if (isset($_GET['projectid'])) {
    $projectId = strip_tags($_POST['projectid']);
    $query = "SELECT SUM(amount) as sum FROM pledge WHERE project_id=$projectid";
    $amount = mysqli_query($mysqli, $query) or die(mysql_error());

    $response = array();
    $response["success"] = TRUE;
    $response["amount"] = $amount;

    echo json_encode($response);
}
Javed Sayyed
  • 149
  • 10
  • 2
    What have you changed that would solve a 500 error? The OP should also use Prepared Statements instead of `strip_tags()` (which has zero relevance in this context) and injecting the user input totally unescaped into the query. – Magnus Eriksson Aug 21 '18 at 05:27
  • the code looks good, to fix 500 we will need more info or error logs, but the JS code is expecting json response so this change is required, even if he manage to fix 500 error the JS code will not work if response is not in json format – Javed Sayyed Aug 21 '18 at 05:33
  • also mixing post\get –  Aug 21 '18 at 05:38
  • Since we don't know what's causing the 500 error (which is what the OP posted the question about), we should simply wait with giving answers until the OP comes back with more info. – Magnus Eriksson Aug 21 '18 at 05:38
0

The 500 (internal server error) means something went wrong on the server's side.

It could be several things you have to check,

1)I would start by verifying that the URL and parameters are correct. Also, make sure that whatever handles the request is expecting the request as a GET and not a POST.

2) One useful way to learn more about what's going on is to use a tool like Fiddler which will let you watch all HTTP requests and responses.

If you don't have a compelling reason to write your own Ajax code, you would be far better off using a library that handles the Ajax interactions for you. jQuery is one option.

Madhuri Patel
  • 1,684
  • 10
  • 22