1

@Edit 2,

I think the problem stems from passing arguments.

<br />
<b>Warning</b>:  mysqli_connect(): (HY000/2002): Connection refused in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>12</b><br />
Failed to connect to MySQL: Connection refused<br />
<b>Warning</b>:  mysqli_query() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>30</b><br />
<br />
<b>Warning</b>:  mysqli_close() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>41</b><br />

@Edit, if I disable doRecord method and assign a random number to $retVal, I can see its value from the console. I think the problem is about the function’s body.


I’m trying to save information which is put by the fields into MySQL database. But I cannot see even what the result is by exit(json_encode(array("response" => $response))); or exit(json_encode(array("response" => "not entered")));. I’m sure database works, I tested. Also, button onclick works, but no more. What’s the wrong?

saveEmail.php

<?php


function doRecord($host, $username, $password, $dbName,
                  $senderName, $senderMail, $senderSubject, $senderBody, $cronInput) {

    $retVal = 0;
    /* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
    $link = new mysqli($host, $username, $password, $dbName);

// Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    $date = gmdate('Y-m-d h:i:s', time());
    /*$htmlBody =
        "bodyy <p><a href=\"http://sdfdsf.com/\" target=\"_blank\" rel=\"noopener\">link burada</a>&nbsp;</p>
    <p>&nbsp;</p>
    <p>fdgfd</p>";
    */


// Attempt insert query execution
    $sql = "INSERT INTO  staj.info(name, email, subject, body, progressTime, cronInput)
            VALUES
    ('$senderName', '$senderMail', '$senderSubject', '$senderBody', '$date', '$cronInput');";


    if(mysqli_query($link, $sql)){
        //echo "Records inserted successfully.";
        $retVal = 1;
    } else{
        //echo "\n\nERROR: Could not able to execute $sql. " . mysqli_error($link);
        $retVal = 0;
    }



// Close connection
    mysqli_close($link);
    return $retVal;
}

if (isset($_POST['cron'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];
    $cron = $_POST['cron'];



    $retVal = doRecord("127.0.0.1", "root", "12345678", "staj",
        $name, $email, $subject, $body, $cron);



    if ($retVal == 1) {
        $response = "Mail is put into database";
    } else {
        $response = "SQL error.";
    }
    exit(json_encode(array("response" => $response)));
} else {
    exit(json_encode(array("response" => "not entered")));
}


?>

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
    <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.css" rel="stylesheet">

    <style type="text/css">
        textarea, input {
            margin-bottom: 10px;
        }

    </style>

</head>
<body>
    <div class="container" style="margin-top:100px;">
        <div class="row justify-content-center">
            <div class="col-md-6 col-md-offset-3">
                <label for="name">Name:</label>
                <input id="name" placeholder="Name" class="form-control" required>

                <label for="email">E-mail:</label>
                <input id="email" placeholder="E-mail" class="form-control" required>

                <label for="subject">Subject:</label>
                <input id="subject" placeholder="Name" class="form-control" required>

                <!--<label for="body">Body:</label>-->
                <textarea id="summernote" placeholder="Email body" name="editordata"></textarea>


                <label for="cron">Crontab:</label>
                <input id="cron" placeholder="CronTab Input" class="form-control">

                <input type="button" onclick="saveMail()" value="Save it to Database" class="btn btn-success btn-info">
            </div>
        </div>
    </div>


<script
        src="https://code.jquery.com/jquery-3.4.1.js"
        integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
        crossorigin="anonymous"></script>

<script type="text/javascript">
    function isNotEmpty(caller) {
        if (caller.val() == "") {
            caller.css('border', '1px solid red');
            return false;
        } else {
            caller.css('border', '');
            return true;
        }
    }

    function saveMail() {
        console.log("SaVinG Attempt...");
        var name = $("#name");
        var email = $("#email");
        var subject = $("#subject");
        var body = $("#summernote");
        var cron = $("#cron");

        if (isNotEmpty(cron)) {
            $.ajax({
                url: 'saveEmail.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    name: name.val(),
                    email: email.val(),
                    subject: subject.val(),
                    body: body.val(),
                    cron: cron.val()
                }, success: function (response) {
                    console.log(response);
                }
            });
        }
    }   
</script>

