Storing JavaScript functions in a MySQL database

Is there a way to save the output from a JavaScript function to MySQL?

    var macs = {
        getMacAddress : function()
        {
            document.macaddressapplet.setSep( "-" );
return (document.macaddressapplet.getMacAddress());
        }
    }

document.write(macs.getMacAddress());

I've been advised to use ajax, but I'm struggling to figure it out. Any help would be greatly appreciated. Thank you!

Answer №1

To achieve this functionality, utilizing AJAX is the recommended approach. While it's possible to accomplish the task using vanilla Javascript, it tends to result in messy code. Personally, I always opt for using a library like jQuery for smoother implementation. With jQuery, the code would look like this:

<input type="button" id="sendmac" value="Send MAC Address">

And the accompanying jQuery script would be:

$(function() {
  $("#sendmac").click(function() {
    document.macaddressapplet.setSep( "-" );
    $.post("savemacaddress.php", {
      getMacAddress: document.macaddressapplet.getMacAddress()
    });
  });
});

For the PHP script savemacaddress.php:

<?php
$addr = $_POST['savemacaddress'];
$addr = mysql_real_escape_string($addr);
$sql = "INSERT INTO macaddress ('$addr')";
mysql_connect(...);
mysql_query($sql);
?>

It is assumed that PHP is being used for this scenario.

Answer №2

const macID = getMacID();

// If you are utilizing jQuery - an AJAX library can be incredibly helpful

$.get('/submit-macID.php?macID=' + macID, function() { alert('Submission successful!'); })

Next, in the PHP section, you would typically execute something like this:

mysqli_query('INSERT INTO macIDs SET macID = ' . mysqli_real_escape_string($_GET['macID']));

It goes without saying that you'll also need to incorporate additional error handling and security measures.

Answer №3

Thank you for the swift response...

The code has been placed in create_user.php

var macAddress = getMacAddress(); 
$.get('/send-mac.php?mac=' + macAddress, function() { alert('Process completed successfully'); })

Could you please elaborate on the function, "$.get('/send-mac.php?mac=' + macAddress, function() { alert('Process completed successfully'); })"?

Also, can you verify the availability of checkAvailability,

mysql_select_db($databaseName);
$sql = mysql_query("SELECT * FROM user WHERE UserID = '" . $_POST['newUserID'] . "'");
mysql_query('INSERT INTO test SET macAddress = ' . mysql_real_escape_string($_GET['mac']));  

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

Ways to dynamically combine a group of objects

I'm grappling with a challenge involving an array containing two objects. After using Promise All to fetch both of these objects, I've hit a roadblock in trying to merge them dynamically. Despite experimenting with various array methods like map, ...

The use of Ajax post results in the retrieval of multiple arrays containing objects that possess various values

I have a PHP file (ajax.php) that retrieves messages from a database and a JavaScript file (main.js) that sends an AJAX request to this PHP file. My goal is to create a table row in the JS file for each message returned by the PHP file. Main.js: functio ...

The Ionic2 http post request is missing the 'Access-Control-Allow-Origin' header

Here is the complete code snippet: this.http.post(link, data, { headers: headers }) .map(res => res.json()) .subscribe(data => { this.data.response = data._body; }, error => { console.log("Oops! An error occurred"); ...

The parameter type 'string | null' cannot be assigned to the value function 'ValueFn<SVGPathElement, Datum[], string | number | boolean | null>'

I recently delved into the world of d3 and attempted to create a simple line chart using d3, TypeScript, and react. However, I keep encountering a TypeScript error whenever I try to implement it. Strangely, I can briefly see my chart before it disappears a ...

Stop the duplication of downloading JavaScript files

When it comes to my website, I have incorporated sliders that stream videos from Vimeo. Upon running a check on GTMetrix, I noticed an overwhelming number of http requests. Looking at the waterfall, I discovered numerous duplicate downloads of javascript, ...

nuxt-link: take me to the identical position with the hash in the URL

I'm facing an issue with the <nuxt-link> component in my Nuxt application: The first time I click on the link, everything works perfectly and the page is changed as expected. However, if I scroll down a bit and try clicking the link again, noth ...

Sending back the requested information in C to the ajax (jquery) CGI

After fetching specific data using C in my jQuery, how can I appropriately transfer the data to C? function Run() { $.ajaxSetup({ cache: false }); var obj = {"method":"pref-get","arguments":{"infos":["sys_info"]}}; alert("Post Json:" + JSO ...

Utilizing the power of Material-UI with React in conjunction with Python-Django: A comprehensive

I am seeking guidance on implementing React with Material UI components in my web application. The technologies I have utilized in multiple projects include: Materialize CSS, Javascript, Jquery. The technologies I wish to explore for future projects are ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Leveraging JavaScript for Validating Radio Buttons

I've been following a tutorial guide on this specific website , but I'm encountering some difficulties despite following the exact steps outlined. Can someone provide guidance? Here is what I have done: <html> <script> fu ...

Unable to iterate through nested arrays in Contentful mapping

I am facing an issue while trying to map further into the array after successfully retrieving data from Contentful. The error message field.fields.map is not a function keeps popping up and I can't figure out what I'm doing wrong. export defau ...

Encountering the error message "Cannot GET /" when trying to access the front page using Express.js

I am a beginner in Node.js. I have been learning through videos and documentation, and I started developing a site following an MVC structure. The node server appears to be working fine, but I am facing an issue where the front end displays 'Cannot GE ...

Issue with Tooltipster plugin causing jQuery function not to trigger upon clicking the link within the tooltip

Recently, I've been experimenting with a jquery plugin called Tooltipster by inserting some HTML into the tip with an href link. The problem arises when I try to add a class to the href and fire a jquery function upon clicking it. No matter how much I ...

Unable to set custom claims using Firebase Auth's setCustomClaims() method

I am encountering an issue with setting custom claims for Firebase Authentication service's token. I am using a Cloud function to establish the custom claims for Hasura. The cloud function is triggered upon the creation of a new user to set the custom ...

AngularJS: iterating through POST requests and passing each index into its corresponding response

Using AngularJS, I am attempting to execute multiple http POST requests and create an object of successfully finished requests. Here is a sample code snippet: var params = [1, 2, 3], url, i, done = {}; for (i in params) { url = '/dir ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

Concealing and revealing an element using the CSS property visibility:hidden/visible

There are two div-boxes that should show/hide when clicking on another two div-boxes. I want the divs to maintain their space so as not to disrupt the DOM, ruling out the use of .toggle(). I attempted this approach without success: $('#red, #pink&ap ...

"Encountering issues with autocomplete feature loading empty data when attempting to populate several fields simultaneously

Encountering issues with autocomplete when trying to select a value and fill in multiple fields. Seeing small blank lines on autocomplete and search stops while typing. Suspecting the problem lies within .data("ui-autocomplete")._renderItem or ...

Choosing multiple images by clicking on their alternative text with jQuery

I am currently working on a project that involves clicking on a thumbnail to enlarge the image and display its name (alt) below it. I have made progress, but there seems to be an issue where only one image is displayed no matter which thumbnail I click on. ...