Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first radio button in the database. This means that even if "No" is selected on the radio button, "Yes" is stored in the DB. I am unsure of what mistake I might be making.

Below are the relevant HTML functions:

function saveUserInfo(userName, userEmail, optedIn, currentUser, catDog, otherBrand)
    {
            if(optedIn === "Yes")
            {
                finalAnswers = userName + "yes" + "~" + userEmail + "~" + optedIn + "~" + currentUser + "~" + catDog + "~" + otherBrand + "~";
            }else{
              finalAnswers = userName + "no" + "~" + userEmail + "~" + optedIn + "~" + currentUser + "~" + catDog + "~" + otherBrand + "~";
              //  finalAnswers = userName + "~" + userEmail + "~0" + optedIn + "~1" + currentUser + "~2" + catDog + "~3" + otherBrand + "~4";
            }

      try
        {
          $.ajax({
            url: surveyServer + finalAnswers,
            type: 'post',
            success: function(evt){
              console.log('success saving ' + finalAnswers);
            }
          });
        }
      catch(err)
      {
        alert(err.message);

      }
    }


function saveUser()
{
  $('.wrapper').find("#userEmail").blur();
        if (($('#userName').val().length > 0) && ($('#userEmail').val().length > 0))
        {
            var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
            var valueToTest = $('#userEmail').val();
            if (testEmail.test(valueToTest))
            {
                //pass
                saveUserInfo($('#userName').val(), $('#userEmail').val(), $('#optedIn').val(), $('#currentUser').val(), $('#catDog').val(), $('#otherBrand').val());
                $('.wrapper').slick('slickNext');
            } else {
                // Do whatever if it fails.
      alert("Please enter a valid email address.");
                $('.wrapper').find("#userEmail").focus();
            }

        }else{
            alert("Please enter your name and email address then click Submit.");
            $('.wrapper').find("#userName").focus();
        }
    }

The following is the surveySurver code snippet:

if (isset($_GET['user']))
    {
            try
            {
                $dbh = new PDO('mysql:host=localhost; dbname=bp1234', 'bp1234','bp1234');


                $userAnswerArray = explode("~", $_GET['user']);

                $stmt = $dbh->prepare("INSERT INTO bpQuiz (userName, userEmail, optedIn, currentUser, catDog, otherBrand) VALUES (:userName, :userEmail, :optedIn, :currentUser, :catDog, :otherBrand)");

                $stmt->bindParam(':userName', $userName);
                $stmt->bindParam(':userEmail', $userEmail);
                $stmt->bindParam(':optedIn', $userOption);
                $stmt->bindParam(':currentUser', $currentUser);
                $stmt->bindParam(':catDog', $catDog);
                $stmt->bindParam(':otherBrand', $otherBrand);

                // insert value
                $userName = $userAnswerArray[0];
                $userEmail = $userAnswerArray[1];
                $userOption = $userAnswerArray[2];
                $currentUser = $userAnswerArray[3];
                $catDog = $userAnswerArray[4];
                $otherBrand = $userAnswerArray[5];
                $stmt->execute();

            }

            catch (PDOException $e)
            {
                    echo 'ERROR: ' . $e->getMessage();
            }

    }
    else
    {
        echo "no querystring...";
    }

To add to the context, here are the form input fields:

      <input type="text" class="contactFormInputBox" name="userName" id="userName"/>
      <input type="text" class="contactFormInputBox" name="userEmail" id="userEmail"/>
      <input type="checkbox" name="optedIn" id="optedIn" value="Yes">
        <input type="radio" name="currentUser" value="1" id="currentUser">Yes
        <input type="radio" name="currentUser" value="0" id="currentUser">No
        <input type="radio" name="catDog" value="cat" id="catDog">Cat
        <input type="radio" name="catDog" value="dog" id="catDog">Dog
        <input type="radio" name="catDog" value="both" id="catDog">Both
      </div>
      <div class="surveyOptions" id="Q2-b">
        <input type="text" class="contactFormInputBox" name="otherBrand" id="otherBrand"/>

Answer №1

Following freedomn-m's advice, I removed the "ID=" and made adjustments to the code below which retrieves values from checked radio buttons/checkboxes (e.g. $( "input[type=checkbox][name=optedIn]:checked" ).val()):

