1

Hope you can help me with this. I have an array that im sending over to my php script to process via ajax. What I want to do is loop through the array and based on the value of a certain key, execute a SQL statement for that array. Most of the time it will be multiple arrays. Here is what I got so far....for this example, ill put in static values:

HTML

    <form id='logForm' method='post' action='seatingProcess.php'>
    <span id='"219"' changeType='SEATCHANGE' setDeskId='9-4' prevSeatNew='T'></span>
    <span id='"229"' changeType='SEATCHANGE' setDeskId='2-5' prevSeatNew='T'></span>
    <span id='"299"' changeType='REMOVESEAT' setDeskId='0'></span>
<div class='btn btn-primary' type='submit' id='submit'>Submit</div>
    </form>

Javascript

$('#submit').click(function(){
            var spans = $('#logForm span');
            var data = [];

             $(spans).each(function(){
                 var newItem = {};
                 var item = $(this);
                 newItem.id = $(item).attr('id');
                 newItem.deskval = $(item).attr('setDeskId');
                 newItem.changeType = $(item).attr('changeType');
                 newItem.prevSeatNew = $(item).attr('prevSeatNew');
                 data.push(newItem);                 
             })

             $.ajax({
                 type: "POST",
                 url: "seatingProcess.php",              
                 data: {data:data},
                 success: function(msg){
                     console.log(msg); //testing the sql statements
                 },
                 error: function(){
                     alert('fail');                  
                 }               
             })

seatingProcess.php

<?php
if(isset($_POST['data'])){
 $obj = $_POST['data'];
 $doKeyChange = ['changeType'];
 $addValue = 'SEATCHANGE';
 $delValue = 'REMOVESEAT';  

 foreach($obj as $doKeyChange => $addValue) {
    //Array[0] {'id' => 219, 'deskval' => 9-4, 'prevSeatNew' => T}
   //Array[1] {'id' => 229, 'deskval' => 2-5, 'prevSeatNew' => T}

    $userid = ['id'];
    $desk_id = ['desk'];
    $set_desk_id = ['deskval'];
    $prevseat = ['prevSeat'];
    $prevseatNew= ['prevSeatNew'];
    $sqlAdd = "UPDATE roster SET  seat='$set_desk_id' preDesk='$prevseatNew' WHERE id='$userid'";
    print_r ($sqlAdd);
}
 foreach($obj as $doKeyChange => $delValue) {
    //Array[2]{'id' => 299, 'deskval' => 0}
    $userid = ['id'];
    $set_desk_id = ['deskval'];
    $sqlAdd = "UPDATE roster SET  seat='$set_desk_id' WHERE id='$userid'";
    print_r ($sqlAdd);
}
}
?>

Currently, im getting errors like:

Notice: Array to string conversion

Not sure what to do, thanks in advance

QUESTION

How do I write the php so that it takes the value of the requested key and puts it into the SQL statement?

4
  • 1
    This may be a stupid question but if you're using a form, why aren't you using inputs, even with hidden spans, then serializing the form itself? That would save a lot of js and guess work. Commented Nov 10, 2015 at 16:41
  • this code is a snippet of my much larger code. There's a reason for this way that makes sense with my main code but I understand how silly it looks in this example. If you could just indulge me with my example, id really appreciate it. Commented Nov 10, 2015 at 16:44
  • If the question is why you're getting array to string conversion errors, its because 'id' is a string but ['id'] is an array, so $userid = ['id']; gives you an array,....i.e. take the brackets off. Commented Nov 10, 2015 at 16:46
  • I made some updates, hopefully it can clarify what Im looking for Commented Nov 10, 2015 at 16:55

1 Answer 1

1

You are currently making no attempt to serialize the data array into a format that can be properly handled by both $.ajax() and your PHP script. When you try to rely on jQuery's default object to query string conversion with code like this:

data: {data:data},

jQuery expects data to be an object (i.e. key-value pairs) that it can serialize into a query string. Passing a numerically indexed array as data is going to cause the conversion errors you are seeing.

You need to either properly create a serialized query string, or (and this would be my recommendation) since you are trying to pass a more complex data structure, you might consider JSON-encoding the data structure and POSTing to PHP with application/json header type. This would require you to then read the raw POSTed data in PHP, not read the data from $_POST, as PHP does not populate the $_POST superglobal for content type headers other than the form-encoded types.

To send JSON, your ajax call might look like this:

         $.ajax({
             type: "POST",
             url: "seatingProcess.php",
             contentType: "application/json",              
             data: JSON.stringify(data),
             success: function(msg){
                 console.log(msg); //testing the sql statements
             },
             error: function(){
                 alert('fail');                  
             }               
         })

In PHP you read the JSON from raw input like this:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Sign up to request clarification or add additional context in comments.

4 Comments

I would like to give that a shot, Ive tried using the application/json header type but I could not get it to work. Can you show me what you mean exactly?
@user247326 I just updated the answer to show how to read JSON data from raw input in PHP.
Sorry to be a bother, im still a novice at this and im having a bit of trouble putting it together. How do i formulate the sending of the array?
@user247326 I have updated the answer to include modified $.ajax() call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.