Attempting to create a function that runs other functions

Is there a way to call a JavaScript function from a PHP file using AJAX and the GET method?

I attempted to achieve this by including

<script type="text/javascript"> callFunction(); </script>

but it did not work as expected. Is there an alternative approach to accomplishing this?

function exec(func , arg) {
  func(arg); // executes the function
}

If a similar method doesn't exist, how can I successfully call a function with AJAX following a PHP request via the use of the GET method?

The error message I encountered when attempting this was:

'func is not a function'

Here is the snippet of my JS AJAX code:

                var emailVal = document.getElementById("email").value;
                var passVal = document.getElementById("password").value;
                var uVal = document.getElementById("username").value;
                var busVar = document.getElementById("businessname").value;
                var firstVal = document.getElementById("firstname").value;
                var params = "email=" + emailVal + "&password=" + passVal + "&businessname="+busVar + "&username="+uVal+"&firstname="+firstVal;
                var url = "business.php";
                http = new XMLHttpRequest();
                http.open("POST", url, true);

                //Send the proper header information along with the request
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

                http.onreadystatechange = function() {  
                    if(http.readyState == 4 && http.status == 200) {
                        console.log(http.responseText);
                        exececc(http.responseText , null);
                    }
                }

                http.send(params);

For reference, here is the relevant PHP code:

echo '<script type="text/javascript"> callFunction(); </script>';

Answer №1

Aha, I believe I've identified the issue here. It appears that you are passing a string to the executeFunction() method.

To resolve this, please ensure that the values assigned to the variables fnName and params are indeed strings, and not JSON objects. For example, you may need to use data["fnName"] to extract the function name from your data JSON object. As a troubleshooting step, you can always output these variables to the console to confirm their data type.

function greet($message) {
  console.log($message);
  return;
}

var fnName = "greet";
var params = "Hello there"

window[fnName](params);

Answer №2

Always remember to provide a correct function name when calling a function for execution, as shown below:

function displayMessage($message){
console.log($message);
}

function runFunction(fn,arg){
fn(arg);
}


runFunction(displayMessage,"Success, it's running!");

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

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

Sending a JS function to a PHP script

I've been incorporating the Soundcloud API into my project and successfully implemented their record button on my website. Once the upload is completed, the code generates the URL of the newly created soundcloud file. My goal now is to pass that URL ...

I am attempting to load the ajax content into separate divs simultaneously

When I attempt to load the ajax into two separate divs, I notice that despite calling for data to be placed in two different divs within the ajax code, it all ends up in one div. <script>$(document).ready(function(){ $.ajax({ url: "http: ...

Icon dropdown in Bootstrap

Looking for a solution to modify this dropdown using only bootstrap classes. Instead of the current text "Dropleft" and left arrow icon, how can I replace it with an icon fas fa-ellipsis-h? <button type="button" class="btn btn-secondary ...

Using AJAX call and jquery each loop to work with JSON syntax

I made an AJAX request that fetches data from PHP. echo json_encode($json_response); The output looks like this: [{"name":"Sprouts.......}] Next, I used JQUERY to iterate through the data using the following code: $.each($.parseJSON(data), function(i, ...

What is the best way to transform an HTML <script> tag into React code?

I am new to the world of JavaScript and React. Can someone help me convert the script below into a React component? <div id="SOHUCS" sid="xxx"></div> <script charset="utf-8" type="text/javascript" sr ...

The functionality of save() is not compatible with mongoose.Schema

const Information = require('./Models/Information'); ... let sampleData = new Information( dataSample ); sampleData.save( function ( error ){ console.log('testing); if ( error ) { console.log('Error occurred while saving Informa ...

How to make Ajax work within a ViewComponent in ASP.NET Core?

I was looking to streamline my comments section by placing it, along with the "post comment" button, within a ViewComponent. However, I encountered an issue where Ajax functionality did not seem to work within the ViewComponent. The same code worked perfe ...

Can you tell me the distinction between using RemoteWebDriver's executeScript() and Selenium's getEval() for executing

Can you explain the distinction between these two pieces of code: RemoteWebDriver driver = new FirefoxDriver(); Object result = driver.executeScript("somefunction();"); and this: RemoteWebDriver driver = new FirefoxDriver(); Selenium seleniumDriver = ne ...

Express JS routing encounters 500 error following the submission of a form button

I've been developing a unique chatbot that specializes in recommending songs based on the user's current mood. However, I've hit a roadblock when it comes to routing a response to the user after they submit their preferences through an HTML ...

Why do we need to use [`expression`] notation?

I've recently started exploring reactjs and I came across this code snippet: handleChange = event => { const { name, value } = event.target this.setState({ [name]: value, }) } I'm a bit puzzled about the notation used here: [name ...

JavaScript featuring Ajax functionality

Although I have limited experience in web programming, I am currently testing a simple add-on to integrate with my app. The webpage I have created displays multiple rows, each containing an editable field for user input. After the user inputs data into th ...

"Shopping just got easier with our new drag and drop feature! Simply drag items

I want to develop a Virtual Shopping Cart system. Items will be retrieved from a database. A virtual basket will be available. Users can drag items and drop them into the basket, similar to shopping in a mall. Once the user clicks the save button, the s ...

Preventing selection of past dates with Material UI in ReactJS

I'm currently working on a date range picker using react material ui. The goal is to allow users to select a specific date and then disable all past dates from that selected date onward. How can I go about implementing this functionality in react mate ...

Is CefSharp compatible with JavaScript promises?

I noticed that when I run the JavaScript code below in the console of my browser, it works perfectly fine. However, when I try to use this code in CefSharp, it returns null. I am currently using CefSharp version 100.0.120-pre. Does CefSharp 100.0.120-pre s ...

Issues with looping Jquery ajax请求

Is there a bug in the code? Here are some examples: for(i=0;i<2;i++){ $.ajax({ url : 'process.php', type: "POST", data : "abcd", success : function(data){ alert(i); } }) } or for(i=0;i<2;i++){ $.post("proc ...

Navigating through the various levels of organization within Meteor, it is

In my Meteor application, I am dealing with groups and items. Each item is associated with a group. Some groups are part of a larger hierarchy, where a group can contain subgroups. Here is an example of what the hierarchy might look like: Group 1 Su ...

What is the best way to JSON serialize a Django queryset in python?

When working with AJAX responses, I encountered an error while trying to serialize a queryset. The error message was: TypeError: 'Font: FontName' is not JSON serializable The code snippet using JSON response looks like this: ... return Json ...

Having issues with jQuery when trying to select only a single checkbox?

I have created a table with four rows and eight columns, each containing a checkbox. My goal is to allow only one checkbox to be checked per row. I am attempting to achieve this using jQuery. While it works in jsfiddle, I am experiencing difficulties in ge ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...