Question

EDITTED WITH FIXES - PROBLEM RESOLVED

Context: I'm trying to create a page where clicking an image changes the user's preferences on the server. Trying to use ajax to send the information without refreshing the page, and Jquery to trigger the post.

Problem: Nothing seems to be posting. It seems the ajax isn't posting the data to the data.php file.

Intended action: When image is clicked, the id of the parent is posted in the game column for that user.

header.php

<script type="text/javascript">
  $(document).ready(function(){
    $(".pickteam").click(function() {
        var game = $(this).parent().attr('data-id');
     $.ajax
        ({ 
            url: 'data.php',
            data: {game: game},
            type: 'post',
        });
    });
 });
</script>

index.php

<div class="col-md-3 team1 otherteam" data-id="m004">
    <button class="pickteam">
        <img src="http://img.fifa.com/images/flags/4/bra.png" alt="Brazil">
    </button>
    <span class="country">BRAZIL</span>
</div>

data.php

$game = $_POST['game'];

mysqli_query($con, "INSERT INTO choices (user, game) VALUES ('12345', '$game')");

Thanks in advance of any and all help.

Was it helpful?

Solution 2

Use var game = $(this).parent().attr('data-id'); to get the value from parent div

And remove extra comma from your ajax function near type : "post",, so the final code should be :

<script type="text/javascript">

$(document).ready(function(){

        $(".pickteam").click(function() {
            var game = $(this).parent().attr('data-id');
         $.ajax
            ({ 
                url: 'data.php',
                data: {game: game},
                type: 'post'
            });
        });
});

</script>

OTHER TIPS

I'm guessing you're not getting your data id right because your jQuery code should be var game = $(this).parent().attr('data-id');, so to put it all together:

<script type="text/javascript">
    $(".pickteam").click(function() {
        var game = $(this).parent().attr('data-id');
     $.ajax
        ({ 
            url: 'data.php',
            data: {game: game},
            type: 'post'
        });
    });
</script>

You need to use

var game = $(this).parent().attr('data-id');

To get the value of the data-id attribute. It's not clear what exactly goes wrong. Could you provide more details on where you're stuck?

You just need to wrap your code inside Document ready wrapper:

<script type="text/javascript">
$(document).ready(function(){
    $(".pickteam").click(function() {
        var game = $(this).parent().data('id');
     $.ajax
        ({ 
            url: 'data.php',
            data: {game: game},
            type: 'post',
        });
    });
});    
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top