-2

Hello Stackers,

I'm having a lot of trouble with AJAX. I Want ajax to change a color for a div. First directly, which it does. Then it should save it in a Database, which it DOES NOT. No other questions on stackoverflow contained a solution for me.

The problem is this: It does not alter the column in the database. It's not stored.

The jQuery requesting the AJAX file

$(document).ready(function() {
    var uid = <?php echo $user['id']; ?>;
$('#blue').click(function() {
    $('#upbar').css({
        'background-color': '#3498db',
        'background-image': 'none',
    });

    $.ajax({
                method: 'post',
                url: 'app/tpl/skins/Magical/includes/ajax.php',
                data: {
                    action: 'update_blue',
                    id: uid,
                }
            })

});

$('#purple').click(function() {
    $('#upbar').css({
        'background-color': '#9b59b6',
        'background-image': 'none',
    });

    $.ajax({
                method: 'post',
                url: 'app/tpl/skins/Magical/includes/ajax.php',
                data: {
                    action: 'update_purple',
                    id: uid,
                }
            })

});
$('#red').click(function() {
    $('#upbar').css({
        'background-color': '#e74c3c',
        'background-image': 'none',
    });

    $.ajax({
                method: 'post',
                url: 'app/tpl/skins/Magical/includes/ajax.php',
                data: {
                    action: 'update_red',
                    id: uid,
                }
            })
});
$('#yellow').click(function() {
    $('#upbar').css({
        'background-color': '#f39c12',
        'background-image': 'none',
    });

    $.ajax({
                method: 'post',
                url: 'app/tpl/skins/Magical/includes/ajax.php',
                data: {
                    action: 'update_yellow',
                    id: uid,
                }
            })
});
$('#image1').click(function() {
    $('#upbar').css({
        'background-image': 'url("app/tpl/skins/Magical/assets/images/header-magie.png"),
    });

    $.ajax({
                method: 'post',
                url: 'app/tpl/skins/Magical/includes/ajax.php',
                data: {
                    action: 'update_image1',
                    id: uid,
                }
            })
});
});

ajax.php

 error_reporting(E_ALL);
 ini_set('display_errors', '1');


if(!isset($_POST["action"])) {
    exit("fail");
}

$user = $_POST['id'];

switch ($_POST["action"]) {

        case "update_blue":
            echo "1";
            $update = mysql_query("UPDATE users SET magical_header = '1' WHERE id = '".$user."'")or die(mysql_query());
        break;

        case "update_purple":
            echo "2";
            $update = mysql_query("UPDATE users SET magical_header = '2' WHERE id = '".$user."'");
        break;

        case "update_red":
            echo "3";
            $update = mysql_query("UPDATE users SET magical_header = '3' WHERE id = '".$user."'");
        break;

        case "update_yellow":
            echo "4";
            $update = mysql_query("UPDATE users SET magical_header = '4' WHERE id = '".$user."'");
        break;

        case "update_image1":
            echo "5";
            $update = mysql_query("UPDATE users SET magical_header = '5' WHERE id = '".$user."'");
        break;  

    default:
        echo 'I did not know that you were there.';

}

Am I overlooking something here? Why this is not offtopic; The expected behaviour is reported above, I Want a DIV to recolor, however, it didn't save, and that's the issue, again, clearly stated above. All the code can be used to reproduce the error, and there is no minimal version of it. This is the code which needed to be fixed, not a complete other one.

Pascal Boschma
  • 187
  • 1
  • 14
  • what is the error? message? problem? – cmnardi Sep 03 '16 at 19:08
  • Open developers console and check for errors and request results. – u_mulder Sep 03 '16 at 19:08
  • There is a succesfull request. No error message returning. `jquery.min.js:4 XHR finished loading: POST "http://example.com/app/tpl/skins/Magical/includes/ajax.php".` The problem is that the query doesn't run. It does not save anything – Pascal Boschma Sep 03 '16 at 19:10
  • Have you tried adding an [`error` option](https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) or [`.fail()`](https://api.jquery.com/deferred.fail/) callback to the Ajax requests? jQuery generally allows Ajax to fail silently. Or, have you inspected the request in your browser's dev tools? Does it receive a `200 OK` response? If not, does the response content mention any PHP errors? – Jonathan Lonowski Sep 03 '16 at 19:17
  • Side notes: [`mysql`](https://php.net/intro.mysql) functions have been deprecated and shouldn't be used anymore. Alternatives are mentioned in its documentation. – Also, using concatenation within a query makes your application susceptible to [SQL injection attacks](https://www.owasp.org/index.php/SQL_Injection). To avoid those, [you can use parameterized/prepared queries](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) or ensure all variables are [properly escaped](https://php.net/mysqli.real-escape-string). – Jonathan Lonowski Sep 03 '16 at 19:24

1 Answers1

1

your code seams to be fine, maybe you're just lost because you have a lot of jquery selector, what i suggest is using data key to set color, it will save a lot of space in your script,

$(document).ready(function(){
    var uid = 'something';
    $('.colorButton').on('click', function(){
        var color = $(this).data('color');
        $.ajax({
            'url':'path/to/your/file/ajax.php',
            'method':'POST',
            'data':{'action': color, 'uid':uid},
            'success':function(){
                console.log('success')
            }
        });
    });
});

With some basic html like

<div>
    <button class="colorButton" data-color="update_yellow"></button>
    <!-- and all your other buttons -->
</div>

this will ligthen your code a little bit. now, for your Ajax.php page. you could use an associative array to validate your color and then use only one query to update the database. i also suggest binding your parameters just to be sure you're protected against injection.
I would suggestion something like that.

<?php
    if(isset($_POST['action']) && isset($_POST['uid'])){
        $ALLOWED_ACTION = array('update_yellow' => '4', 'update_blue' => '1' ) // add the rest
        if(array_key_exists($_POST['action'], $ALLOWED_ACTION)){
            $stm = mysqli_prepare('UPDATE users SET magical_header = ? WHERE uid = ?')
            $stm->bind_param('s', $ALLOWED_ACTION[$_POST['action']]); // S for string
            $stm->bind_param('i', $_POST['uid']); // I for integer
            $stm->execute();
        } else {
            die('invalid action');
        }
    } else {
        die('Invalid Parameters');
    }

Normaly this should work, i havn't tested it yet though. Hopes it helps!

  • Nic
Nicolas
  • 8,077
  • 4
  • 21
  • 51