Page 1 of 1

More JS Help [Solved, Thanks Renavoid!]

Posted: Mon Mar 04, 2013 6:34 pm
by MikeD
Sorry I am awful at JS lol.

I have this working how I want in entering something into the DB.

What I want is after JQuery calls the PHP script, for the Submit button to change. It's just returning plain text.

Here's the PHP part.

Code: Select all

echo "<td>";
                    echo "<div id='action_$row[0]'>";
                    echo "<input type='hidden' value='$row[0]' name='player_id' id='player_id'/>";

                $Get_Board = mysqli_query($server,"SELECT `player_id` FROM `recruiting_board` WHERE `player_id`='$row[0]' AND `team_id`='$team_id'") or die(mysqli_error($server));
                if (mysqli_num_rows($Get_Board) == 1){
                    echo "<input type='submit' name='remove_player' value='Remove' />";
                } else {
                    echo "<input type='submit' name='add_player' value='Add' id='add_player' />";
                }
                echo "</div>";
                echo "</td>";
and here's the Jquery where it calls another PHP Script.

Code: Select all

$('input#add_player').on('click', function(){
    var player_id = $('input#player_id').val();

        $.post('add_player.php',{player_id: player_id}, function(data){
            var div_name = "div#action_"+player_id;
            $(div_name).text(data);

        });
});
And the PHP script that is called (Just inserting a player into the DB)

Code: Select all

<?php

function random($array, $counter){
    shuffle($array);
    for($i=0;$i<$counter;$i++){
        $newarray[$i]=$array[$i];
    }
    return $newarray;
}

include_once 'includes/global_include.php';

$Get_Info = mysqli_query($db,"SELECT `team_id`,`server_id` FROM `coaches` WHERE `coach_id`='$player->coach_id'") or die (mysqli_error($db));
$coach_info = mysqli_fetch_array($Get_Info);
$team_id = $coach_info['team_id'];

list($server) = ServerConnect($coach_info['server_id']);

if(isset($_POST['player_id'])){
    $player_id = mysqli_real_escape_string($server,$_POST['player_id']);

    $Get_Board = mysqli_query($server,"SELECT `player_id` FROM `recruiting_board` WHERE `player_id`='$player_id' AND `team_id`='$team_id'") or die(mysqli_error($server));
    if (mysqli_num_rows($Get_Board) == 1){
        mysqli_query($server,"UPDATE `recruiting_board` SET `active`=1 WHERE `player_id`='$player_id' AND `team_id`='$team_id'") or die (mysqli_error($server));
        echo "<input type='submit' name='remove_player' value='Remove' />";
    } else {

        $pitches_array = array(1,2,3,4,5,6,7);
        $promises_array = array(1,2,3,4,5,6,7,8,9);

        list ($most,$high,$like,$avg,$low,$dislike,$hate) = random($pitches_array,7);
        list ($pmost,$phigh,$plike,$pavg,$pnormal,$pmediocre,$plow,$pverylow,$pdislike) = random($promises_array,9);

        mysqli_query($server,"INSERT INTO `recruiting_board` (`team_id`,`player_id`,`most`,`high`,`like`,`avg`,`low`,`dislike`,`hate`,`promise_most`,`promise_high`,`promise_like`,`promise_avg`,`promise_normal`,`promise_mediocre`,`promise_low`,`promise_dislike`,`promise_hate`)VALUES('$team_id','$player_id','$most','$high','$like','$avg','$low','$dislike','$hate','$pmost','$phigh','$plike','$pavg','$pnormal','$pmediocre','$plow','$pverylow','$pdislike')") or die(mysqli_error($server));

        ######## Pitches
        # 1 = Coach Prestige
        # 2 = School Prestige
        # 3 = Conf Prestige
        # 4 = Playtime
        # 5 = Pro Potential
        # 6 = Fan Base
        # 7 = Contender
        ########

        ######## Promises
        # 1 = No Redshirt
        # 2 = Playtime
        # 3 = Rivals
        # 4 = Conf Title
        # 5 = National Title
        # 6 = Facility Upgrades
        # 7 = Playoffs
        # 8 = Training Time
        # 9 = Winning Record
        ########

        echo "<input type='submit' name='remove_player' value='Remove' />";

    }


}
?>
Again I need it to return a submit button, not text.

Here's a pic of what it returns.

http://gyazo.com/5042344bf8eb3eeecdb4655a1fa52e82

I'm sure it's something simple, but I know about 0 JS lol.

Re: More JS Help

Posted: Mon Mar 04, 2013 7:15 pm
by MikeD
Hmm, I thought it was working right, but I guess not. No matter what player you click to add, it always adds from the top down. So the first player on the list is added first, no matter who you click on. I hate JS :?

Re: More JS Help

