0

I am a noob and trying to find out what's wrong with my code, I am trying to recieve some data from php handler for using it in my JavaScript code. When I test project on local server, it works perfect, but when I upload it to hosting, I have strange error in DevTools:

Uncaught SyntaxError: Unexpected token '<', "<br />
<b>"... is not valid JSON
    at JSON.parse (<anonymous>)
    at req.onload ((index):491:18)

((index):491:18) is referring to dot after JSON in line json = JSON.parse(this.response); in my JavaScript code:

<script>
    function send(event, php){
    console.log("Sending request");
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
    var req = new XMLHttpRequest();
    req.open('POST', php, true);
    req.onload = function() {
        if (req.status >= 200 && req.status < 400) {
        json = JSON.parse(this.response);
        console.log(json);
            
            if (json.result == "success") {
                function showw() {
                    document.getElementById("topLayer").removeAttribute("style","display: none");
                    document.getElementById("topLayer").setAttribute("style","animation: 300ms show ease-in;");
                    document.getElementById("name").value = "";
                    document.getElementById("phone").value = "";
                    document.getElementById("message").value = "";
                }
                
                function hideTopLayer() {
                    document.getElementById("topLayer").setAttribute("style","animation: 300ms hide ease-out;");
                    return true;
                }
                    showw()
                    setTimeout (hideTopLayer, 5000);
                    function hidee() {
                        document.getElementById("topLayer").setAttribute("style","display: none");
                    }
                    setTimeout (hidee, 5200);
            } else {
                alert("Error. Message not sent");
            }
        } else {alert("Server error. Number: "+req.status);}}; 
    
    req.onerror = function() {alert("Request sending error");};
    req.send(new FormData(event.target));
    }
    </script>

My PHP code:

<?php
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
require 'phpmailer/Exception.php';
$name = $_POST['name'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$title = "Callback request";
    $body = "
    <h2>Call me!</h2>
    <b>Name:</b> $name<br>
    <b>Phone:</b> $phone<br><br>
    <b>Message:</b><br>$message
    ";
$mail = new PHPMailer\PHPMailer\PHPMailer();
try {
    $mail->isSMTP();   
    $mail->CharSet = "UTF-8";
    $mail->SMTPAuth   = true;
    //$mail->SMTPDebug = 2;
    $mail->Debugoutput = function($str, $level) {$GLOBALS['status'][] = $str;};
    $mail->Host       = 'smtp.******.**';
    $mail->Username   = '***********';
    $mail->Password   = '*************';
    $mail->SMTPSecure = 'ssl';
    $mail->Port       = 465;
    $mail->setFrom('username@mailservice.com', 'User Name');
 
    $mail->addAddress('**********@******.**');  
    $mail->addAddress('******@*********.**');
$mail->isHTML(true);
$mail->Subject = $title;
$mail->Body = $body;    

if ($mail->send()) {$result = "success";} 
else {$result = "error";}

} catch (Exception $e) {
    $result = "error";
    $status = "Message not sent. Error cause: {$mail->ErrorInfo}";
}

echo json_encode(["result" => $result, "resultfile" => $rfile, "status" => $status]);
?>

UPD: content in Response from DevTools Network tab:

<br />
<b>Notice</b>:  Undefined variable: rfile in <b>/home/********/***********.**/docs/form2.php</b> on line <b>51</b><br />
<br />
<b>Notice</b>:  Undefined variable: status in <b>/home/********/***********.**/docs/form2.php</b> on line <b>51</b><br />
{"result":"success","resultfile":null,"status":null}

As you can see it's a callback request form made using PHPMailer. All works fine, mails are send correctly, but I can't receive "success" status from JSON to make a pop-up window over the form which notifies users that message is sent. For local server I use OpenServer bundle with default settings and all works perfect, but hosting service support said that problem is in my code pls help D:

  • It seems that the response you are receiving is not JSON but HTML; to better identify the problem, it would be useful to see the response content shown in the "network" tab of the DevTool – obiTheOne Aug 11 '22 at 09:58
  • @obiTheOne updated post with this data – awrengee Aug 11 '22 at 10:03
  • You never define `$rfile` anywhere, but are still trying to read it in your last `json_encode()`. And you only define `$status` inside your `catch()`-block, which means that `$status` will be undefined if no exception was thrown and caught. If you get an "undefined variable" warning, _always_ start by making sure the variable is defined in the context it's used. – M. Eriksson Aug 11 '22 at 10:17

0 Answers0