简体   繁体   中英

using jquery post to send values to php file

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.

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.

Try removing the '' fx:

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

try this

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

Also you could try something like this to check

$(":checkbox").change(function(){
   var thisId = $(this).attr('id');
   console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];

Try this:

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

Try n use this...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM