Performing an Ajax POST request using jQuery

I am currently working on modifying my code to use POST instead of GET to send variables to a PHP page. The current code sends data via GET and receives it in JSON format. What changes should I make in order to pass the variables to process_parts.php using POST?

function imagething(){
    var done = false,
    offset = 0,
    limit = 20;
    if(!done) {
        var url = "process_parts.php";

        $.ajax({
            type: "POST",
            data: {offset: offset, limit: limit},
            url: url
        }).done(function(response) {

            if (response.processed !== limit) {
                // asked to process 20, only processed <=19 - there aren't any more
                done = true;
            }
            offset += response.processed;
            $("#mybox").html("<span class=\"color_blue\">Processed a total of " + offset + " parts.</span>");
            alert(response.table_row);
            console.log(response);
            imagething(); //<--------------------------recursive call
        }).fail(function(jqXHR, textStatus) {

            $("#mybox").html("Error after processing " + offset + " parts. Error: " + textStatus);

            done = true;
        });
    }
}
imagething();

Answer №1

To modify the default method from GET, simply adjust the type parameter in your request. You also have the option to pass your querystring properties as an object instead of exposing them immediately in the URL:

var endpoint = "process_parts.php";

$.ajax({
    url: endpoint,
    type: 'POST',
    data: {
        offset: offset,
        limit: limit
    } 
}).done(function() {
    // continue with the rest of your script...
});

Answer №2

Give this a shot!


$.ajax({
    url: "URL",
    type: "POST",
    contentType: "application/json;charset=utf-8",
    data: JSON.stringify(ty),
    dataType: "json",
    success: function (response) {
        alert(response);
    },

    error: function (x, e) {
        alert('Failed');
        alert(x.responseText);
        alert(x.status);
    }
});

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

jQuery counter no longer updates when scrolling

I'm having trouble with my jQuery counting function when using the scroll feature on a specific div ID. The numbers freeze if I keep scrolling before they finish updating on the screen. Whenever I scroll to the defined div ID, the counting function k ...

FullCalendar, showcasing real-time event creation as you select dates

I am currently utilizing fullcalendar 4 on my website and I am attempting to incorporate an indicator for when a user selects a date on the calendar. While the background color changes, it's not very visible. My aim is to replicate the functionality ...

Bring in JS into Vue from the node_modules directory

Apologies for my limited knowledge in this area, but I am currently working on integrating and importing This Grid System into my Vue project. However, I am facing some challenges. Typically, I import plugins like this: import VuePlugin from 'vue-plu ...

Implementing AJAX to populate a dropdown list: A step-by-step guide

I have a question about populating options in a select dropdown using AJAX. Can you spot any errors in my code? Below is the snippet from my View: $(function() { $.getJSON("Animes/GetCategories", null, function(data) { var options = '&a ...

When working in React, I encountered a problem with the for of loop, as it returned an error stating "x is undefined." Although I could easily switch to using a simple for loop, I find the for of loop to

I'm encountering an issue when using a for of loop in React, as it gives me an error stating that "x is undefined". import { useEffect } from "react"; export default function HomeContent() { useEffect(() => { let content = document ...

When the jquery loop fails to function

I need to dynamically add a class to a specific tag using jQuery depending on an if condition. Here's the code snippet: if ($(".asp:contains('Home')")) { $("ul.nav-pills a:contains('Home')"). parent().addClass('active ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Tips for triggering several functions with a single onClick event in React?

I am currently working on a React Project where I have defined several functions to set conditions for rendering components on the page. However, I now need to be able to call all these functions again within the components when a button is clicked, in ord ...

How can I create an asynchronous route in AngularJS?

I implemented route and ngView to display dynamic content, however I received a warning message: The use of Synchronous XMLHttpRequest on the main thread is deprecated due to its negative impact on user experience. For more assistance, please refer to ...

mentioning a Windows Communication Foundation (WCF) web service

Our current project is utilizing an asmx service. While we want to maintain this service, we are interested in adding another wcf service for making ajax calls. I recently setup the service following instructions I found online and it's working well ...

AngularJS - Sending configuration values to a directive

I'm trying to figure out how to pass parameters (values and functions) to an Angular directive. It seems like there should be a way to do this in Angular, but I haven't been able to locate the necessary information. Perhaps I'm not using th ...

What is the process of converting TypeScript to JavaScript in Angular 2?

Currently diving into the world of Angular 2 with TypeScript, finding it incredibly intriguing yet also a bit perplexing. The challenge lies in grasping how the code we write in TypeScript translates to ECMAScript when executed. I've come across ment ...

Swagger is unable to locate a user schema when utilizing Yaml files

Hello, I am a beginner using Swagger and trying to create simple endpoint documentation. However, I am facing an issue with my schema type and cannot figure out what's wrong. To start off, I organized my folder structure in the root src directory whe ...

Tips for inserting information into data tables

Let me begin by outlining the process I am undertaking. I interact with a remote JSON API to retrieve data, perform some basic operations on it, and ultimately produce a data row consisting of three variables: Date, name, and message (think of an IRC chat ...

develop a hidden and organized drop-down menu using the <select> tag

I am currently developing a website for a soccer league. The site includes two dropdown lists with specific criteria, where the options in the second dropdown are limited based on the selection made in the first dropdown. My goal is to initially hide cer ...

javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...

The python-pyinstrument is in need of a javascript dependency that seems to

As I attempt to profile my Python program using pyinstrument, I encounter an error when trying to view the profile in HTML format. Traceback (most recent call last): File "/home/ananda/projects/product_pred/025200812_cpall_ai_ordering_model_v2/.venv ...

What is the functionality of this.$eval in Vue.js?

During the process of updating an unfamiliar old script from version 0.11 to 2.5.4, an alert popped up stating: To address the warning message saying 'Replace this.$eval('reportData | reportFilter false') with a solution using normal Java ...