0

i'm trying to send a form inputs as array to a php script

function submit_form(){
    var arr  =  [];
    var key, val ;
    $('#form input').each(function(){

        key = $(this).attr('id');
        val = $(this).val();
        arr[key] = val;

    })
    alert(arr['username']); // check to see if array is not empty

    var jsondata =  JSON.stringify(arr); 

    $.post(base_url+'profile/edit_profile/<?php echo $profile_username; ?>' , {data : jsondata }, function(){
    })
}

on the php script

$data =  json_decode($_post['data']);
var_dump($data);
exit;

and here is the result

array (size=0)
  empty
1
  • Have you tried turning {data: ...} into {"data": ...}? Commented Jul 21, 2012 at 19:10

2 Answers 2

3

You're using an Array when you should be using an Object.

var obj = {};
var key, val ;
$('#form input').each(function(){

    key = $(this).attr('id');
    val = $(this).val();
    obj[key] = val;

});

JSON methods will ignore non-numeric properties of Arrays.


Although instead of using id attributes, use name, and then use .serialize().

var data = $('#form input').serialize();
Sign up to request clarification or add additional context in comments.

2 Comments

thanx , i thought using serialize whould give me a string of "k&v" pears and it used for GET method ?
@max: If you want an object structure, you can use serializeArray(), which will give you an array of objects.
0

This needs basic debugging first. Before you decode the data, dump it so you do ensure that the data is correct:

$data =  $this->input->post('data');
var_dump($data);
$array = json_decode($data);
var_dump($array);
exit;

Lessons to learn:

  • Do one step after the other. The more stupid the better.
  • Before and after each step, verify the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.