I am trying to display results from the process page on the host page. At the moment I keep getting the Uncaught ReferenceError: data is not defined error message. How do I go about fixing this?

form.php

$(document).ready(function () {
    // variable to hold request

    var request;
    // bind to the submit event of our form

    $("#commentForm").submit(function (event) {

        // abort any pending request
        if (request) {
            request.abort();
        }

        // setup some local variables
        var $form = $(this);

        // lets select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // serialize the data in the form
        var serializedData = $form.serialize();

        // lets disable the inputs for the duration of the ajax request
        $inputs.prop("disabled", true);

        // fire off the requestp
        var request = $.ajax({
            url: "process_msg.php",
            type: "post",
            data: serializedData
        });

        // callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR) {

            // log a message to the console
            console.log("Hooray, it worked!");

            // flash update text
            $("#flashmessage").html(data)
        });

        // callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown) {

            // log the error to the console
            console.error(

                "The following error occured: " + textStatus, errorThrown);
        });

        // callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {

            // reenable the inputs
            $inputs.prop("disabled", false);
        });

        // prevent default posting of form
        event.preventDefault();
    });
});

<form id="commentForm">
    <textarea maxlength="255" placeholder="What's on your mind?" id="post_box"
    style="font-family: Verdana; border-color: #dedede" name="msg"></textarea>
    <br />
    <input type="hidden" name="user_id" value="<? echo $loggedin_id; ?>" />
    <input type="submit" id="post_btn" style="display: none" value="Post"
    />
</form>
<div id='flashmessage'></div>

process_msg.php

<?php
require_once("../resources/php/connection.php");
$msg = $_POST["msg"];
$user_id = $_POST["user_id"];
?>

<div id="flashmessage">
<?php echo $msg; ?>

</div>

Dani AI

Generated

You are getting that ReferenceError because your .done() callback names the first parameter response, but you later use data. In jQuery, the first argument passed to .done() (or success) is the response payload, so either rename the parameter to data or use response consistently. Also consider writing into the target with .text() unless you intentionally return trusted HTML. jQuery’s docs show the callback arguments and warn about using .html() with untrusted input. (api.jquery.com)

There is a second, easy-to-miss bug: request aborting will not work as written because var request is declared again inside the submit handler, which shadows the outer request due to var hoisting. Remove the inner var so both submits share the same variable. (developer.mozilla.org)

Here is a minimal, safe pattern you can drop in:

let pending; // shared across submits
$("#commentForm").on("submit", function (e) {
  e.preventDefault(); // stop the native submit
  if (pending) pending.abort();

  const $form = $(this);
  const $inputs = $form.find("input, select, button, textarea").prop("disabled", true);

  pending = $.ajax({
    url: "process_msg.php",
    type: "POST",
    data: $form.serialize()
  })
  .done(function (data) {
    $("#flashmessage").text(data); // use .html(...) only for trusted markup
  })
  .fail(function (jqXHR, textStatus) {
    console.error("Request failed:", textStatus);
  })
  .always(function () {
    $inputs.prop("disabled", false);
  });
});

On the server, return only the message content (or JSON) and do not echo a second element with id="flashmessage"; IDs must be unique in the DOM. For plain text, echo an escaped string (e.g., htmlspecialchars) rather than wrapping it in another div. (api.jquery.com)

Tip: Call preventDefault() at the start of the handler to avoid the browser’s normal form post racing your Ajax call. (developer.mozilla.org)

Member Avatar for Member #949455

@jeansymolanza

Uncaught ReferenceError: data is not defined error message.

Line 40:

 $("#flashmessage").html(data)

You didn't define flashmessage so that's why the error messages appear when you ran the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.