Is it possible to transfer data from javascript to php through ajax?

I am attempting to extract the data speedMbps from my JavaScript code using Ajax to send the data to my PHP script, but unfortunately, I am not receiving any output. My experience with Ajax is limited to implementing auto-completion feature.

<script src="//code.jquery.com/jquery-1.10.2.js"></script>          

<script>
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!
var imageAddr = "testimage.jpg"; 
var downloadSize = 2097152; //bytes

window.onload = function() {
    var oProgress = document.getElementById("progress");
    oProgress.innerHTML = "Loading the image, please wait...";
    window.setTimeout(MeasureConnectionSpeed, 1);
};

function MeasureConnectionSpeed() {
    var oProgress = document.getElementById("progress");
    var startTime, endTime;
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        showResults();
    }

    download.onerror = function (err, msg) {
        oProgress.innerHTML = "Invalid image, or error downloading";
    }

    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = imageAddr + cacheBuster;

    function showResults() {
        var duration = (endTime - startTime) / 1000;
        var bitsLoaded = downloadSize * 8;
        var speedBps = (bitsLoaded / duration).toFixed(2);
        var speedKbps = (speedBps / 1024).toFixed(2);
        var speedMbps = (speedKbps / 1024).toFixed(2);
        oProgress.innerHTML = "Your connection speed is: <br />" + 
           speedBps + " bps<br />"   + 
           speedKbps + " kbps<br />" + 
           speedMbps + " Mbps<br />";

        $.ajax({
          method: "POST",
          url: "test_select.php",
          data: {speedMbps: speedMbps },
          cache: false
        }).done(function( html ) {
            $( "#speed" ).val( html );
        });
    }
}

</script>

<input type="text" id="speed" name="speed" value="">

test_select.php

<?php
    echo $_POST['speedMbps'];

    if(isset($_POST['speedMbps'])){
        echo $speedMbps = $_POST['speedMbps'];
    }

?>

Answer №1

$.ajax({
      type: "POST",
      url: "test_select.php",
      data: {speedMbps: speedMbps },
      cache: false
    }).done(function( html ) {
        $( "#results" ).val( html );
    });

replace method:"POST" with type:"POST".

Answer №2

If you want to streamline your code, consider combining the top and bottom scripts and placing them after your jQuery hook to ensure the variables are correctly accessed.

Additionally, it appears that you have overlooked adding method: "POST" in your Ajax script. This is essential to specify the type of HTTP request being made. Since you are using $_POST in your .php file, the request types must align for proper functionality.

$.ajax({
  method: "POST",
  url: "test_select.php",
  data: {speedMbps: speedMbps },
  cache: false
}).done(function( html ) {
    $( "#results" ).val( html );
});

If you need more information about jQuery's ajax feature, you can refer to their documentation here: ajax docs

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

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Dealing with data manipulation in the realm of javascript

In the following code snippet, I am iterating through multiple URLs and extracting data (title and content) from each of them. My objective is to store this data for later use on another page, and thus it needs to be accessible using its respective title, ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

The function getCustomSearchContext is not properly functioning within the SilverStripe platform

I have designed a custom Album DataObject, outlined below, to be administrated in the CMS using ModelAdmin. Within the search filter, only the Name input field is currently available. However, I aim to incorporate an additional input field for Author. My ...

Best practices for efficiently utilizing setInterval with multiple HTTP requests in NodeJS

Imagine you have a collection with 3 to 5 URLs. You want to send requests every 5 seconds, one by one. Here is how I approached this: setInterval(() => { array.forEach(element => { request .get(element.url) .on('response', ...

"An interactive webpage utilizing HTML5 that transmits sensor information from an iPhone to a server

Recently, I have been immersed in a project that involves utilizing the gyroscope of an iPhone to manipulate items on a computer screen. To achieve this, I have been using an application called "Sensorlogger" which allows me to stream sensor data to the co ...

Node: Sending JSON Values in a POST Request

I am currently working with the index.js file below: var Lob = require('lob')('test_6afa806011ecd05b39535093f7e57757695'); var residence = require('./addresses.json'); console.log(residence.residence.length); for (i = 0; i ...

Showing the True/False data in Material-UI Table using React

I am currently working on a Material Table event log implementation. This event log is designed to receive data in the form of 'string' and 'boolean' values. While I am able to display the string values without any issue, I am facing di ...

Navigating through an array containing references to object IDs with Mongoose

In my meanjs project, I am receiving user input on the server with a specific request body structure: { transaction: { heading: '', items: [Object] }, something: {}, somethingAgain: {} } The format of the items a ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Performing code execution in MVC 5 View every 1 second

I am currently working on a MVC 5 web application and I have a question regarding performing real-time calculations in the view. Below is an example of my view code: var timeRemaining = Model.account.subscriptionEndDate - DateTime.UtcNow; Is there a way ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Implementing a 10-second alert display in selenium

Task at Hand: I need to display the alert on my page for a few seconds to allow reading. Is there any function in Selenium Web-driver that can help with this? I am new to automation and have been learning about explicit waits. I tried using explicit wait ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item. Can anyone provide some guidance? Thank you! This is the JavaScript used: <script> show() $(functi ...

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...