0

I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?

Here's the javascript:

var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {        
    var memberID = document.getElementById("member"+i); 
    if(memberID && memberID.checked) {
        var memberID = document.getElementById("member"+i).value;
        $.ajax({
            type : 'post',
            datatype: 'json',
            url : 'subtract.php',
            data : {hours : hours.value, memberID : memberID.value},
            success: function(response) {
                if(response == 'success') {
                    alert('Hours subtracted!');
                } else {
                    alert('Error!');
                }
            }
        }); 
    }
    i++;
}   
}    

subtract.php:

if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
    $hoursToSubtract = (int)$_POST['hours'];
    $studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");

Edit: Updated code following @Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.

5
  • Try alerting the js values before you post them. It sounds like they aren't being set properly Commented Mar 31, 2013 at 7:57
  • what is numberofMembers? You shouldn't just send a bunch of asynchronous requests like this over and over in a loop. I would recommend you aggregate the data and send it all at once, along with a response for the entire set of data. Commented Mar 31, 2013 at 7:57
  • @PRPGFerret I set up breakup points in firebug, and all the variables got their respective values. Commented Mar 31, 2013 at 8:10
  • Is there any information about the parameters it's sending in the Network tab? Commented Mar 31, 2013 at 8:12
  • @Barmar, nothing came up Commented Mar 31, 2013 at 8:22

7 Answers 7

3

This might help you:

function subtractHours(numberofMembers) {
    var hours = document.getElementById('hours');
    var i = 1;

    while(i < numberofMembers) {
        // Put the element in var
        var memberID = document.getElementById(i);
        // Check if exists and if it's checked
        if(memberID && memberID.checked) {
            // Use hours.value and memberID.value in your $.POST data
            // {hours : hours.value, memberID : memberID.value}
            console.log(hours.value + ' - ' + memberID.value);
            // $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
            $.ajax({
                type : 'post',
                dataType : 'json', // http://en.wikipedia.org/wiki/JSON
                url : 'subtract.php',
                data : { hours : hours.value, memberID : memberID.value},
                success: function(response) {
                    if( response.type == 'success' ) {
                        alert('Bravo! ' + response.result);
                    } else {
                        alert('Error!');
                    };
                }
            });

        }
    i++;
    }
}

and PHP part:

$result = array();

// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND  ! empty( $_POST['memberID'] ) ) {
    $result['type']   = "success";
    $result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
    $result['type']   = "error";
}

// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;

die();

Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/

You can simple fix that by putting some string in front:

var memberID = document.getElementById('some_string_' + i);

This is not ideal solution but it might help you to solve this error.

Cheers!

UPDATE:

First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.

Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.

Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for this! I slightly changed the php portion to only retrieve the numbers, is there something wrong with what I did?
Hi Andrew, I'm glad you solved the error and that my first answer ever on StackOverflow helped you :) I can't call myself an expert but rather a person that knows his way around :). Since I often find answers to my problems on StackOverflow and I in fact was working on something similar the other the day I thought I could try to help you. I updated my answer with longer explanation what seemed to be a problem. Cheers
And Andrew why don't you use just Firebug and Net panel for testing this, that's how I do it. I did test this and in fact I'm using similar code on my server. Have you checked all the paths of files? IE. try to test with html site with JS in it (inline not external) and php in same folder and etc. Try to exclude first obvious errors that we all seem to forget sometimes :)
0

Try removing the '' fx:

$.post (
        "subtract.php",
        {hours : hours, memberID : memberID}

3 Comments

what do you get out of memberID and hours when you do console.log?
Try converting your i inside document.getElementById(i) to string and use @jycr753's solution.
do you get the right values when you console them out? just before sending the post
0

try this

        $.ajax({type: "POST",
        url:"subtract.php",
        data: '&hours='+hours+'&memberID='+memberID,  
        success: function(data){
          }
        });

1 Comment

what differentiates between this one and using .post?
0

Also you could try something like this to check

$(":checkbox").change(function(){
   var thisId = $(this).attr('id');
   console.log('Id - '+thisId);
});

Comments

0
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];

Comments

0

Try this:

$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
  document.body.style.cursor = "auto";
});

Comments

0

Try n use this...

$.post("subtract.php", { hours: hours, memberID : memberID })
    .done(function(data) {
        $(body).css({ 'cursor' : 'auto' });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.