Using Ajax to set the file target dynamically

Let me start by saying that I prefer not to use JQuery for any suggestions. I'm not a fan of how JQuery has become the de facto standard within JavaScript.
Now, onto my issue:
I want to pass a variable to a function that will then use that variable as the path to the file in a .open() method. Here's what I have so far:
An example of how the function is called:
ajaxPost('chatlog.txt',null);

The function itself:

function ajaxPost(targetPath, toSend){
    var getMessage;
    if (window.XMLHttpRequest){
        getMessage = new XMLHttpRequest();
    }
    else{
        getMessage = new ActiveXObject("Microsoft.XMLHTTP");
        alert("Stop using Internet Explorer.");
    }
    getMessage.open("POST", targetPath, true);
    getMessage.onreadystatechange = function(){
        if (getMessage.readyState == 4 && getMessage.status == 200){
            alert(getMessage.responseText);
        }
    };
    getMessage.send(toSend);
}

Unfortunately, this doesn't seem to work for some unknown reason.

Answer №1

Upon reviewing your code, I noticed a logical issue:

  • The purpose of using the POST method is typically to send data to a backend server for processing. However, in your case, you are using the POST method to retrieve the 'chatlog.txt'. For this scenario, the GET method would be more appropriate initially.

  • If you still prefer to use the POST method instead of GET, it is possible to achieve similar results. However, you may encounter unexpected complications.

IDENTIFYING THE ISSUE:

Upon loading your page, I encountered an error in the console:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

This error implies the need to adjust the method being used. I made the following changes:

function ajaxPost(targetPath,toSend){
    var getMessage;
    if (window.XMLHttpRequest){
    getMessage=new XMLHttpRequest();
    }
    else{
        getMessage=new ActiveXObject("Microsoft.XMLHTTP");
        alert("Stop using Internet Explorer.");
    }
    getMessage.open("GET",targetPath,true);
    getMessage.onreadystatechange=function(){
    if (getMessage.readyState==4 && getMessage.status==200){
            alert(getMessage.responseText);
        }
    };
    getMessage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    getMessage.send(toSend);
}

After implementing these adjustments, the data was successfully retrieved as follows:

<b>Peck:</b> Hello World!<br/>#
<b>World:</b> Hello Peck!<br/>#

Answer №2

Include

sendRequest.setRequestHeader("Content-type", "application/json");

Ensure you specify this before sending the request. This informs the server about the data being sent through POST method.

Answer №3

Avoid using XMLHttpRequest as it is not recommended. If you are currently utilizing JQuery, consider implementing the following approach:

$.post( "test.php", {name: "John", time: "2pm"}).done(function( data )
{
  alert ("Success! Data received: " + data);
});

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

Show a loading indicator similar to a browser's loading animation during ajax requests

For example, if you go to your Facebook wall and scroll to the end of the page, Facebook will asynchronously load more wall posts. Alternatively, clicking on an image in a wall post will also trigger asynchronous loading of the image dialog with comments a ...

Exploring the concepts of nested If statements, for loops, and else if ordering within Javascript programming (FreeCodeCamp - lookUpProfile)

Currently tackling Free Code Camp's Javascript tutorials and encountering a roadblock on the "Contact Profile" <a href="https://www.freecodecamp.com/challenges/profile-lookup#?solution=%2F%2FSetup%0Avar%20contacts%20%3D%20%5B%0A%20%20%20%20%7B%0A%2 ...

Validating complex ASP.NET MVC objects using AngularJS

I am encountering an issue with validating my model in a subform using AngularJS. Despite making changes to the SearchPostCode values and seeing updates in classes, the error message fails to display, and the button remains disabled. <form novalidate&g ...

Error: Vuex commit fails due to JSON circular structure issue

Using Vue.js along with the vuex store, I make an API call to validate an item, which returns arrays of errors and warnings. Below is my vuex action : export function validateitemReview ({ commit, dispatch, state }, { reviewId, type, itemreviewData }) { ...

"Optimizing reload time for DIV content with jQuery's .load function is proving to be

I am currently facing an issue with a div that displays data from a database and a form that updates item quantities. After submitting the form, the div refreshes while a modal with a bootstrap spinner pops up to indicate it is loading. The problem arises ...

Disable the add to cart popup in Prestashop while keeping the ajax add to cart functionality active

Is there a way to turn off the popup that appears when adding a product to the cart using ajax? I've been looking through ajax-cart.js but couldn't find anything related to the popup. I don't want to completely disable the ajax add to cart f ...

The AJAX response did not include the <script> element

Currently working on a WordPress theme where I am implementing AJAX to load new archive pages. However, encountering an issue where the entire block of Javascript code is not being included in the newly fetched content. Let's say, initially the struc ...

How can I locate and substitute a specific script line in the header using Jquery?

I need to update an outdated version of JQuery that I have no control over, as it's managed externally through a CMS and I can't make changes to it. But I want to switch to a newer version of JQuery. Here is the old code: <script type="text/ ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

What methods are commonly used to calculate the bitsPerSecond rate for media recording?

Is there a specific formula that combines frames per second and resolution to determine the bits per second for video encoding? I'm struggling to figure out the appropriate values to use for specifying the bits per second for 720p, 1080p, and 4k video ...

Is there a different option than jQuery.ajaxSettings.traditional for use with XMLHttpRequest?

Is there a different option similar to jQuery.ajaxSettings.traditional for xmlhttprequest? or What is the method to serialize query parameters for an xmlhttprequest? ...

Does the process of reading a `stream` consume resources in Node.js?

Node.js utilizes a stream as an abstract interface for handling streaming data. The node:stream module offers an API to implement this stream interface. During my exploration of NodeJs streams, I encountered confusion over whether a stream was involved in ...

Suggestions for incrementing a button's ID every time it is clicked

I am working on a button functionality that increases the button id when clicked. Below is the HTML code for the button: <input type="button" id="repeataddon-1" name="repeataddon" class="repeataddon" value="add" > Accompanied by the following scr ...

Securely getting a data point from a pathway

Within my Angular project, I recently made the transition from using query string elements in URLs such as: http://www.whatever.com/products?productName=TheMainProduct&id=234234 To a route-based system like this: http://www.whatever.com/products/The ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Utilizing JSON parse/stringify for data manipulation

I'm seeking advice on manipulating JSON data using JavaScript, particularly with the stringify/parse methods. In this scenario, I start by creating a JSON string and then use parse to convert it into an object. However, my goal is to efficiently delet ...

Unable to successfully remove item by ID from mongoDB within a Next.js application

Currently, I am developing an application using NextJS for practice purposes. I'm facing challenges in deleting single data from the database with the findByIdAndDelete function. Error encountered: CastError: Cast to ObjectId failed for value "undef ...

Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention: switch ($i) { case "apple": echo "i is apple"; ...

AngularJS encountered an error while attempting to load a template: [$compile:tpload]

After developing my angularjs example app in my netbeans ide based local server, I encountered an issue when I tried to move the application to an nginx server. The browser displayed the following error message: Error: [$compile:tpload] Failed to load tem ...

Packages starting with @ are found in the Node.js ecosystem

What's the deal with libraries in Node.js starting with @ symbols? Is there a specific convention for this? I feel like I'm missing something obvious here. ...