rhill45
rhill45

Reputation: 569

Parse json data with JS being received from php

My form:

          <form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
        <div class="form-group">
          <input type="email" name="email" class="form-control" placeholder="Email address">
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
        </div>
      </form>

the end of my php script

$response = array(
    "status" => $status,
    "message" => $message
);

echo json_encode($response);

My page is receiving data like:

{"status":0,"message":"This email is already on list!"}

using JS I need to parse that data and then update text within an element.

 <span id="notice">Get notified!</span>

here's my script which doesn't work, after senging form data to my php script I get a white screen that shows the json strong

    $(document).ready(function() {
      $.ajax({
      dataType: 'json',
        $('#notice').text(data.message);
      });
    });

Upvotes: 0

Views: 31

Answers (3)

Pascal Boutin
Pascal Boutin

Reputation: 1264

You have to handle the response in a callback.

$(document).ready(function() {
    $('form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
          data: $(this).serialize(),
          url: $(this).attr('action'), // Or the path of the PHP file
          dataType: 'json',
        }).done(function(response) {
          $('#notice').text(response.message);
        });
    });
});

See the related docs here

Upvotes: 1

Patrick Evans
Patrick Evans

Reputation: 42736

Your code as is, is just executing at page load and not on submission of a form. You need to attach an onsubmit event, prevent the default action of doing the form submit and do your ajax call in there. Also your ajax call itself was malformed

$("#yourFormID").submit(function(e){
    e.preventDefault();
    $.ajax({
       url:"/urlToServerScript",
       data:{} //any form data the script needs you should be put here,
       dataType:"json" //type of response the server will output
    }).then(function(data){
       $('#notice').text(data.message);
    });
});

Upvotes: 1

taxicala
taxicala

Reputation: 21759

That ajax call is not well formed, missing success callback and url e.g:

$(document).ready(function () {
    $.ajax({
        url: '/the/url/where/your/data/comes/from/',
        dataType: 'json',
        success: function (data) {
            $('#notice').text(data.message);
        }
    });
});

Upvotes: 1

Related Questions