John Davidson

javascript - call API and save to mySQL


I have a script which gets my users data from Strava and builds a JSON.

I would like to get this data saved into my database without me needing to click submit on a form as this script I plan to run at set periods using a cronjob.

I have saved the data to local storage but then Im unable to get it out into PHP variables, I've tried passing the javascript variables to PHP variables but that doesn't work, if i'm not mistaken the PHP runs first the javascript so my PHP variables are empty when it inserts into the database table.

      var strava_data_object = { 'activity_date': activity_date,
'commute': commute,
'distance': distance,
'activity_id': activity_id,
'activity_type' : activity_type };

// Put the object into storage
localStorage.setItem('strava_data_object', JSON.stringify(strava_data_object));

To test my PHP INSERT I saved a copy of my JSON to 'JSON/strava_data.json' and then ran the following code it all works as planned

//read the json file contents
$jsondata = file_get_contents('JSON/strava_data.json');

//convert json object to php associative array
$decoded_data = json_decode($jsondata, true);

//convert json object to php associative array
$distance = $decoded_data['distance'];
$type = $decoded_data['activity_type'];
$commute = $decoded_data['commute'];
$date = $decoded_data['activity_date'];
$activity_id = $decoded_data['activity_id'];


Maybe if I could save my results to my JSON folder using javascript rather than to the local browser storage but I don't know if it can be done, and if it can how?

below is my function for getting the data from strava

function getActivites(res){
const activities_link = `${res.access_token}`;
.then((res) => res.json())
.then(function (data){
activity_type = data[0]['type'];
// Check if Activity is Run, Walk or Cycle
if (activity_type == 'Run' || activity_type == 'Cycle' || activity_type == 'Walk' ){

activity_date = data[0]['start_date'];
activity_date = activity_date.slice(0,10);
distance_detail = data[0]['distance'] * 0.000621371;
distance = distance_detail.toFixed(2);
activity_id = data[0]['id'];
activity_name = data[0]['name'];
activity_name = activity_name.toLowerCase();

const subString = "commute";
{ commute = true; }
else { commute = false; }

var strava_data_object = { 'activity_date': activity_date,
'commute': commute,
'distance': distance,
'activity_id': activity_id,
'activity_type' : activity_type };

// Currently saving the object into local storage
localStorage.setItem('strava_data_object', JSON.stringify(strava_data_object));

// Wondering if there is a way to save Save Json file to a folder

window.confirm("something went wrong, please check your last activty on strava was a Run, Walk or Cycle!");

My Answer:
You can achieve this by sending the data from your JavaScript script to a PHP script using AJAX. Here's an example of how you can do this:

1. Modify your JavaScript script to send the data to a PHP script using AJAX:

var strava_data_object = {
'activity_date': activity_date,
'commute': commute,
'distance': distance,
'activity_id': activity_id,
'activity_type' : activity_type

// Send the data to a PHP script using AJAX
var xhr = new XMLHttpRequest();'POST', 'save_data.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('Data saved successfully');

2. Create a PHP script (save_data.php) to receive the data and save it to your MySQL database:

// Get the JSON data sent from the JavaScript script
$data = json_decode(file_get_contents('php://input'), true);

// Connect to your MySQL database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

// Insert the data into your database table
$stmt = $mysqli->prepare("INSERT INTO your_table (activity_date, commute, distance, activity_id, activity_type) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $data['activity_date'], $data['commute'], $data['distance'], $data['activity_id'], $data['activity_type']);

// Close the database connection

Make sure to replace 'localhost', 'username', 'password', 'database', 'your_table' with your actual MySQL database details.

By using AJAX to send the data to a PHP script, you can save the data to your MySQL database without needing to click submit on a form. You can then set up a cron job to run your JavaScript script at set periods to automatically save the data to your database.

Rate this post

3 of 5 based on 3402 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us