After very little success in using JQuery .post methods I wanted to try asking this here before giving up. I am serving a couple JS based games on a site using PHP as members can log into the site and through sessions/cookies remain logged and play games under their account. One game I have coded purely in PHP and it is simple to update the users database field for each game stating how many matches they've played, won, lost or tied. But one or two of the other games I am working on are in JavaScript using JQuery.

I had the game working fine in alerting the player whether they had won, lost or the match was a draw. I then attempted to add JQuery's .$post function to each case to send the result to a 'non-visible' (ie: it does not output HTML and is not seen by the player) php script which would update the appropriate field of the appropriate MySQL database.

First is the area of the game JS where the winner of the match is determined, an alert informs the player of the outcome and (will hopefully) update the database.

if (all==1){ alert("You won, congratulations!"); wn++; $.post("update_scores.php",
        {
               outcome: "won"
        })
}
if (all==2){ alert("Gotcha!  I win!"); ls++; $.post("update_scores.php",
        {
               outcome: "loss"
        })
}
if (all==3){ alert("We tied."); ts++; $.post("update_scores.php",
        {
               outcome: "tied"
        })
}

And next is the update_scores.php contents. I am attempting to capture the value of 'outcome' so that the script updates the proper field in the user's database row.

$outcome = $_POST['outcome'];

if($outcome == "won") {
    mysql_query("UPDATE `playerdb` SET `won`= `won` + 1 WHERE `user` = '$username'");
}

if($outcome == "lost") {
    mysql_query("UPDATE `playerdb` SET `lost`= `lost` + 1 WHERE `user` = '$username'");
}

if($outcome == "tied") {
    mysql_query("UPDATE `playerdb` SET `ties`= `ties` + 1 WHERE `user` = '$username'");
}

It is important to note that both PHP pages (the game page and score update page) uses a common function to check for an active session and fills the username variable from there. Also not in the update_score.php code are the database connection (but it does connect correctly). I created another page to send the 'outcome' as I am trying to get the JQuery to do and update_score.php handles it and updates the correct field of the correct users' row without issue. My issues seems to be in either getting JQuery to properly send the outcome info or the update_score.php's method of recieving that info.

I know that this is an incredibly specific case but after hours of scouring I am finding all too little info about JQuery post and so hopefully others could potentially gain knowledge from any possible solutions.

Thanks in advance to anyone who is able to point me towards the right direction!

Dani AI

Generated

A short diagnosis and practical fixes to complement 's description and 's debugging advice.

A few common root causes explain the behavior described: a mismatch between the string sent by the JS and the string the PHP checks for (that prevents any branch from running); the AJAX request not reaching the script (check the Network tab / response code); or the script not seeing the logged-in username because the session was not started or is inaccessible. Ensure update_scores.php calls session_start() before using session data. (php.net)

A pragmatic debug checklist (order matters): inspect the browser DevTools Network request to confirm the POST payload and HTTP status; use an AJAX call with explicit success/fail handlers (so failures surface instead of silently failing); log the raw $_POST and session contents server-side to a debug file; and check webserver / PHP error logs for fatal errors or permission issues. The jQuery ajax API documents success/error handling and the returned jqXHR promise. (api.jquery.com)

A safe server-side pattern avoids both logic bugs and SQL risk. Log incoming data, validate the outcome against a whitelist, then update the DB with a prepared statement (PDO or mysqli). Example debugging/logging + update flow:

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
session_start();
file_put_contents(__DIR__.'/xhr-debug.log', print_r($_POST, true)."\nSESSION: ".print_r($_SESSION, true)."\n", FILE_APPEND);

$out = $_POST['outcome'] ?? '';
$map = ['won'=>'won_col','loss'=>'lost_col','tied'=>'ties_col']; // whitelist column names
if (!isset($map[$out]) || empty($_SESSION['username'])) { exit; }

// Use PDO or mysqli prepared statements to run the update safely.

The $POST superglobal holds form-encoded POST data, and the old mysql* functions are deprecated/removed—switch to mysqli or PDO and use prepared statements to avoid SQL injection and PHP-compatibility problems. (php.net)

Additional notes: AJAX requests are subject to same-origin and CORS rules (verify domain/port/protocol), and PHP session locking can block concurrent XHRs (session_write_close() after reading session data helps). If the debug log shows the POST arrived but the DB still not changing, check the username source and DB errors next.

What kind of error are you getting?
Try using developer console to analyse the http request(often in Network tab).
Also, use the $.ajax method so you can get an error callback to debug it.

Example

var msg, outcome;

if (all==1){ wn++; msg ="You won, congratulations!";  outcome = "won" }
else if (all==2){ ls++; msg ="Gotcha!  I win!";  outcome = "loss" }
else if (all==2){ ts++; msg ="We tied.";  outcome = "tied" }

alert(msg);

$.ajax({
    type: "POST",
    url: "update_scores.php",
    data: { outcome : outcome },
    success: function(data, textStatus) {
        console.log("Request Result: " + textStatus);
    },
    error: function(event, jqXHR, ajaxSettings, thrownError) {
        console.log("Request Error: " + thrownError);
    },
    dataType: dataType
});

And a simplification of your php script

$outcome = $_POST['outcome'];
$upate = "";

if($outcome == "won") { $update = "`won`= `won` + 1" }
else if($outcome == "lost") { $update = "`lost`= `lost` + 1"; }
else if($outcome == "tied") { $update = "`ties`= `ties` + 1"; }

mysql_query("UPDATE `playerdb` SET ". $update . " WHERE `user` = '$username'");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.