Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array in database:

a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}

So I unserialize with php and then encode it with json, code looks like following:

$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');

print_r ($unwp);

echo json_encode($unwp);

I get this on the page:

Array ( [1] => 1993 [2] => 1994 [3] => 1995 [4] => 1996 ) {"1":"1993","2":"1994","3":"1995","4":"1996"}

I need to loop it somehow with jQuery? so i can get 1993,1994,1995,1996 and so on.

I was testing jQuery.getJSON(), but cant figure out how exactly to use it?

All code together on the page:

<?php
   $array = $_POST['inputarray'];
   $str = serialize($array);
   print $str . "\n";
   $unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
   print_r ($unwp);
   echo json_encode($unwp);
?>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script>

   jQuery(function ($) {

    // Add children input fields
    var childBlock = $('.block');
    var countChildren = $('div.block div.row').size() + 1;
    $('#addChild').live('click', function (e) {
        e.preventDefault;
        $('<div class="row"><input type="text" name="inputarray['+countChildren+']" id="inputarray'+countChildren+'" placeholder="inputarray['+countChildren+']"><a href="javascript://" id="deleteChild">Delete</a></div>').appendTo(childBlock);
        countChildren++;
    });
    $('#deleteChild').live('click', function (e) {
        e.preventDefault();
        if (countChildren > 2) {
            $(this).parents('div.row').remove();
            countChildren--;
            var counter = 1;
            $('input[name^="inputarray"]').each(function () {
                $(this).attr('name', 'inputarray[' + counter + ']');
                $(this).attr('placeholder', 'inputarray[' + counter + ']');
                $(this).attr('id', 'inputarray' + counter);
                counter++;
            });

        }
    });
})(jQuery);

</script>



   <form action="" method="post">
      <div class="block">
         <div class="row"><input type="text" name="inputarray[1]" placeholder="inputarray[1]"></div>
         <input type="hidden" value="<?php echo $str; ?>">
      </div>
      <input type="submit">
   </form>


<a href="javascript://" id="addChild">Add a child</a>

Thank you!

share|improve this question
1  
Why loop with jquery when you already have the result there, with you in the php script? Could you be more clear so we can understand the motive behind it please. –  Darren Aug 5 '14 at 7:34
2  
If this something you're writing now, you shouldn't use the migrate plugin and still be using live, you should just move to on. Also, you should be using length not size(). Thirdly, are you just echoing the JSON on the page, and could you just echo it to a javascript variable, or do you really need to get it with ajax ? –  adeneo Aug 5 '14 at 7:35
    
I have a project where I can create unlimited dynamic text fields. Then get all the data from it, store it into database. Then get all the results from this array in database, so i can get something like: Has 4 children (1993,1994,1995,1996). –  Alex Chizhov Aug 5 '14 at 7:39

3 Answers 3

up vote 1 down vote accepted

This could be done easily in PHP. Since I don't see any handlers for submit() or click() or anything that could suggest an ajax request.

And you also have the php in the same file, so why not simply loop with PHP and produce what you need?

echo "<select name='year'>";
foreach($unwp as $year) {
    echo "<option value='{$year}'>{$year}</option>";
}
echo "</select>";

The above snippet will product exactly what you need.

Example


Edit

You're trying to generate a <select> right? If not, let me know so I can modify as required.

share|improve this answer
    
I modified it already like that: foreach($unwp as $year){$countYears++;echo $year . ', ';}. How do i remove comma after the last value in the array? –  Alex Chizhov Aug 5 '14 at 8:57
    
@AlexChizhov who not just do echo implode(',', $unwp); ? –  Darren Aug 5 '14 at 8:58
1  
That works just great! thank you :) –  Alex Chizhov Aug 5 '14 at 9:06

Use $.getJSON like this:

$.getJSON("scriptname.php", function(data) {
    html = '';
    $.each(data, function(i, el) {
        html += '<div class="block">' +
            '<div class="row"><input type="text" name="inputarray['+i+']" placeholder="inputarray['+i+']"></div>' +
            '<input type="hidden" value="'+el+'">');
    });
    $("form > div").delete();
    $("form").prepend(html);
});
share|improve this answer
    
and how do i use it if script is in the same file? –  Alex Chizhov Aug 5 '14 at 7:52
    
I thought you wanted to add the inputs dynamically. If the script is in the same file, you can just write a PHP loop, you don't need to do it in jQuery. –  Barmar Aug 5 '14 at 7:54
    
now im supper confused myself :) how do i loop it with php then? –  Alex Chizhov Aug 5 '14 at 7:57
    
foreach ($unwp as $i => $value) { echo ... } –  Barmar Aug 5 '14 at 7:59

I would change

echo json_encode($unwp);

to

echo "<script> var fromPhP = ".json_encode($unwp). "</script>;

in this way you get json in variable and I saw you are using jquery so i would use $.each to loop it:

$.each(fromPhP ,function(index,item){
    console.log(index,item);
});
share|improve this answer
    
You've almost got it. change that to var fromPHP = $.getJSON('".json_encode ... In your example that will not compile (because no ' around the string), the fromPHP var would only contain a JSON string. –  Morg. Aug 5 '14 at 7:49
    
It will work, it's not passing string to fromPhp it's passing object so getJSON is unnecessary –  Michał Fraś Aug 5 '14 at 8:01
    
My mistake. It makes so little sense to take that route (<script php echo) I had not even realized :) –  Morg. Aug 5 '14 at 8:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.