amin
amin

Reputation: 31

use more than a array in jquery post and get php result

i want to post many array to php page with jquery and get result but i cant give array in php page

Notice: Undefined index: $name

Notice: Undefined index: $type

Notice: Undefined index: $value

Notice: Undefined index: $size

the jquery code :

$('#ss').live('click', function () {
$("#main_login").html("<center>waiting plaese . . . .</center>");
    var name = [];
    var type = [];
    var size = [];
    var value = [];

    $(".name").each(function() {
        name.push($(this).val());
    });

    $(".type").each(function() {
        type.push($(this).val());
    });

    $(".size").each(function() {
        size.push($(this).val());
    });

    $(".value").each(function() {
        value.push($(this).val());
    });
    
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: "name[]="+name+"&type[]="+type+"&size[]="+size+"&value[]="+value,
        success: function (data) {
            $('#main_login').html(data);
            

        }
    });

the html code

<input type="text" class="name"  name="name[]" value="" />
<input type="text" class="value" name="value[]" value="" />
<input type="text" class="type"  name="type[]" value=""  />
<input type="text" class="size" name="size[]" value=""  /> 

<a href="#" id="ss">send</a>

the php code :

$name = $_POST['name'];
$size = $_POST['size'];
$value = $_POST['value'];
$type = $_POST['type'];

$names = array(
   'name' => '$name',
   'size' => '$size',
   'value' => '$value',
   'type' => '$type',
);

foreach( $names as $key => $n ) {
  echo "
  The name is ".$name[$key]."
  The size is ".$size[$key]."
  The type is ".$type[$key]."
  The value is ".$value[$key]."
  ";
}

Upvotes: 0

Views: 59

Answers (1)

trincot
trincot

Reputation: 350034

In the JavaScript part, this line in the ajax call is problematic:

data: "name[]="+name+"&type[]="+type+"&size[]="+size+"&value[]="+value,

You are concatenating arrays, which will be converted to comma-separated strings. This is not what you'd want (think of individual values that already have commas). Instead use object notation. jQuery will deal with it:

data: {
    name: name,
    type: type,
    size: size,
    value: value
}

Secondly, in PHP this code is problematic:

$names = array(
   'name' => '$name',
   'size' => '$size',
   'value' => '$value',
   'type' => '$type',
);

The single quotes around $name will just make it a literal string that is $name (not the variable, but the literal with $ ... etc).

But, besides that, the above associative array $names is not really helping you. I would just drop the whole statement, and continue like this (notice $name in singular):

foreach( $name as $key => $n ) {
   echo "
    The name is ".$name[$key]."
    The size is ".$size[$key]."
    The type is ".$type[$key]."
    The value is ".$value[$key]."
  ";
}

Upvotes: 2

Related Questions