0

I am trying to decode a json string by using JSON.parse() however, I don't know exactly where to place the code as I'm not that familiar with JSON/Jquery.

This is the JS part:

 /* ----------------------------------------------------------- */
   /*  Contact form
   /* ----------------------------------------------------------- */

   $('#contact-form').submit(function(){

      var $form = $(this),
         $error = $form.find('.error-container'),
         action  = $form.attr('action');

      $error.slideUp(750, function() {
         $error.hide();

         var $name = $form.find('.form-control-name'),
            $email = $form.find('.form-control-email'),
            $phone = $form.find('.form-control-phone'),
            $message = $form.find('.form-control-message');

         $.post(action, {
               name: $name.val(),
               email: $email.val(),
               phone: $phone.val(),
               message: $message.val()
            },
            function(data){
               $error.html(data);
               $error.slideDown('slow');

               if (data.match('success') != null) {
                  $name.val('');
                  $email.val('');
                  $phone.val('');
                  $message.val('');
               }
            }
         );

      });

      return false;

   });

The relevant part of my mailscript:

if($isValid == true) {
        $result["submit_message"] = _msg_send_ok;
    } else {
        $result["submit_message"] = _msg_send_error;
    }
        if($_POST["name"]=="" || $_POST["name"]==_def_name)
            $result["error_name"] = _msg_invalid_data_name;
        if($_POST["email"]=="" || $_POST["email"]==_def_email || !preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"]))
            $result["error_email"] = _msg_invalid_data_email;
        if($_POST["message"]=="" || $_POST["message"]==_def_message)
            $result["error_message"] = _msg_invalid_data_message;   

    $result['isValid'] = $isValid;

    echo json_encode($result);

This outputs the following: {"submit_message":"Bedankt voor uw bericht!","isValid":true}

How can I make sure it only shows the submit_message part in the Json string?

twan
  • 2,450
  • 10
  • 32
  • 92
  • 1
    If you set your `$.post` datatype to JSON you wouldn't need to decode it at all. jQuery would do that for you. Check [jQuery.post](http://api.jquery.com/jQuery.post/) – apokryfos May 12 '16 at 08:26
  • 1
    Possible duplicate of [JQuery Parsing JSON array](http://stackoverflow.com/questions/10463131/jquery-parsing-json-array) – Regis Portalez May 12 '16 at 08:33

1 Answers1

0

If what you want is to display the submit message in $error.html(data) then all you need to do is replace it with $error.html(data.submit_message) as jQuery automatically parses the json from the data variable into a object.