Posted: Mon Mar 04, 2013 7:43 pm
by Renavoid
The bugs in here are not limited to javascript... Your first problem is how you're using an html id attribute as a nonunique variable. you can't have both your hidden input, and the submit button use the id='player_id' (and I'm assuming every other row in your data has the same id, which is why only the first one works). They need unique values. I AM assuming that you have more than just this one row of data being returned, and want this behavior to work for each row... So, try using data- attributes on your submit buttons to get across the info you need on row classes like this:

Code: Select all

$('.add_player').click(function() {  //assigns click event to each tag with class 'add_player'  try 'input.add_player' if you want to specify
  var player_id = $(this).attr('data-player-id');
  $.post('add_player.php',{player_id: player_id}, function(data){
    var div_name = "div#action_"+player_id;
    $(div_name).html(data);
  });
});
And the answer to your actual question... .text() renders what you pass to it as a string. You want to use .html() as shown here. In your php, you would only have the div, not the hidden input, and on the submit button, you'd have the data- attribute, sort of like this:

Code: Select all

                if (mysqli_num_rows($Get_Board) == 1){
                    echo "<input type='submit' name='remove_player' value='Remove' />";
                } else {
                    echo "<input type='submit' name='add_player' value='Add' data-player-id='$row[0]' class='add_player'/>";
                }

Re: More JS Help

Posted: Mon Mar 04, 2013 7:49 pm
by Renavoid
It occurred to me that I might have sounded a bit rude and curt. Sorry! I was just trying to point out what was wrong and a way to fix it. There are other ways to fix it, too. That approach just readily comes to me. Also, this is just a bit of nitpicking, but since you're not actually submitting a form, you should use input type="button" instead of "submit" for this application. Otherwise, you might accidentally run into some quirky behavior for seemingly no reason (dealt with someone handling that just a month ago).

Re: More JS Help

Posted: Mon Mar 04, 2013 8:02 pm
by MikeD
Nope, didn't sound rude at all. I thank you for all the help, as you got it right. That was actually my first crack at this using a Youtube Tutorial. I just don't understand JS/JQuery yet, so I have a ton of learning left to do there.

I got both scripts working how I wanted (add player and remove player). However, if I add a player, I can't remove him until the page is refreshed, and vice versa, any idea of what is causing that?

Re: More JS Help

Posted: Mon Mar 04, 2013 8:13 pm
by Renavoid
Oh, I forgot that you were adding new buttons. Yes, the problem is that the new buttons you created with JS do not have any click events registered to them. Rather than calling the $('.add_player') again which would register all inputs of class add_player, you should only apply it to the new button by doing something like this:

Code: Select all

  $.post('add_player.php',{player_id: player_id}, function(data){
    var div_name = "div#action_"+player_id;
    $(div_name).html(data);
    $(div_name).find('.add_player').click(...);
  });
Note here, that because of the recursion, you'll need to make this a named function that you can call again. Also, be aware that the new button you're returning also needs that data- attribute on it.

Code: Select all

$(function() { //a function to be called once the page is ready, if you didn't know
  $('.add_player').click(addPlayer);  //register's the click event to trigger the addPlayer function
});

function addPlayer() {
  var player_id = $(this).attr('data-player-id');
  $.post('add_player.php',{player_id: player_id}, function(data){
    var div_name = "div#action_"+player_id;
    $(div_name).html(data);
    $(div_name).find('.add_player').click(addPlayer); //register the new button with this method.
  });
}

Re: More JS Help

Posted: Mon Mar 04, 2013 8:39 pm
by MikeD
Thanks, but that didn't work for me.

I do have the data attribute on the new buttons, and I pasted those functions you made.

Code: Select all

echo "<input type='button' name='remove_player' value='Remove' data-player-id='$player_id' class='remove_player' />";

Re: More JS Help

Posted: Mon Mar 04, 2013 9:03 pm
by Renavoid
Err.. can you specify what doesn't work? I am kind of creating this on the fly, so if you just copy-pasted, it's entirely possible that I have typos. Mind you, these are only for adding players. You'd have to duplicate the code for removing players, if you missed that point (but I don't think you did, given that the button you just posted is of class remove_player). Just covering bases.

Re: More JS Help

Posted: Mon Mar 04, 2013 9:24 pm
by MikeD
Sorry, yeah what I meant is that I still can't Remove a player after adding him, and vice versa, I did copy/paste the function and changed the values for removePlayer().

Re: More JS Help

Posted: Tue Mar 05, 2013 12:09 am
by Renavoid
I don't really see any immediate problems jumping out at me. Have you tried opening developer tools to see if there are any JS errors being thrown? IF you're in Chrome, IE, or have Firebug installed on FireFox, hit F12 on the page. Go over to the Console. Click on one of the add or remove buttons. Do any errors pop up? The JS seems correct, so my guess is there's a syntax error somewhere. It might even be something amiss in the data returned by your php script.