开发者

Associative array passing as empty string

开发者 https://www.devze.com 2023-04-10 08:11 出处:网络
I am trying to pass an array to PHP via Ajax, but the array is being passed as an empty string. This is my code when creating the array:

I am trying to pass an array to PHP via Ajax, but the array is being passed as an empty string. This is my code when creating the array:

var params = new Array();
var inputs = new Array();
inputs = $(":input");
$.each(inputs, function(key, value) {
  params[value.id] = value.value;
});

alert(params);

Before that there are around 20 in开发者_开发知识库puts that look like this:

<input name="first_name" id="first_name" type="text" class="medium"/>
<input name="last_name" id="last_name" type="text" class="medium"/>

The alert(params) is just giving me an empty string. However, alert(params['first_name']) actually gives me the first_name input value.

Why isn't the array going through?


Can you try this -

$(document).ready(function() {
    var params = new Array();
    var inputs = $(":input");

    $.each(inputs, function(key, value) {
        //I guess the problem was that params is array and your id's were strings
        //array's elements are arr[0], arr[1],
        //not like arr[firstname], arr[lastname], ...
        params[value.id] = value.value;  
    });
    alert(params);
});
//moved everything inside $(document).ready

with this -

<input name="first_name" id="0" value="1" type="text" class="medium"/>
<input name="last_name" id="1" value="2" type="text" class="medium"/>

<!-- Changed id's from string to numbers. -->

Update:

Also, try this it might help you understand whats going on -

$(document).ready(function() {
    var params = {}; //use object instead of array
    var inputs = $(":input");

    $.each(inputs, function(key, value) {                       
        params[value.id] = value.value;
    });

    for(var prop in params) {
        alert(prop + " = " + params[prop]);
    }
});

Notice: params is an object now not an array.

With this -

<input name="first_name" id="firstname" value="Your first name." type="text" class="medium"/>
<input name="last_name" id="lastname" value="Your last name." type="text" class="medium"/>


You can't simply pass a variable to the server, you need to serialize it into name, value pairs, or use JSON.


I'm slightly unsure what you're trying to accomplish by creating an array in Javascript like this.

Your best bet is probably to use the JQuery command serialize then grab the data using $_GET

0

精彩评论

暂无评论...
验证码 换一张
取 消