2 Replies - 1151 Views - Last Post: 31 August 2012 - 03:55 AM

#1 andreea115  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 30-August 12

how do i serilize a form so that it may be sent by JSON via AJAX to PH

Posted 30 August 2012 - 08:56 PM

Hello everyone.

i am new to jquery and have no idea how to resolve this problem.

i want to "serilize" a user registration form so that i may send the data in JSON FORMAT via AJAX to a php script.

i understand that the .serilize() function will not work as the data must be put into an array for correct JSON FORMATTING.

i have looked online for advice/tutorials on the correct way to serilize a form for JSON SENDING but cannot find anything. so any adivice /pointing me in teh right directions for online tutorials on this will be greatly appriciated.


i have tried the following below but it did not work. does anyone have the correct plugin or can anyone advice me on the correct way to do it.
if it will help i will show you below waht i have done so far


//the first part is my document ready . i.e where i receive the form data, validate it and then attempt to send it to Json.


 $(document).ready(function() {


//START THE FUNCTION FOR THE SUBMISSION OF REGISTATION FORM TO THE DATABASE VIA AJAX

$('form #response').hide();

$('#submit').click(function(e) {

    // prevent forms default action until
    // error check has been performed
    e.preventDefault();

    // grab form field values
    var valid = '';
    var required = ' is required.';
    var name = $('form #name').val();
    var email = $('form #email').val();
    var cat = $('form #cat option:selected').val();
    var location = $('form #country_loc option:selected').val();
    var honeypot = $('form #honeypot').val();
    var humancheck = $('form #humancheck').val();

    // perform error checking
    if (name = '' || name.length <= 2   ||  name == 'name*'   ) {
        valid = '<p>Your name' + required +'</p>';  
    }

    if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
        valid += '<p>Your email' + required +'</p>';                                                  
    }

    if (cat = '' || cat.length < 1) {
        valid += '<p>Please tell us whether you are;  seeking work or  looking for a careworker' + required + '</p>';  
    }


if (location = '' || location.length < 1) {
        valid += '<p>Please tell us your current location' + required + '</p>';
    }

    if (honeypot != 'http://') {
        valid += '<p>Spambots are not allowed.</p>';    
    }

    if (humancheck != '') {
        valid += '<p>A human user' + required + '</p>';
    }

    // let the user know if there are erros with the form
    if (valid != '') {

        $('form #response').removeClass().addClass('error')
            .html('<strong>Please correct the errors below.</strong>' +valid).fadeIn('fast');          

    }
    // let the user know something is happening behind the scenes
    // serialize the form data and send to our ajax function
    else {

        $('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');                                      
         

        // the above works perfectly. its from below onwards that i am having problem.
        // i am now attempting to send the data via JSON TO A PHP SCRIPT  
        var formData = $('form').serializeFormJSON();
        submitForm(formData);          
    }          

});


//END THE FUNCTION FOR THE SUBMISSION OF REGISTATION FORM TO THE DATABASE VIA AJAX

  });//end ready fucntion.





YOU WILL NOTE ABOVE THAT I SENT THE DATA VIA A JSON PLUGIN. I WILL NOW ENCLOSE THAT PLUGIN BELOW.

//START OF FUNCTIONS TO SERILIZE THE FORM SO THAT IT MAY BE SUBMITTED BY JSON.  
            (function($) {
        $.fn.serializeFormJSON = 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;
        };
        })(jQuery);





FINALLY, I NOW ENCLOSE THE AJAX SCRIPT THAT SHOULD RECEIVE THE DATA AND SEND IT ON TO THE PHP SCRIPT.


$.ajax({    
    type: 'POST',
    url: 'cms/index.php?view=joint_reg',        
    data: formData,
    dataType: 'json',
    cache: false,
    timeout: 7000,
    success: function(data) {           

        $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
                    .html(data.msg).fadeIn('fast'); 

        if ($('form #response').hasClass('success')) {

            setTimeout("$('form #response').fadeOut('fast')", 5000);
        }

    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {

        $('form #response').removeClass().addClass('error')
                    .html('<p>There was an<strong> ' + errorThrown +
                          '</strong> error due to a<strong> ' + textStatus +
                          '</strong> condition.</p>').fadeIn('fast');           
    },              
    complete: function(XMLHttpRequest, status) {            

        $('form')[0].reset();
    }
}); 
};//END SUBMIT FORM VIA AJAX, USING JSON






i would really appriciate any advice or help on this matter.

warm regards

Andreea

Is This A Good Question/Topic? 0
  • +

Replies To: how do i serilize a form so that it may be sent by JSON via AJAX to PH

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6066
  • View blog
  • Posts: 23,526
  • Joined: 23-August 08

Re: how do i serilize a form so that it may be sent by JSON via AJAX to PH

Posted 31 August 2012 - 02:56 AM

Why did you ignore the response you received 5 days ago here?
Was This Post Helpful? 0
  • +
  • -

#3 andreea115  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 30-August 12

Re: how do i serilize a form so that it may be sent by JSON via AJAX to PH

Posted 31 August 2012 - 03:55 AM

ah.

hello again everyone and speacial thanks to JackOfAllTrades.

i did not see the reply. i will have a look at it now. thank you for pointing that out to me.

warm regards

andreea
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1