Attempting to transmit a text message to a PHP script using Ajax

Hey there! I'm facing a challenge while trying to send a string to a PHP file using AJAX. It seems like the http.send function is not working as expected, and I suspect there might be an issue in my code. (I'm fairly new to programming)

 mainlink= 'a link';
 id= 'an id';
 $(document).click(function(){
   var http = new XMLHttpRequest();
   var link = mainlink+id;
   http.open("POST", 'test.php', true);
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.onload = function(){
     if(this.status == 200) {
       console.log (link);
     }
   }
   http.send("link="+link);
 });

test.php:

<?php 
if (isset($_POST['link'])){
echo $_POST['link'];
} else{echo "error";}
?>

I have attempted using both GET and POST methods.

Answer №1

Yes, this solution is effective. Are you utilizing jQuery as a source? Simply insert the following code snippet within the head section of your webpage:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

It would be advisable to console log this.responseText instead of link in order to capture the server's response accurately. Here is the precise code implementation I employed for successful execution:

HTML:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
                var mainlink = 'a link';
                var id = 'an id';
                $(document).click(function(){
                    var http = new XMLHttpRequest();
                    var link = mainlink + id;
                    http.open("POST", 'test.php', true);
                    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    http.onload = function(){
                        if (this.status == 200){
                            console.log(this.responseText);
                        }
                    }
                    http.send("link=" + link);
                });
        </script>
    </head>
</html>

PHP:

<?php 
    if(isset($_POST['link'])){
        echo $_POST['link'];
    }
    else{
        echo "error";
    }
?>

To witness the functionality firsthand, visit this link. Ensure that the pathname for test.php is correctly specified.

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

Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method: function MyController($scope) { $scope.clock = new Date(); var updateClock = function() { $scope.clock = new Date(); }; setInterval(updateClock, 1000); }; The HTML asso ...

Sinatra application encounters internal server error resulting in AJAX request failure

I'm currently developing a game where a user's guess is submitted to the backend for evaluation and then feedback is returned in the form of an array. To achieve this, I am utilizing AJAX to fetch a set of data from a Sinatra backend. Below is th ...

What is causing my basic angularjs to not function properly?

In my angularjs test instance, I am using a global variable but the alert tag is not functioning as expected. This code snippet is from my first example on codeschool. Any thoughts on why the alert is not running? <!DOCTYPE html> <html xmlns="ht ...

Unusual $http Angular.js POST inquiry

Hey there, I'm facing a peculiar issue in my web development project. I have a table that acts as an input field where users can enter data and then send it back to the Spring Rest API. The data is received as a String and then parsed using the Gson l ...

Secure HyperText Transfer Protocol prevents JavaScript from executing

My website's HTTPS version is having trouble loading JavaScript. All scripts are hosted on the same server. I've attempted: <script type="text/javascript" src="https://server.tld/js/jquery.js"> <script type="text/javascript" src="//ser ...

Finding it challenging to retrieve the dynamically generated data from the PHP-MYSQL combination through jQuery AJAX

The question's title doesn't provide much information. Let me explain what I'm trying to accomplish here. Using jQuery, I have an HTML form that sends an AJAX request to a PHP file. The PHP file successfully returns the required data back to ...

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

Unable to track user (Mineflayer - Node.js)

Trying to track a player using the mineflayer library in Node.js, but encountering an error within the source code of the library itself. Attempted code: const mineflayer = require('mineflayer'); const { pathfinder, Movements, goals } = require( ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Challenges Encountered When Working with React.useState()

I am facing an issue where a new row is not appearing after clicking the button. Although the console.log output indicates that the row was added correctly to the tables variable. Another concern I have is why I can see the new row added to the table even ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Unable to integrate multiple webpack projects: Uncaught SyntaxError occurs due to a missing closing parenthesis after the argument list

My website features a section where clients can track their projects. One aspect of the site involves viewing a blueprint created using THREE.js and bundled with webpack. I have been tasked with adding another type of blueprint to the site. I have success ...

Send an array to Spring's controller using AJAX

I am currently encountering an issue while attempting to send an array of objects to a Spring controller using jQuery AJAX. Below is the snippet of Javascript code being utilized: var data = new Array(); $.each(products, function (i) { ...

Performing a task after a process has finished

Currently, I'm working with node JavaScript and facing an issue where I need to run a new function after a loop has completed. In the code snippet provided below, // loop through objects in data, to process it represents a basic for loop iterating ove ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

A more efficient approach to creating a personalized design

After realizing the original question was unclear and wouldn't solve my problem, I have decided to edit it and create a new one. For my project, I require a customized layout where users can move, resize, add, or remove each box according to their pr ...

Working with Angular's forEach method and handling null values

I'm encountering an issue where the array of selected devices is not getting the values when attempting to add multiple devices to a group. Can someone identify the problem or suggest an alternative method? I referred to http://www.dotnetawesome.com/2 ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...