Tyler Hughes
Tyler Hughes

Reputation: 602

Javascript/Ajax/Json: Sending objects and arrays

I have a form where people enter their clients into.

This form allows the user to add as many phone numbers, emails, and addresses as they want.

Phone and email have type and data fields for each added row (phone_type, phone_data) while Address has type, street, city, state, and zip fields for each row (address_type, address_street, address_city, address_state, address_zip).

So for example, when the user adds a phone field it adds:

<input type="text" name="phone_type[]" />
<input type="text" name="phone_data[]" />

I need to send the form data over Ajax to a PHP to process and store in database.

I've thought of storing it in array within an object.

phone = new Object();
var phone.data = new Array(), 
phone.type = new Array();
$("input[name='phone_data[]']").each(function() {
  if($(this).val() != '') {
  phone.data.push($(this).val());
  phone.type.push($('select[name="phone_type[]"]').val());
})

This doesn't seem to work. Am I even approaching this correctly?

Also, once I get it into an object that I send over Ajax to a PHP page, how do I grab the values?

Upvotes: 0

Views: 453

Answers (3)

samazi
samazi

Reputation: 1171

You can most definitely use jQuery serialize(). In your event which triggers the processing you can do the following:

$.ajax({  
    type: "POST",  
    url: "your_php_processing_page.php",  
    data: $("#FormID").serialize(),  
    dataType: "json",  
    success: function(data){
        // do stuff here
    },  
    error: function() {  
        // do stuff here             
    }  
});

In your_php_processing_page.php you can get the values as follows:

$phone_types = $_POST["phone_type"];
$phone_data = $_POST["phone_data"];

Upvotes: 1

bipen
bipen

Reputation: 36531

serialize your form... use data of ajax to sent the serialize data to the server...

 data:$('#YourFORMID').serialize();

here is the documentaiotn have alook to the examples...

http://api.jquery.com/jQuery.post/

and to grab the data in your PHP (if you are using ajax type as post)

 $data=$_POST['phone_data'];
 $type=$_POST['phone_type'];

if ajax type : GET

 $data=$_GET['phone_data'];
 $type=$_GET['phone_type'];

Upvotes: 3

epascarello
epascarello

Reputation: 207501

Are you trying to reinvent jQuery's serialize()

var frm = $("#myForm");
var values = frm.serialize();

//make Ajax call
$.post("someUrl", values, function(){} );

http://jsfiddle.net/BZcja/

Upvotes: 1

Related Questions