Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting inserted into my database. For the sake of brevity, I've included the HTML in this pastebin for reference.

Below is my php script:

<?php
if($_POST) {
$link = mysqli_connect(localhost, <removed>, <removed>, <removed>);

function val_data($data){
  $data = trim($data);
  $data = strip_tags($data);
  $data = mysqli_real_escape_string($link,$data);
  return $data;
}

$type = val_data($_POST['type']);
$size = val_data($_POST['size']);
$date = val_data($_POST['datepicker']);
$message = val_data($_POST['message']);
$steam = val_data($_SESSION['steamid']);
//Query
$sql = "INSERT INTO requests (type, size, fdate, steam64id, message) VALUES ('$type', '$size', '$date', '$steam', '$message')";
$query = mysqli_query($link, $sql);
mysqli_close($link);
}
?>

Here's the corresponding Javascript:

function hideModal() {
   $('#myModal').modal('hide');
}

$(document).ready(function() {
   $(document).on('submit', '#myModal', function() {
      var error = "";
      var type = document.getElementById("type").val();
      var size = document.getElementById("size").val();
      var date = document.getElementById("datepicker").val();
      var message = document.getElementById("message").val();

      if(type == "") {
         error = "A Job type is required";
         document.getElementById("sparam").innerHTML = error;
         $("type").focus();
         return false;
      }

      if(size == "") {
         error = "A Job size is required";
         document.getElementById("sparam").innerHTML = error;
         $("size").focus();
         return false;
      }

      if(date == "") {
         error = "A desired completion date is required";
         document.getElementById("sparam").innerHTML = error;
         $("date").focus();
         return false;
      }

      if(message == "") {
         error = "A description of the job is required";
         document.getElementById("sparam").innerHTML = error;
         $("message").focus();
         return false;
      }

      $.ajax({
         type: 'post',
         url: 'ajaxsubmit.php',
         data: {
            type:type,
            size:size,
            date:date,
            message:message
         }, 
         success: function(res) {
            $('#sparam').html("Thanks! We'll be in touch soon");
            setTimeout(hideModal, 5000);
         }
      });
      return false;
    });
  });

Answer №1

It's worth noting that using event.preventDefault() is a safer approach compared to using return false. It also simplifies the debugging process.

$(document).on('submit', '#myModal', function(event) {
      event.preventDefault();
      // Any errors thrown after this will prevent form submission

If an error occurs before the return false, it will block the remaining code execution within the function. As a result, without returning false, the browser will submit the form and reload the page. The return statement must be placed at the end of the event handler to work effectively.

In case such errors occur, debugging becomes challenging since they flash on the console briefly before both the page and console are cleared. This makes identifying and fixing those errors more difficult.

By preventing the default behavior first, any subsequent errors in the code won't allow form submission by the browser. However, the console remains accessible, making error detection easier and quicker.


Main issue:

You should replace the val() method, which is meant for jQuery objects not DOM nodes, with either value or simplify the DOM searches using jQuery.

var type = document.getElementById("type").val();

It should be changed to either:

var type = document.getElementById("type").value;

Or

var type = $("#type").val();

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

Solution: The issue where the children's onChange event was not updating the parent in Ant Design was discovered to be due to the Select and Table components nested inside a Tab not changing according to the pageSize

I'm facing an issue with updating a parent element when the children's onChange event is triggered. Specifically, I have an Ant Design Select and Table inside a Tab that are not reflecting changes in the pageSize value. Although setPageSize func ...

Angular filter is causing an error message saying "Unable to interpolate," but the filter is functioning as expected

I have implemented the filter below (which I found on StackOverflow) that works perfectly fine on one page. However, when using the same object, it throws an error as shown below: app.filter('dateFormat', function dateFormat($filter){ return f ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

Having trouble with the query string functionality in Laravel 5?

Within my code, I have utilized {!! URL::route('editCatForm',['id'=>$row->id]) !!} to navigate to the named route editCatForm with a query string of ?id=5 or any other value dynamically retrieved from $row->id @foreach($catego ...

Ways to incorporate a custom JavaScript function that is activated by an external server system?

I'm currently exploring a JavaScript widget that needs to operate within specific constraints: The widget initiates a request to a third-party server using a callback URL The third-party server pings the callback URL after a set period, triggering a ...

Understanding the distinction between deleting and nullifying in JavaScript

var obj = {type: "beetle", price : "xxx", popular: "yes" ,.... }; If I want to remove all the properties from obj, what is the correct way to do it? Should I use delete obj.type; delete obj.price; delete obj.popular ... and so on. Or should I set ob ...

How can you display Unicode characters within an HTML input element with type=submit value?

I am having trouble displaying a right facing triangle character after the main text on a form button based on a designer mockup. The code snippet causing issues is as follows: <input type="submit" value="Add to basket &#9654;" /> The desir ...

When I try to start the editor with HTML content using the convertFromHTML method, I encounter an error stating that

I am encountering an error when trying to initialize my Editor state with a HTML markup. at renderToString (/home/al/Documents/node/admin-next/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27) at render (/home/al/Documents/node/admin ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Steps to disable all fields if the previous field is set to its default value and the default value is currently selected

As a newcomer to AngularJS, I have successfully disabled fields based on previous field selections. However, my goal is to set the default value of "ALL" for all fields (country, state, city). If the country value is set to "ALL," then the state and city ...

Tips for improving the speed of loading infinite scroll pages

I am currently working on scraping over 100k rows from the provided URL. The data goes back approximately a month, loading in batches of 7-8 rows at a time. My current approach involves using a macro to scroll down the page slowly, which is effective but ...

What is the reason behind the Chrome icon flickering momentarily while loading certain web pages?

I recently put together a basic html document, here it is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <title>Just a test.</title> </head> <body> <svg ...

The Google Maps API allows all markers to be connected to a single infowindow

I've been grappling with this issue for some time now, but I just can't seem to find a solution! I'm retrieving data from a database in Laravel using Ajax and then attempting to display infowindows for each marker on Google Maps. The markers ...

Improper headings can prevent Chrome from continuously playing HTML5 audio

Recently, I encountered a peculiar and unlikely issue. I created a custom python server using SimpleHTTPServer, where I had to set my own headers. This server was used to serve .wav files, but I faced an unusual problem. While the files would play in an ...

What is the optimal method for sending an error response to an Ajax request?

After I call a WebMethod using ajax and return a simple string, the success method of the ajax code is executed without any errors. Here's an example: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string Hello() { ...

Looping through an array of nested objects using Vue

I have encountered a challenge with accessing specific data within an array that I am iterating over. The array is structured as follows, using Vue.js: companies: [ name: "company1" id: 1 type: "finance" additionalData: "{& ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

Create a self-bot that can generate a new server

I am currently working on a discord.js self-bot and I need assistance in creating a server. Any guidance would be greatly appreciated. I have experimented with the client.user method, but did not achieve the desired result. If it is not possible to c ...

The Calendar Extender does not appear when used with masterpages

I'm having trouble with my masterpages as I can't seem to get my calendarextender to display after going through numerous solutions. Take a look at my code below: http://pastebin.com/m789f935e ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...