jonjon
jonjon

Reputation: 121

use jQuery to send javascript array to php

I'm trying to pass javascript array to php using ajax and jQuery.

I have simple page that contains a series of numbers that I've made selectable via jQuery UI (see below) When I select a group of numbers, I use array.push to add those numbers to an array called "shift". Here's the question: What's the simplest way to send this array to PHP? Will it remain an array after it comes over? I'm new to coding and would appreciate any help I can get. After a lot of research, here's what I've tried. Oh, I've managed to figure out how to submit the form to PHP, it's the jQuery UI array that i'm stuck on.

example. 9, 1, and 3 have been selected

here's my main.php

<!DOCTYPE html>
<html>
<head>

    <title>test</title>


<link rel="stylesheet" type="text/css" href="main.css">

</head>

<body>
<div class = "container">
<form action="post.php" method="post" id="add">
<input type="text" class="leader" name="name" placeholder="Leader">
<input type="text" class="date" name="date" placeholder="date">
<input type="text" class="time" name="time" placeholder="time">
<input type="text" class="score" name="score" placeholder="score">
<input type="submit" id="btn" value="send" />
</form>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4.custom.js"></script>
<script src="globe.js"></script>


<ul id ="hours_zoned">
    <li class="nine">9</li>
    <li class="ten">10</li>
    <li class="eleven">11</li>
    <li class="twelve">12</li>
    <li class="one">1</li>
    <li class="two">2</li>
    <li class="three">3</li>
    <li class="four">4</li>
    <li class="five">5</li>
    <li class="six">6</li>
    <li class="seven">7</li>
    <li class="eight">8</li>
    <li class="nine">9</li>
</ul>
</div>  




</body>
</html>

here's my post.php

 <html>
    <body>


 /* I'm using all of these echoes to verify that the data is coming
 over. Only "shift" fails to come over */

    NAME <?php echo $_POST["name"]; ?><br>
    DATE <?php echo $_POST["date"]; ?><br>
    TIME <?php echo $_POST["time"]; ?><br>
    SCORE: <?php echo $_POST["score"]; ?><br>

    SHIFT: <?php echo $_POST["shift"]; ?> 

    <?php 

    include("db.php");

    $name = $_POST["name"];
    $date = $_POST["date"]; 
    $time = $_POST["time"];



    $query = "INSERT INTO leaders (name, shift_date, shift_time)  VALUES ('$name', '$date', '$time')";     
    $result = $db->query($query);



     ?>

    </body>
    </html>

here is my globe.js

var shift = []; //create array to store zoned hours

    $(function() {
        $( "#hours_zoned" ).selectable();
            $( "#hours_zoned" ).on('click', 'li', function() {

                $(this).addClass("clicked ui-selected");
                 $( this ).css( "background-color", "#e74c3c" );
                $( this ).selectable({ disabled: true });

                var floorTime = $(this).text(); // get the value of the hour that was clicked
                shift.push(floorTime); // add that hour to the floorTime    
             }); 

    /*$('#add').on('submit', function() {
        var name = $('.leader').val(); */


    $('#btn').on('submit', function() {
        $.ajax({
            type: 'POST',
            url: 'post.php',
            data: shift,
            success: function(msg) {
                alert(msg);
            }
        });
    });

        return false;
    });

Upvotes: 2

Views: 1269

Answers (4)

Just wanna add to the answers given here..

You also need to check if the items selected are in array already (prevent duplicate).. so to do that you can do it like this

*code is taken from Matt answer

if($.inArray(floorTime, shift) === -1) {
                shift.push(floorTime);
                $("#add .shift").val(shift);
 }

Upvotes: 2

Matt Shultz
Matt Shultz

Reputation: 312

EDIT: Your ajax function was a bit jacked up. Fixed that for you also. See new code.

Your ajax submit isn't running. Add return false; to prevent the main form from submitting. I'm thinking the easiest way to add the array would be to insert it into a hidden input immediately after being pushed in your jQuery function. Then you would just serialize the form data and send it all in your ajax function. See below:

New form:

<form action="post.php" method="post" id="add">
<input type="text" class="leader" name="name" placeholder="Leader">
<input type="text" class="date" name="date" placeholder="date">
<input type="text" class="time" name="time" placeholder="time">
<input type="text" class="score" name="score" placeholder="score">
<input type="hidden" class="shift" name="shift">
<input type="submit" id="btn" value="send" />
</form>

New function:

var shift = []; //create array to store zoned hours

$(function() {
    $( "#hours_zoned" ).selectable();
        $( "#hours_zoned" ).on('click', 'li', function() {

            $(this).addClass("clicked ui-selected");
             $( this ).css( "background-color", "#e74c3c" );
            $( this ).selectable({ disabled: true });

            var floorTime = $(this).text(); // get the value of the hour that was clicked
            shift.push(floorTime); // add that hour to the floorTime  

            $("#add .shift").val(shift); // add shift array to hidden input in form  
         }); 

/*$('#add').on('submit', function() {
    var name = $('.leader').val(); */


$('#add').submit(function() {
    $.ajax({
        type: 'POST',
        url: 'post.php',
        data: $("#add").serialize(),
        success: function(msg) {
            alert(msg);
        }
    });
return false; // you need this to prevent the other form submission
});

    return false;
});

Untested, but that should get you going in the right direction.

Upvotes: 2

Sean
Sean

Reputation: 12433

You are only sending the key

data: shift,

according to the docs - Object must be Key/Value pairs. (https://api.jquery.com/jQuery.ajax/)

try

data: {shift: shift},

so it is now

$('#btn').on('submit', function() {
    $.ajax({
        type: 'POST',
        url: 'post.php',
        data: {shift: shift},
        success: function(msg) {
            alert(msg);
        }
    });
    return false;
});

Upvotes: 3

Ryan Smith
Ryan Smith

Reputation: 694

Try parse_str().

$array = parse_str( $_POST['data'] );

Upvotes: 0

Related Questions