function saveUser()
    {
      $('.wrapper').find("#userEmail").blur();
            if (($('#userName').val().length > 0) && ($('#userEmail').val().length > 0))
            {
                var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
                var valueToTest = $('#userEmail').val();
                if (testEmail.test(valueToTest))
                {
                    //pass
                    saveUserInfo($('#userName').val(), $('#userEmail').val(), $( "input[type=checkbox][name=optedIn]:checked" ).val(), $( "input[type=radio][name=currentUser]:checked" ).val(), $( "input[type=radio][name=catDog]:checked" ).val(), $('#otherBrand').val());
                    $('.wrapper').slick('slickNext');
                } else {
                    // Do whatever if it fails.
          alert("Please enter a valid email address.");
                    $('.wrapper').find("#userEmail").focus();
                }

            }else{
                alert("Please enter your name and email address then click Submit.");
                $('.wrapper').find("#userName").focus();
            }
        }

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

Stop a second ajax request while the first one is in progress

Despite the abundance of questions on Stack Overflow addressing this issue, I still can't find a solution. Here is the jQuery code snippet: function _get_activities_ajax() { $(".activity-accordian h3").click(function() { var catrgory ...

Encountering issues while establishing a connection to SQL Server through Node.js

I've developed a Node.js application to interact with SQL Server. Here's the code snippet: app.get('/SalesStatistics', function (req, res) { var Connection = require('tedious').Connection; // configuration for the databas ...

New button attribute incorporated in AJAX response automatically

data-original-text is automatically added in ajax success. Here is my code before: <button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button> $(document).on("sub ...

excess white space appears in the mobile version

I recently completed a website using both materializecss and bootstrap platforms. While I know this may not be the best practice, it worked for my needs. However, I am facing an issue with the mobile view. When I reduce the viewport size, a margin appear ...

Applying the spread operator in the map function for copying objects

In my Angular application, I am attempting to copy an object and add a new property using the spread operator. To add the new property, I have created a method called 'addNewProperty(name)' which returns the property and its value. However, when ...

What is the best way to access nativeElements during the ngOnInit lifecycle hook?

Assume in my angular script I have the ability to access an HTML element with viewChild('someDiv') or constructor(private elem: ElementRef){}. When my angular component loads, I want to immediately retrieve a property of that element and store it ...

What is the process for pausing a video while it is still buffering and loading?

Is it possible to suspend a video when it is in an opening or preparing state? For example, if I open a video and then switch to another application using the smart hub feature, how can I suspend the video while it is in the process of opening or preparin ...

Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2. function recursionFib(num){ if(num ...

If Android App is not installed, divert users to a personalized web page instead of the Play Store

I am trying to create a link that opens an app on Android when clicked. However, if the app is not installed, it redirects to the Play store by default. This is not the behavior I want. What I would like is for the link to redirect to a custom webpage ins ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory: import Vuex from "vuex"; const createStore = ...

Production is showing a request validation error, but this issue is not occurring on the

After extensively searching the depths of the internet, I am still unable to find a solution. Can anyone assist me with this issue? Locally on my Mac, everything works perfectly. However, upon pushing the site to production (CentOS7 VPS), I encounter the ...

Angular is unable to detect the dynamically loaded page when using Extjs

Within my Extjs SPA system, I have integrated Angular along with the necessary modules to be used on a page that is being referred in an external HTML panel in Extjs. While Angular is defined and functioning properly everywhere else, it seems to not work ...

I'm looking to center the column content vertically - any tips on how to do this using Bootstrap?

Hello! I am looking to vertically align the content of this column in the center. Here is an image of my form: https://i.stack.imgur.com/nzmdh.png Below is the corresponding code: <div class="row"> <div class="form-group col-lg-2"> ...

Node.js user attempting to upload and handle files without any external libraries, solely relying on traditional JavaScript and HTML techniques

Previously, my Node.js code seamlessly integrated with any javascript+HTML project I worked on, leading me to believe there was a direct correlation between Node.js and vanilla Javascript+HTML. However, this misconception was shattered when attempting to u ...

If the value is not set for $_POST when sent via an AJAX request

I have set up a zii.widgets.jui.CJuiDialog to send a form via ajax to my controller. However, I am facing an issue where the post variable if(isset($_POST['Item'])) does not seem to be present when I test for it in the controller. I am trying to ...

Customizing the WordPress loop with different arguments for an alternate outcome

I want to display posts from a custom post type that have the category 'pin-post-to-homepage'. If there are no posts with this category, then I would like to show posts from a different post type. Below are the arguments. I believe I am very clo ...

Using jQuery to pass apostrophes from PHP into an input field

Currently, I am working with database information that includes a character of blah^s (I have replaced the ' character with ^ in order to locate apostrophes within the row). I am using preg_replace to add apostrophes back into the string. Everything i ...

introducing a feature on Facebook where users can post an image along with a description on their wall

Is there a way to customize the Facebook like action so that I can have the title, image, and description of my website displayed on the user's wall? I tried using the default Facebook like option available at http://developers.facebook.com/docs/refe ...