Issue with Ajax: parameters failing to pass without using jQuery

It appears that I am only receiving jQuery results, but I am in search of the correct method to pass parameters via AJAX without using libraries or old browser fallbacks. If there is another thread discussing this topic that I have overlooked, please provide a link =)

The code snippet I am using includes $, however, it is not jQuery, but rather a custom object/implementation.

$.ajax({
    't':'POST',
    'u':e, 
    'd':{ajax:'1'},
    's':function(data){
        console.log(data.response);
        document.getElementById('mainc').innerHTML = data.response;
    },
    'e':function(data){
        console.log(data);
    }
});

This triggers:

$.ajax = function(a){
if(!a.u){return false;};
a.t=a.t||"GET";
typeof a.a=='undefined'?true:a.a;
a.e=a.e||function(){return false;};
a.s=a.s||function(){return true;};
var x=new XMLHttpRequest();
x.open(a.t,a.u,a.a);
x.onreadystatechange=function(){
    if(x.readyState===4){
        if(x.status===200){
            a.s(x);
        }else{
            a.e(x);
        }
    }
};
a.t==="post" ? x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : null;
x.send(a.d);

}

x.send(a.d) should transmit the {ajax:'1'} parameter. I have tested {'ajax':'1'} and just 'ajax=1' as well. It seems that none of the parameter variations successfully make it to the server side. Despite the request being sent and received without problems, the parameters do not appear to reach the server.

Answer №1

XMLHttpRequest.send() does not support javascript / JSON objects if you specify

x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
.

To fix this, you need to format the variables as urlencoded as explained in this post:

Query-string encoding of a Javascript Object

Alternatively, you can set

x.setRequestHeader("Content-Type", "application/json")
as suggested in another answer.

Also note that:

a.t==="post" should be changed to a.t==="POST" as request headers are case-sensitive.

Here is the full working code (with urlencoded data):

$ = {}

$.ajax = function(a){
if(!a.u){return false;};
a.t=a.t||"GET";
typeof a.a=='undefined'?true:a.a;
a.e=a.e||function(){return false;};
a.s=a.s||function(){return true;};
var x=new XMLHttpRequest();
x.open(a.t,a.u,a.a);
x.onreadystatechange=function(){
    if(x.readyState===4){
        if(x.status===200){
            a.s(x);
        }else{
            a.e(x);
        }
    }
};
a.t==="POST" ? x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : null;
x.send(a.d);

}    

$.ajax({
    't':'POST',
    'u':'/', 
    'd':"ajax=1",
    's':function(data){
        console.log(data.response);
        document.getElementById('mainc').innerHTML = data.response;
    },
    'e':function(data){
        console.log(data);
    }
});

Answer №2

For better results, consider adjusting the request header to:

x.setRequestHeader("Content-Type", "application/json")

Explore more details here.

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

add a hyperlink within a mouse click action

Looking for a way to make phone numbers clickable on mobile devices? Check out this script! I've implemented a script that displays a phone number when users click 'call us' and sends a Google Analytics event. However, I'm having troub ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

What is the most efficient way to utilize a single connection to interact with MongoDB?

I have a series of functions that are responsible for running various queries. Here is the code I am working with: var MongoClient = require('mongodb').MongoClient; async function createDatabase() { MongoClient.connect(urlMongoDB, function(er ...

What are the possible reasons for the corruption of files by the asp.net fileupload control

When using the FileUpload control to upload multiple files, they are successfully uploaded. However, a problem arises when downloading the files afterwards - they become corrupt, whether they are .pdf, .docx or another file type. Upon inspecting the server ...

Transforming the output of a PHP script from an HTML table into an ion-list format tailored for the Ionic framework

Currently I am working on an application built with the Ionic framework. I have developed a PHP file to retrieve 'Users' data from my database and it is currently being displayed in an HTML table format. In the services section of the framework, ...

Webster Barron code script

I'm attempting to replicate the concept of this video https://www.superhi.com/video/barron-webster using text, but I am encountering difficulties in achieving the desired effect. The design text is currently overlapping my name and displaying in rev ...

Converting a multidimensional array from PHP to JavaScript in Symfony 4

Greetings! I have an array in Symfony within my controller that looks like this: $array = [ "label" => [ "january", "february" ], "data" => [ 0, 1 ] ]; I am loo ...

Issue with switch statements in PHP/JavaScript causing unexpected 'undefined' behavior

Exploring a switch statement: var currency = ""; switch (row.currency) { case 1 : currency = "&pound;"; break; case 2 : currency = " &#36;"; break; case 3 : currency = "&euro;"; break; default: currency = "&po ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

Refresh the table every couple of seconds

I need to regularly update a table every two to three seconds or in real-time if possible. The current method I tried caused the table to flash constantly, making it difficult to read and straining on the eyes. Would jQuery and Ajax solve this issue? How c ...

How to keep the show/hide effect active in jQuery even when the user presses the backspace

I recently came across this code snippet on a fiddle: https://jsfiddle.net/htz8x1no/ that I'm working with. Here's the code in question: $('.relevant-results').hide(); $('#input').keyup(function() { if ($ ...

Having trouble getting your jQuery code to work in your HTML document after converting it to

Recently, I've been working with HTML5, CSS, and vanilla JavaScript. I wanted to convert this jQuery code and make some changes to it. However, I seem to be encountering an issue after implementing the new code. The original code had a small triangu ...

Ways to determine if the keys of an object are present in an array, filtered by the array key

Working on an Angular 2 Ionic application and I'm wondering if there's a straightforward way to filter individuals by age in a specific array and then verify if any key in another object matches the name of a person in the array, returning a bool ...

What is the reason behind my page automatically scrolling to the bottom when it loads?

I am currently working on a project for my company, and unfortunately, I cannot share the code as it is proprietary. However, I am encountering a problem where the page loads and automatically scrolls to the bottom. I have checked for any unclosed tags in ...

applying various conditions to JavaScript arrays for filtering

After spending countless hours trying to solve my filtering issue, I'm still struggling. I'm in the middle of creating a react marketplace where users need to be able to apply multiple filters on one page. Here's an example of my product lis ...

Why does this code snippet throw an error if let is not hoisted or in the temporal dead zone? It could have simply used the global reference instead

var b = 6; { console.log(b) let b = 55 } When running this code snippet, I encounter the following error message: ReferenceError: Cannot access 'b' before initialization Why is the console.log(b) not displaying 6 as expected? ...

Encountering the error message "Unable to instantiate User: constructor not found" while testing API functionality for

Currently, I am in the process of integrating my backend with MongoDB ATLAS. In order to achieve this, I am utilizing express, mongoose, and node.js for testing purposes. Specifically, I am focusing on testing my API routes, such as adding a user. Below i ...

"Error encountered: 'require' is not defined in the bundled JS file for

Recently, I decided to try my hand at Django and ReactJS. While attempting to compile a simple JSX code to JS, I followed this tutorial: . However, I encountered an error that prevented it from working. I then resorted to using npm run dev to compile the c ...