Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far:

       var request = createRequest();
      var deletenode = node.id;
   window.alert("nodeid=" + deletenode);
       var vars = "deletenode="+deletenode;
       request.open("POST", "deletenode.php", true);
      request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       request.onreadystatechange = function() {
    handleRequest(request);
};
       request.send("deletenode=" + encodeURIComponent(deletenode));

This is my PHP file:

 <?php
 print_r($_POST);
 $node = $_POST['deletenode'];
 print "Node to be deleted: $node";
 ?>

I am not seeing anything in my PHP file. What could the issue be? My AJAX request seems to be working correctly. Thank you, and here is my handle request function:

function handleRequest(request) {
    if(request.readyState == 4){
        json= eval ("(" + request.responseText + ")");;

        closeButton.onclick = function() {
            node.setData('alpha', 0, 'end');
            node.eachAdjacency(function(adj) {
                adj.setData('alpha', 0, 'end');
                var request = createRequest();
                var deletenode = node.id;
                window.alert("nodeid=" + deletenode);
                var vars = "deletenode="+deletenode;
                request.open("POST", "deletenode.php", true);
                request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                request.onreadystatechange = function() {
                    handleRequest(request);
                };
                request.send("deletenode=" + encodeURIComponent(deletenode));
            });       
        }
    }
}

Answer №1

Always ensure that when sending data, you format it as key/value pairs -

request.send("deletenode=" + encodeURIComponent(deletenode));

Answer №2

It seems like there might be a mistake in the code you provided, such as missing curly braces and a double semicolon at the end of the eval line. Here's the corrected version with the extra curly braces added. Please take a look:

 function handleRequest(request) {
    if(request.readyState == 4){
        json= eval ("(" + request.responseText + ")");
        closeButton.onclick = function() {
            node.setData('alpha', 0, 'end');
            node.eachAdjacency(function(adj) {
                adj.setData('alpha', 0, 'end');
                var request = createRequest();
                var deletenode = node.id;
                window.alert("nodeid=" + deletenode);
                var vars = "deletenode="+deletenode;
                request.open("POST", "deletenode.php", true);
                request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                request.onreadystatechange = function() {
                    handleRequest(request);
                };
                request.send("deletenode=" + encodeURIComponent(deletenode));
            });
        }
    }
}

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

Experiencing difficulty adjusting the width of a Tumblr post with JavaScript or jQuery?

Calling all coding experts! I've been working on customizing a Tumblr theme, and everything is looking good except for one issue. I'm struggling to adjust the width of photos on a permalink (post) page. Check out this link: You'll notice t ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

Updating the basket/custom attribute on the cart page of WooCommerce with Product Add-ons

I have been experimenting with updating a custom field on the basket/cart page for each product using WooCommerce Product Add-ons. While I did manage to get a method working as a test, it's not an ideal solution and seems to be quite messy code. Stra ...

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Designing a sequential bar graph to visualize intricate data using AmCharts

I received the following response from the server in JSON format: [{ "data1": { "name": "Test1", "count": 0, "amount": 0, "amtData": [ 0,0,0,0 ], "cntData": [ 0,0,0,0 ], "color": "#FF0F00" }, "data2": { ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...

React JS - State values are not persisting and rendering properly upon clicking

Recently, I followed a step-by-step tutorial on creating a todo list using functional components. However, I encountered an issue when attempting to delete or mark items as complete in the list. In both the deleteHandler and completeHandler functions, I tr ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Are the form fields and database table fields sharing identical names?

Do you think it is a poor practice to use the same name for HTML form fields as for table field names? I'm creating dynamic SQL insert queries and currently, I am using regular expressions to change the names to match the corresponding database fields ...

Is there a way to iterate through this?

I have data that I need to loop over in JavaScript. Since it is not an array, the map function is not working. Can someone help me loop over it or convert it into an array so that I can iterate through it? { "7/15/2021": { "date": ...

Unable to locate the identifier 'BrowserWindow'

In the providers folder of electron.service.ts, I have the following code: import { Injectable } from '@angular/core'; // If you import a module but never use any of the imported values other than as TypeScript types, // the resulting javascrip ...

Once the hidden DIV is revealed, the Youtube video within it begins to load

I currently have a hidden DIV on my website that contains a YouTube clip. My goal is to load the video in the background once the page has fully loaded, so that it's ready to play when the user clicks the button to reveal the DIV. However, at the mo ...

Learn how to toggle between two different image sources with a single click event in JavaScript

If the button is clicked, I want to change the image source to one thing. If it's clicked again, it should change back to what it was before. It's almost like a toggle effect controlled by the button. I've attempted some code that didn&apos ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Customized Paypal button generated using user's email account

Can the PAYPAL button code below be modified to make it dynamic using a php variable? Here is the original code: <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_s-xclick"&g ...

Dynamic background image that fills the entire webpage, adjusts to different screen sizes, and changes randomly

Currently, I am working on designing a web page with a dynamic background image that adjusts responsively in the browser without distortion. The challenge is to randomly select an image from an array using jQuery. Unfortunately, my knowledge of jQuery is ...

What is the best way to retrieve a specific line from a PHP array containing multiple strings?

After setting a PHP variable named $user to $e->getUser(), when I try to echo $user, I receive an array with the following data: Array ( [user_id] => 1 [login] => test [pass] => *** [remember_key] => [pass_dattm] => ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Utilize mongoose-delete to bring back items that have been marked for deletion but are still

Whenever I remove an item from my list, it switches the properties of the data to true, marking it as deleted and moves it to the trash. However, when I try to restore the item from the trash, the deleted properties are no longer available and the data rea ...