<!-- WYSIWYG editor jses -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
<script>
    $(document).ready(function() {
        $('#summernote').summernote({
            height: 300,
            focus: true
        });
    });
</script>
</body>
</html>
concurrencyboy
  • 341
  • 1
  • 11
  • `”` is not the same as `"` This is a syntax error. – Dharman Jul 25 '19 at 18:16
  • 1
    Possible duplicate of [How do I get PHP errors to display?](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) – Dharman Jul 25 '19 at 18:17
  • Try only single quat like this..else { exit(json_encode(array("response" => 'not entered'))); } – Kamlesh Jain Jul 25 '19 at 18:21
  • In your saveEmail.php, instead of return $retVal; , try: echo json_encode($retval); - this way, you should see the proper output in your console. – Andrew Jul 25 '19 at 18:21
  • 1
    @Dharman it is insane to me how many times a day I see this (SQL injection issue in question) – GrumpyCrouton Jul 25 '19 at 18:25
  • @Dharman I cannot see the result google chrome’s console. Even it exits I should be able to see the response on there. – concurrencyboy Jul 25 '19 at 18:37
  • @Andrew it doesn’t show any thing other than “ SaVinG Attempt... “. Could you write an answer? – concurrencyboy Jul 25 '19 at 18:41
  • 1
    @Dave I was like them at one point, thinking "I'll do it this way for now and secure it later", but now having experience doing it the _right_ way, I can see that it's actually _easier_ in general to do it the right way, not even including the difficulty of rewriting it later. I used to think it would be harder to do, just from looking at the documentation for it. This kind of thinking is _really bad_ as a developer. I honestly feel like, once I got over this line of thinking, my skills increased 100x over. – GrumpyCrouton Jul 25 '19 at 18:43
  • 1
    Couldn't agree more GrumpyCrouton (great nick btw). I too was intimidated a bit but once I started doing "the right thing" it was easier AND safer. – Dave Jul 25 '19 at 18:45

1 Answers1

1

It seems like you have an incorrect quotation mark in your saveEmail.php file. If you use code highlighting, it's easier to see. Instead of:

exit(json_encode(array("response" => "not entered”)));

Try:

exit(json_encode(array("response" => "not entered")));

EDIT:

To see what kind of error blocks your AJAX call, put these lines of call at the beginning of saveEmail.php:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Then temporarily change your ajax call to look like this:

$.ajax({
url: 'saveEmail.php',
method: 'POST',
data: {
    name: name.val(),
    email: email.val(),
    subject: subject.val(),
    body: body.val(),
    cron: cron.val()
}, success: function (response) {
   console.log(response);
} });
Andrew
  • 832
  • 2
  • 3
  • 13
  • I don’t think it stems from it. Anyway,fixed. – concurrencyboy Jul 25 '19 at 18:47
  • It could absolutely stem from it. The reason you don't see any response in the console is most likely that the return is not a proper json array, but instead, a php error (which would absolutely happen on a wrong quote). Just for debugging's sake, you can remove the json dataType from your ajax call, and see the response that way (make sure you enable php errors though). – Andrew Jul 25 '19 at 18:56
  • I did, so it's probably still a PHP error inside the doRecord function. Maybe a mysql error, maybe some other. If you enable errors in PHP and remove the JSON datatype from your ajax call (or change it to "text"), you should see it in your console. – Andrew Jul 25 '19 at 19:05
  • But, I need to run the written code via web browser. How could I see the error other than console? – concurrencyboy Jul 25 '19 at 19:23
  • 1
    Sorry, I don't understand you. In your web browser's console (F12), under "SaVinG Attempt...", you should see the output of saveEmail.php if you do the 2 things I suggested above. There is most likely an error in that .php file, so it doesn't return a proper Json array to your ajax call, and it won't display it. - If that doesn't work, just open the saveEmail.php in your browser: comment out the $_POST variables, and put in some test values manually into your script. See what happens then. – Andrew Jul 25 '19 at 19:28
  • Updated my above answer with what I mean. – Andrew Jul 25 '19 at 19:35
  • So there's some problem with the SQL connection. First I'd try using "localhost" instead of "127.0.0.1". If that doesn't do the trick, double-check whether the other parameters are correct. – Andrew Jul 25 '19 at 20:30