-1

I have a form

<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>

<fieldset>
    <legend>User Details</legend>
        <div><label for="post[uname]">Username <em>*</em></label> <input id="post[uname]" type="text" name="uname" value=""  /></div>
            <p class='note' id='err[Name]'></p>

</fieldset>

 <div class="buttonrow">
    <input type="submit" value="Submit This Form via AJAX" class="button" />  
    <input type="button" value="Start Again" class="button" />
     <a href="ajaxformval.html">Refresh this Page</a>
</div>

</form>

I have two arrays post and err. I'm trying to send them to php and then in php it will json_encode the array and print it on the screen like so:

{
   "err": {
       "uname": "Please enter a user name"
   }
   "post": {
       "uname": ""
    }
}

or this is if the user did enter a name:

{
   "post": {
       "uname": "Bob Ross"
    }
}

There could be multiple fields for post and err but it should still follow the same suite.

How do I send the data to php, I understand it's some sort of serializeArray but it doesn't format it properly when I do:

JSON.stringify($("#ajax-form").serializeArray())

A jsfiddle to full html:

https://jsfiddle.net/dzv8ttjn/1/

9
  • 1
    And what is your question....? Commented Nov 24, 2016 at 22:45
  • @DelightedD0D updated original post. Commented Nov 24, 2016 at 22:48
  • Is this the only input, or does your actual html have a bunch of inputs? Commented Nov 24, 2016 at 22:50
  • No theres two text fields, 2 radio buttons and 2 checkboxes. I just included uname as an example. Commented Nov 24, 2016 at 22:52
  • Can you post the full html? Commented Nov 24, 2016 at 22:54

1 Answer 1

0

Your best bet is to call .serialize(); on the form which will give you something like: user-name=some%20name&email=some%20emale&gender=Female&interests=Software

Send that to the PHP script, and have the script create the format of the response while looping over the $_POST array. Something like the below would work:

(note that I've changed your id's to be more sensible and updated the jQuery version used)

<?php 
if(count($_POST)>0){
    $response = ['err'=>[], 'post'=>[]];
    foreach($_POST as $key => $value)
    {
        $response['post'][$key]=$value;
        if(trim($value) == '') $response['err'][$key]='Please enter a '.$key; 
    }
    echo json_encode($response);
  exit;
}
?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> Lab4: Form Validation with AJAX,JQuery,JSON and PHP</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">


    </script>
    <script type="text/javascript">
      $("#ajax-form").on('submit', function(event) {
            event.preventDefault();
            var dataString = $(this).serialize();
            $.ajax({
              type: "POST",
              // url: "page.php", // add this line to send to some page other than the this one
              data: dataString,
              success: function(response) {
                if (response) {
                  alert('test worked');
                }
              },
              error: function(xhr, status, error) {
                console.log(xhr);
              }
            });

        });
    </script>
  </head>

  <body>
    <div id="wrapper">

      <h2>Form Validation with AJAX,JQuery,JSON and PHP</h2>

      <div class="form-container">

        <span id="ajax-message"></span>

        <form id="ajax-form" onsubmit="return false;">
          <p class="legend">All fields marked with an asterisk are required.</p>

          <fieldset>
            <legend>User Details</legend>
            <div>
              <label for="uname">Username <em>*</em></label>
              <input id="uname" type="text" name="user-name" value="" />
              <p class='note' id='name-error'></p>
            </div>
            <div>
              <label for="password">Email Address <em>*</em></label>
              <input id="password" type="text" name="email" value="" />
              <p class='note' id='password-error'></p>
            </div>
            <div>
              <label for="post[gender]">Gender <em>*</em></label>
              <input type="radio" name="gender" value="Male" class="form-check-input" id="Male" required> Male
              <input type="radio" name="gender" value="Female" class="form-check-input" id="Female" required> Female
              <p class='note' id='gender-error'></p>
            </div>
            <div>
              <label for="interests">Interests<em>*</em></label>
              <input type="checkbox" name="interests" value="Music" class="form-check-input" id="Music"> Music
              <input type="checkbox" name="interests" value="Software" class="form-check-input" id="Software"> Software
              <input type="checkbox" name="interests" value="Hardware" class="form-check-input" id="Hardware"> Hardware</div>
          </fieldset>
          <div class="buttonrow">
            <input type="submit" value="Submit This Form via AJAX" class="button" />
            <input type="button" value="Start Again" class="button" />
            <a href="ajaxformval.html">Refresh this Page</a>
          </div>
        </form>
      </div>
      <h3>JSON Array</h3>
      <pre id='debug'></pre>
    </div>
  </body>

  </html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.