When using jQuery's POST method, the "done" event is triggered, however, no data is being sent

I've been working on implementing AJAX form submission and wrote a function to handle it when the button is clicked:

function putUser() {
    $('button#putUser').on('click', function() {
        var user = $('input#user').val(),
            amount = $('input#amount').val(),
            what = $('input#amount').val(),
            country = $('input#country').val(),
            platform = $('input#platform').val(),
            formUrl = $('form#sendUser').attr('action');

        var data = {
            user: user,
            amount: amount,
            what: what,
            country: country,
            platform: platform
        }

        $.post(formUrl, $('#sendUser').serialize(), function() {
            alert('test');
        }).done(function() { alert('done')})

        return false;
    })
}

Although I receive the done alert, it seems that no data is being submitted. Everything appears to be in place, so where could the issue lie? The MySQL query appears to be functioning correctly.

Here's my PHP code:

if(isset($_POST['putUser'])) {
    $user = $_POST['user'];
    $amount = $_POST['amount'];
    $what = $_POST['what'];
    $country = $_POST['country'];
    $platform = $_POST['platform'];

    $query = mysql_query('INSERT INTO sells (id, user, amount, what, country, platform) '
        . 'VALUES (NULL , "' . mysql_real_escape_string($user) . '", "' . mysql_real_escape_string($amount) . '", "' . mysql_real_escape_string($what) . '", "' . mysql_real_escape_string($contry) . '", "' . mysql_real_escape_string($platform) . '")');

    if($query) {
        echo 'ok';
    } else {
        die(mysql_error());
    }
}

Answer №1

I suggest modifying the putUser parameter to a GET parameter.

<form action="sendUser.php?putUser">

php

if(isset($_REQUEST['putUser'])) {

js

function putUser() {
    $('#sendUser').on('submit', function() {
        var formUrl = $(this).attr('action');

        $.post(formUrl, $(this).serialize(), function() {
            alert('test');
        }).done(function() { alert('completed')})

        return false;
    })
}

I have also transitioned to using a submit event instead of click, allowing me to utilize this keyword rather than a selector.

Answer №2

Can you explain the function of $('#sendUser').serialize()? Is it used to gather data from a form that you have created?

UPDATE: You can try using dataType 'json' when posting - http://api.jquery.com/jQuery.post/

Answer №3

It seems like the data you're attempting to send is not being submitted correctly.

Please take note that the function $('#sendUser').serialize() has been replaced with your custom data object. Additionally, the method putUser has been included within the data object in order for the server-side code to recognize it properly.

You may want to consider using the following code snippet:

function putUser() {
    $('button#putUser').on('click', function() {
        var user = $('input#user').val(),
            amount = $('input#amount').val(),
            what = $('input#amount').val(),
            country = $('input#country').val(),
            platform = $('input#platform').val(),
            formUrl = $('form#sendUser').attr('action');

        var data = {
            putUser: true,
            user: user,
            amount: amount,
            what: what,
            country: country,
            platform: platform
        }

        $.post(formUrl, data, function() {
            alert('test');
        }).done(function() { alert('done')})

        return false;
    })
}

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

Is there a way to efficiently update specific child components when receiving data from websockets, without having to update each child individually?

Currently, my frontend requires updated data every 2 seconds. The process involves the frontend sending an init message to the backend over a websocket. Upon receiving this message, the backend initiates an interval to send the required data every 2 second ...

In the XHTML mode, MathOverflow's invaluable mathematical expertise shines brightly

I am interested in incorporating the unique “piece of valuable flair™” from MathOverflow onto my website. The issue I am facing is that I want my webpage to comply with XHTML5 standards, meaning it should be served with the MIME type application/xht ...

JQuery grid pagination bar mysteriously missing

I'm having an issue with a Jquery grid that is built on an HTML table. I've properly configured the grid properties, including implementing pager functionality with a page size of 10. However, I am unable to see the page up and page down buttons ...

Utilize local .json data within a React component

Here is a snippet from my local .json file: { "results": [ { "id": 1, "title": "2 bedroom apartment to rent", "location": "30 South Colonnade London E14 5EZ", "description": "The building offers a communal lifestyle which co ...

Reliable drop-down box is not functioning properly

I am new to AJAX and I came across a solution for my issue on this page, but I am having trouble getting it to work. I want the input #precio to change when I select an option in the select #producto. This is the code I have: <form action="actualizar ...

Any alteration made to the salary, bonus, or deduction in the table cells will automatically impact the total amount displayed

Greetings, I currently have a table with 5 columns Name Salary Bonus Deduction Total Ahmed 500 500 100 900 The calculation for the total is as follows: Total=Salary+Bonus-Deduction and the total should be displayed in red according to my c ...

"Although Vuex data is present, an error is being logged in the JavaScript console

I'm utilizing Vuex to retrieve data from a URL and I need to use this data in computed properties in Vue.js. What could be causing the issue? <script> import {mapGetters, mapActions} from "vuex"; computed: { ...mapGetters(["ON ...

What is the process for assigning a regular expression to an object?

As I work on editing a configuration file, I'm encountering some issues where things aren't quite functioning as expected. Below is the code snippet I am working with: config.module.rules.unshift( { test: "/ckeditor5-[^/\\ ...

Should I include one of the dependencies' dependencies in my project, or should I directly install it into the root level of the project?

TL;DR Summary (Using Lodash as an example, my application needs to import JavaScript from an NPM package that relies on Lodash. To prevent bundling duplicate versions of the same function, I'm considering not installing Lodash in my application' ...

Utilizing Ajax for validation on Telerik Kendo Grid with Change Event

I am working with a Telerik Kendo Grid that has a column listing medical diagnoses. The list is populated using a method in the controller. My task is to verify whether a newly added diagnosis is already present in the grid, and only allow adding diagnoses ...

Challenge with dynamic parent routes

In my React application, different routes are loaded through various parent URLs. For example: {["/sat/", "/act/", "/gre/", "/gmat/", "/toefl/"].map((path) => ( <Route key={path} path={path ...

How do I use React and Material-UI to efficiently display multiple tables from a complex JSON object containing multiple arrays of data?

Trying to come up with an innovative approach to generate a unique dynamic table component that can create individual tables based on the number of arrays in a dictionary object (essentially iterating through each array and generating a table). For my sce ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

Error: Unable to access the 'sid' property because it is undefined

I've been facing an issue where sending an SMS through Twilio's API Explorer works fine, but fails under my node installation. Despite a complete uninstall and reinstall, the problem persists. Error 7 Oct 21:28:37 - [nodemon] starting `node scr ...

What is the best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

Error: Unable to access the applicant's ID as it is undefined

I'm currently facing an issue with passing parameters from server.js to humanresources.js in a login request. Although the params are successfully printed out in server.js, they appear as "undefined" once passed on to the function in human resources.j ...

In relation to User Interface: Analyzing target tracking and studying the flow of time

Is there a way to track mouse cursor movements, button clicks, and click times to an external database using only CSS, HTML5, and Javascript? I am curious about the possibility of conducting usability studies in this manner. ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

Basic inquiries concerning Vue.js and JavaScript

Hey there, I recently developed a small app to practice my Vue skills. However, there are a few features that I would like to implement but I'm not sure how to do it just yet. <div class="container" id="app"> <div class="row"> <d ...

Decoding JSON on 9gag

I am trying to select a random image from the following URL: In order to display it correctly, I need to determine the size of the image. I am utilizing YQL to store the JSON result in a variable (referred to as source). After replacing 'https&apos ...