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

Combine the arrays to utilize ng-repeat

I'm working with several arrays and I need to display them in a table using ng-repeat. Is there a way to combine arrays like name=[name1, name2] and type=[type1, type2] into a single array data=[..] so that I can use ng-repeat for data.name and data.t ...

refresh data storage in PhoneGap

Encountering the following error: Error: INVALID_STATE_ERR: DOM Exception 11 This error message pops up while attempting to run a query. Has anyone come across this issue before? function populateDatabase(tx) { tx.executeSql('DROP TABLE IF ...

Utilizing jQuery for AJAX requests on a timed loop

I'm puzzled by a situation involving an AJAX call within an interval. It seems that the code doesn't work as expected, and I'm wondering why. Initially, I had this code snippet which wasn't functioning properly: setInterval($.ajax({ ...

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

Passing an unpredictable amount of parameters to react router in a dynamic way

Within my React application, users have the ability to create both folders and files. A folder can contain an indefinite number of subfolders within it. Here is an example structure: Folder-1 |_Folder-1-1 |_Folder-1-2 |_Folder-1-2-1 |_Folder- ...

Generate Material UI sidebar components that are positioned above all other components

I am currently working on a sidebar component using the Material UI Drawer component. I am looking to add components that align side by side with the sidebar, similar to the green box shown in the image below. After attempting to code this, I ended up wi ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

The Vue.js application is failing to toggle the integrated code

I am new to using Vue and I am trying to create a vertical navigation bar. When the menu icon is clicked, the navbar should toggle. Here is my menu icon code: <button type="button" id="sidebarCollapse" class="btn btn-info [collapsed?'': ...

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

Create additional object property and include in current object's properties dynamically

I have a JSON object that looks like this: "highChart":{ "xAxis":{ "categories":[ "SYN 13 ", "Settlement", "Service Interaction", "FNOL", ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

Navigation bar theme toggle malfunctioning as anticipated

I'm experiencing an issue with the navbar theme change functionality. Whenever I click on the dark mode button, the theme changes for a brief moment and then reverts back to light mode. <!doctype html> <html lang="en"> <hea ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

Jquery click event functioning on one page but malfunctioning on another

On one page, the dropdown click function is working, but on another page, even though it's the same component and JavaScript file, it's not working. Here's the component: <li class="nav-item dropdown"> <a clas ...

What is the reason for Firefox displaying the "excessive recursion" error message?

I have been working on generating an area Google chart using the code below, but I am running into an issue where Firefox is showing me a "too much recursion" error. The chart currently only has one point for testing purposes. Can anyone provide some gui ...

Executing a PHP function within the same file using AJAX: A step-by-step guide

I've been exploring online tutorials to learn about ajax as it's a new technology for me. My main goal is to understand how to utilize two functions, create() and population(), in a php file. The create() function generates a form like this: ma ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Determine the hexadecimal color value by combining two different colors along with a specified percentage/position

Can a color in the middle of a gradient be calculated? var initialColor = 'FF0000'; var finalColor = '00FF00'; // At 50% between the two colors, it would result in '808000' var middleColor = determineMiddleColor(initialColor ...

Struggling with lag in MaterialUI TextFields? Discover tips for boosting performance with forms containing numerous inputs

Having some trouble with Textfield in my MateriaUI project. The form I created has multiple inputs and it's a bit slow when typing or deleting values within the fields. Interestingly, there is no lag in components with fewer inputs. UPDATE: It appear ...