1

I am very new to ajax.

What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.

After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.

My problem is that after adding this part, I am no more able to submitting the form!

Can anyone please let me know what am I doing wrong here? I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.

Thank you in advance.

AJAX:

var form = $('#contact-form');


var formMessages = $('#form-messages');


form.submit(function(event) {

        event.preventDefault();

        var formData = form.serialize();

        $.ajax({
            type:     'POST',
            url:      form.attr('action'),
            data:     formData,
            dataType: 'json', //after adding this part, can't anymore submit the form
            success:  function(data){

               var message_status = data.message_status;
               var duplicate      = data.duplicate;
               var number         = data.ref_number;
               //Do other stuff here
               alert(number+duplicate+number);

           }
        })
});

PHP:

//other code here

$arr = array(
  'message_status'=>$message_status,
  'duplicate'=>$duplicate,
  'ref_number'=>$ref_number
);
echo json_encode($arr);
Mazen
  • 171
  • 4
  • 14

2 Answers2

0

The way you have specified the form method is incorrect. change

 type:     'POST',

to

 method:     'POST',

And give that a try. Can you log your response and post it here ? Also, check your console for any errors.

Angad
  • 69
  • 3
0

If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).

You have to prepare data as json object :

Here is the extension function you can add:

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

Credit goes to : Difference between serialize and serializeObject jquery

Community
  • 1
  • 1
Mahesh Chavda
  • 593
  • 3
  • 9