I have a form that is a
chat apps am building
for project. Now
everything seems to be
working fine to best of
my ability.
Now i want to submit
the data from the form
into my php script
without any form of
reload. That means i
don't want redirection
to the action page and
back to the chat page.
What i want is for the
page to submit the
form at the background.
And i know i need ajax
to this bt i cnt get it
right. Here is my form

<form method="post"
id='chatbox'
action="reply.php">
<input type="text"
id="text"
name="adchat"/>
<input type='hidden'
id='user_id' name='id'
value='1'>
<input type='hidden'
id='user_name' name='id'
value='Ben'>
<input type='submit'
id='submit' name='chat'
value='send'></form>
What i need is an ajax
code to submit d
variable to the reply.php
scrit and maybe a
message to display
when the form it been
submitted say
something like
(sending...). Thanks for
assiting

Dani AI

Generated

Two quick fixes first: — the hidden fields in the original form both use name="id", so one value will overwrite the other. Give each input a distinct name (for example user_id and user_name) and do not trust those values for authentication — verify the active user on the server (session or token). ’s jQuery prototype is a solid approach; below is a lightweight, modern alternative using the Fetch API plus server-side tips.

Corrected form (adds a small status element for feedback):

<form id="chatbox" method="post" action="reply.php">
  <input type="text" id="adchat" name="adchat" placeholder="Type message" />
  <input type="hidden" id="user_id" name="user_id" value="1" />
  <input type="hidden" id="user_name" name="user_name" value="Ben" />
  <input type="submit" value="Send" />
  <span id="sendStatus" aria-live="polite"></span>
</form>

Minimal vanilla-JS submit (prevents reload, shows "sending...", handles JSON response and appends the sent message to a chat list):

document.getElementById('chatbox').addEventListener('submit', async function(e) {
  e.preventDefault();
  const form = e.target;
  const status = document.getElementById('sendStatus');
  const btn = form.querySelector('[type="submit"]');
  btn.disabled = true;
  status.textContent = 'sending...';
  const formData = new FormData(form);

  try {
    const res = await fetch(form.action, { method: 'POST', body: formData, headers: { 'Accept': 'application/json' } });
    if (!res.ok) throw new Error(res.statusText);
    const json = await res.json();

    if (json.success) {
      const list = document.getElementById('chatList'); // assume a <ul id="chatList"> exists
      const li = document.createElement('li');
      li.textContent = json.chat.user_name + ': ' + json.chat.text;
      list.appendChild(li);
      form.reset();
      status.textContent = '';
    } else {
      status.textContent = json.message || 'Server error';
    }
  } catch (err) {
    status.textContent = 'Network error';
    console.error(err);
  } finally {
    btn.disabled = false;
  }
});

Server-side outline (reply.php): return JSON, validate and sanitize POST, verify session user, use proper HTTP codes. Never accept hidden user_id as proof of identity. Escape content when inserting into the database and when rendering back into the DOM (or use textContent so the browser does not interpret HTML). For debugging, inspect the Network tab to confirm the POST reaches reply.php and that the response has Content-Type: application/json.

Hi,

I will provide prototype example: Form Code

<form name="frmcontact" id="frmcontact" method="post">
  <p>First Name:
    <input name="fname" type="text" id="fname" placeholder="First Name" />
  </p>
  <p>Last Name:
    <input name="lname" type="text" id="lname" placeholder ="Last Name" />
  </p>
  <p>Email:
    <input name="email" type="text" id="email" placeholder="Email" />
  </p>
  <p>Comment:
    <textarea name="comments" id="comments" placeholder="Comments" class="txtarea"></textarea>
  </p>
  <a href="javascript:void(0);" id="submit" class="btn1 left">Submit</a>
</form>

Javascript function to submit form:

<script type="text/javascript">
$(document).ready(function() {
    $("#submit").click( function() {
        //alert('New Registration');

        var url = 'formpost.php';
        var frmdata = $("#frmcontact").serialize() ;
        $.ajax({
            url: url,
            dataType: 'json',
            type: 'POST',
            data: frmdata,
            success: function(response) {
                    alert(response); // For test
                    if( response.status == 'Y' ) {
                        $("#div_form").html('<h2>Your request is submitted successfully./h2>');

                    }
                    else {
                        $("#div_form").html('<h2>Error in process. Please try later.</h2>');
                    }
                }   
        });

    });


/*** End document ready **/
});
</script>

Sample of formpost.php

<?php
$response = array();
// Do some Mail Procedure

If mail( .. ) {
    $response['status'] = 'Y';
}
else {
    $response['status'] = 'N';
}

die(json_encode($response));
?>

Please Note:

  1. All input fields have ID and Name (Required)
  2. <form> did not require action tag
  3. Did not use submit button. (Submit button try submit the form as a result page get refresh.
  4. var frmdata = $("#frmcontact").serialize() get all from data have name=>value pair
  5. Please include jQuery.

Please check and let me know.
Thanks,
Ajay

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.