-2

I want to send an get data from this way and creat input whit this jquery and post to php page and get result but the problem is :

Warning: Invalid argument supplied for foreach() in

jQuery

$('#ss').live('click', function () {
    $("#main_login").html("<center>waiting plaese . . . .</center>");
    var arr = $("#myInputs").val();
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: "myInputs=" + arr,
        success: function (data) {
            $('#main_login').html(data)
        }

    });
});


$(function () {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;


    $('#text').live('click', function () {
        $('<p><input type="text" id="myInputs" size="20" name="myInputs[]" value="" placeholder="Input Value" /> <a href="#" id="rtext">Remove</a></p>').appendTo(scntDiv);
        i++;
        return false;
    });
});

HTML

<a href="#" id="text">add</a><br>

<div id="p_scents">
    <p><label for="p_scnts"><input type="text" id="myInputs[]" size="20" name="myInputs[]" value="" placeholder="Input Value" /></label></p>
<div id="main_login"></div>

php

$name = $_POST['myInputs'];
foreach( $name as $key => $n ) {
    print "The name is ".$n." and email is , thank you<br>";
}
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
amin
  • 31
  • 7

1 Answers1

1

The issue is with your javascript, not the PHP. These lines:

var arr = $("#myInputs").val();
[...]
    data: "myInputs=" + arr,

Problems

  1. Because you're using a CSS ID selector you're only allowed one element with that ID
  2. $("#myInputs").val() will only return the value of the first element, and it will be a string, not an array
  3. "myInputs=" + arr will send the POST data as a string, not an array

Solutions

You need to do a couple things to fix these issues:

  1. Switch id='myInputs[]' to use a CSS class (i.e. class='myInputs')
  2. Pull all values from the .myInputs elements and combine them in an array (hint: use jQuery's .each function)
  3. Change "myInputs=" to array format (i.e. { "myInputs[]" : arr })

Let me show you:

HTML

    <p><label for="p_scnts"><input type="text" class="myInputs" size="20" name="myInputs[]" value="" placeholder="Input Value" /></label></p>

Javascript

$('#ss').live('click', function () {
    $("#main_login").html("<center>waiting plaese . . . .</center>");
    var arr = [];
    $(".myInputs").each(function() {
        arr.push($(this).val());
    });

    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: { "myInputs[]" : arr },
        success: function (data) {
            $('#main_login').html(data)
        }
    });
});
Skrat
  • 577
  • 2
  • 15