Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow:

  1. User clicks on an image (either 'cowboys' or 'giants')
  2. Onclick triggers the function 'teamback' with 'this' passed to it (so far so good, now we need to use ajax to connect to the database and insert the information)
  3. The function should take the userid (session variable), tn, and sc, then use ajax to insert them into the database

I'm having trouble with the ajax part because I have no experience with it. I believe I made a mistake in the GET section. The issue is that it's not working; nothing gets inserted into the table. It seems like my ajax code in the teamback function and makepick.php file is incorrect. Any guidance on setting this up would be greatly appreciated!!

Here is the HTML document...

<?php
 // This initiates the session 
 session_start();
 $id = $_SESSION['userid'];

 // Connecting to the database
$con = mysql_connect("localhost","yourfan3_jeengle","armyjoe30");
mysql_select_db("yourfan3_demo", $con);

//**THIS VARIABLE MANUALLY SETS THE PICKS POSSIBLE
$maxcorrectpicks = 16;

 // Getting user information
 $result = mysql_query("SELECT * FROM League_Info WHERE User_ID = '$id'");  
 $result2 = mysql_fetch_array($result);
 $leaguename = $result2['League'];

 // Checking if league name exists
 $memberslist = mysql_query("SELECT User_ID, Correct_Picks, Points FROM League_Info WHERE League = '$leaguename'"); 
 ?>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
        <script type="text/javascript" src="js/jquery-easing-1.3.pack.js"></script>
        <script type="text/javascript" src="js/jquery-easing-compatibility.1.2.pack.js"></script>
        <script type="text/javascript" src="js/coda-slider.1.1.1.pack.js"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="icon" href="http://www.indiana.edu/favicon.ico" />
        <title>Your</title>
        <link rel="stylesheet" type="text/css" href="yourteamstyle.css" />

        <script type="text/javascript">
        var userid = "<?=$id?>";

        function newPopup(url) {
            popupWindow = window.open(url,'popUpWindow','height=450,width=600,left=10,top=10,resizable=no,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
        }
        function bigimg(x) {
            var myDate = new Date(); 
            var myEpoch = myDate.getTime()/1000; 
            var deadline = '1344700055.000'; 
                if(myEpoch < deadline) {
                    x.style.height="65px";
                    x.style.width="85px";
                    x.style.opacity="0.5";
                } else {}
        }
        function defaultimg(x) {
            x.style.height="60px";
            x.style.width="80px";
            x.style.opacity="1.0";
        }
        function teamback(x) {
            var myDate = new Date(); 
            var myEpoch = myDate.getTime()/1000; 
            var deadline = '1344700055.000';
                if(myEpoch > deadline) {
                    var tn = x.id;
                    var sc = x.name;
                    document.getElementById("actualone").src = x.src;
                    document.getElementById("curtime").innerHTML = myEpoch;
                    document.getElementById("team").innerHTML = x.id;
                    document.getElementById("scenario").innerHTML = x.name;
                    if (window.XMLHttpRequest) {
                        xmlhttp=new XMLHttpRequest();
                    } else {
                        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlhttp.onreadystatechange=function() {
                    }
                    xmlhttp.open("GET","makepick.php?newuserid="+userid, true);
                    xmlhttp.open("GET","makepick.php?newtn="+tn, true);
                    xmlhttp.open("GET","makepick.php?newsc="+sc, true);
                    xmlhttp.send();

                } else {}           
        }
        </script>

    </head>
        <body>
            Your Team<br>
            <iframe style="background-color:red;" src="http://free.timeanddate.com/countdown/i38ik9yz/n417/cf12/cm0/cu4/ct1/cs1/ca0/co1/cr0/ss0/cac000/cpc000/pct/tc66c/fs100/szw320/szh135/tatTime%20Remaining%20to%20Make%20Picks/tac000/tptTime%20since%20Event%20started%20in/tpc000/iso2012-08-11T13:00:00" frameborder="0" width="236" height="36"></iframe>

            <br><img id="cowboys" name="One" onmouseover="bigimg(this)" onclick="teamback(this)" onmouseout="defaultimg(this)" src="cowboys.gif"> vs <img id="giants" name="One" onmouseover="bigimg(this)" onclick="teamback(this)" onmouseout="defaultimg(this)" src="giants.gif"><img src="" id="actualone" style="width:85px; height:65px;"><br><br>
            <div id="curtime">44</div>|||<div id="deadline"></div><br><div id="team">Team</div><div id="scenario">Scenario</div>


        </body>
</html>

And here is the makepick.php file

<?php
$userid = $_GET["newuserid"];
$tn = $_GET["newtn"];
$sc = $_GET["newsc"];

$con = mysql_connect("localhost","yourfan3_jeengle","armyjoe30");
mysql_select_db("yourfan3_demo", $con);

mysql_query("INSERT INTO Week1_Picks_Test (UserID, '$sc') VALUES ('$userid', '$tn')");

?>

Answer №1

If you are utilizing Jquery, my recommendation is to update your teamback() function to utilize jQuery's ajax method:

function teamback(x) {
var myDate = new Date(); // Your time zone! 
var myEpoch = myDate.getTime()/1000; 
var deadline = '1344700055.000';
    //checks if user was on time for submission
    if(myEpoch > deadline) {
        // update the "actualone" image's source to the sending-image's source
        var tn = x.id;
        var sc = x.name;
        document.getElementById("actualone").src = x.src;
        document.getElementById("curtime").innerHTML = myEpoch;
        document.getElementById("team").innerHTML = x.id;
        document.getElementById("scenario").innerHTML = x.name;

        $.ajax({
          type: 'GET',
          url: 'makepick.php',
          data: { newuserid: userid, newtn: tn, newsc:sc },

          success:function(data){
            //perform actions upon successful submission
            alert('success');
          },
          error:function(){
            //handle errors that occur during submission
            alert('error');
          }
        });
    } else {}           

}

Answer №2

Upon initial observation, I immediately noticed an issue: The AJAX processing query contains the $sc variable within single quote marks ('). This can result in a syntax error since $sc is a column name. To rectify this, consider removing the quotes or using backticks (`) instead.

Furthermore, it is recommended to sanitize input before sending it to the database and implementing prepared statements with PDO for enhanced security measures: http://php.net/manual/en/book.pdo.php

Answer №3

It seems like there might be an issue that you're facing, so it could be helpful to learn more about SQL injections. You can check out this resource for beginners at .

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for distinguishing between the different values

Greetings! I am currently utilizing this code snippet to retrieve values from a Java class. Upon getting the data from Java, it triggers an alert displaying two values separated by spaces. My next goal is to split the values into two separate entities an ...

Transferring sizable JavaScript array to the Web API

I've been grappling with this problem for two days... In my JavaScript code, I have a large array comprising 20,000 rows and 41 columns. This data was initially fetched in JavaScript via an ajax call, as shown below: var dataArray = []; var dataRequ ...

What methods can be utilized to avoid displaying a Bootstrap popover intermittently within an AngularJS framework?

When using the bootstrap popover in a custom AngularJS directive, I need to display an error message when the button is disabled by setting $scope.buytypeButton= {type:false}. The error message should be displayed in a popover. On the other hand, when $sco ...

Creating a Slider with a Multitude of Images

I am working on a project to develop a gallery that pulls images from a JSON source. I have successfully implemented infinite scrolling to display the images on the first page. However, I am now facing a challenge when it comes to showing the selected imag ...

Embracing the Unknown: Exploring Wildcard Values

I have a code snippet below that has a wildcard * in it. I'm looking for suggestions on how to make the * accept any number. Any thoughts on this? $('body').on('click', '.custom_295_*-row', function(){ var href = "htt ...

Repeated firing of items is seen when using jQuery for infinite Ajax scroll functionality

I have incorporated the jquery infinite ajax scroll (ias) plugin to display category results for a mobile shop. As users scroll or swipe down, the script loads items from subsequent pages multiple times. You can try it out here: Testpage If you access t ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

Determine if a specific date occurred at least one day ago using momentjs

Is there a way to determine if a specific date is at least one day (24 hours) in the past using momentjs? For example: const currentDate = moment() const isAtLeastOneDayAgo = currentDate.subtract(dateToVerify) > 1 // How can this be done? ...

Tips for getting rid of the glowing effect on MUI slider thumbs when they are in focus

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

Is it possible to establish a connection between React and a MySQL Database?

I've been encountering issues with connecting to a remote database in React. Despite my efforts, I haven't been successful in establishing the connection. I have tried various solutions without any luck. The goal is simple - I just want to connec ...

Managing class values with Selenium - Manipulating and updating classes

In the program I'm working on, there is a need to toggle which element receives the class value of "selected". <div class="countryValues"> <div data-val="" >USA and Canada</div> <div data-val="US" >USA - All< ...

Implement the HTML code for utilizing the GET method in an AJAX request

I'm exploring a way to utilize inline HTML directly as the URL for the ajax GET method without fetching data from a separate webpage. Is it feasible? Here is my ajax code: $.ajax({ type: "GET", url: $(elm).attr("href"), ...

Verify if the screen is in full view by monitoring document.fullscreenElement within Vue3

Is there a way to determine when the document is in fullscreen mode? I attempted to monitor document.fullscreen with the following code, but it was not successful: watch(document.fullscreenElement, (newValue) => { fullScreenActivated.value = newValue ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

Relocate the bxslider carousel to the specific div clicked on

Is it possible to move the slider to the selected div when using bxslider? I have a carousel below. Currently, when you click on the controls (left/right arrows), it only moves one slide/div at a time, keeping the active div always on the left side. Howev ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

What is the best way to get the latest props in the midst of an async function?

There's a fascinating open-source project called react-share, where the ShareButton component offers a prop known as beforeOnClick for customization. I've utilized this beforeOnClick to upload images to our CDN before sharing, ensuring that only ...

Ways to store AJAX response data for future use

I am struggling with implementing the getState function. My goal is to update a field on click using a state value retrieved from an AJAX call. I have come across mentions of promises in other responses, but I am unsure how to integrate them into my code ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Can the default position of the scrollbar be set to remain at the bottom?

I have a select option tag with a scrollbar to view the contents in the dropdown. I am looking for a way to automatically position the scroll at the bottom when an item is selected from the dropdown. jquery code $('document').ready(func ...