Tom
Tom

Reputation: 2044

JQuery returning string not array, despite apparent logic of code...why?

I'm revising code written by another developer. Here he collects values and turns them from an array (dataId) into a comma-separated string:

$("#retrieve_works_form").on('submit', function(e) {
    e.preventDefault();
    $('#toggle_search_terms').trigger('click');
    var dataId = new Array();
    $('li.nw').each(function() {
        var thisDataId = $(this).attr('data-id');
        dataId.push(thisDataId);
    });
    $('li.added_gallery_item').each(function() {
        var thisDataId = $(this).attr('data-id');
        dataId.push(thisDataId);
    });
    $('#returned_gallery_work_ids').val(dataId.join(','));

The $_POST['returned_gallery_work_ids'] therefore holds a comma-separated string of the values in the dataId array. I want to revise this so it simply returns the array, with each element in a sequential index. I would think that doing this would do the trick:

$('#returned_gallery_work_ids').val(dataId);

...but it doesn't; it returns a comma-separate string of values, no different than what is returned when dataId.join(',') is the argument of the .val() operator.

There are really two questions here:

  1. Why is the result a comma-separated string in each case?
  2. How do I make it return the dataId array?

[The second question is the truly necessary question, but I want to understand the mechanics of what's taking place here.]

Upvotes: 1

Views: 228

Answers (1)

James Pederson
James Pederson

Reputation: 404

When storing a value of any kind in an input, it's stored as a string, so if you later retrieve it, you'll need to split it:

var galleryArray = $("#returned_gallery_work_ids").val().split(',');

Or in PHP on the server side, you'll use this:

$galleryArray = explode( ",", $_POST['returned_gallery_work_ids'] );

Hope this helps.

Upvotes: 1

Related Questions