What could be the reason behind my inability to initiate this PHP file through jQuery/AJAX?

I'm experiencing an issue with a piece of PHP code (located at ../wp-content/plugins/freework/fw-freework.php).

<div id="new-concept-form">
        <form method="post" action="../wp-admin/admin.php?page=FreeWorkSlug" class="form-inline" role="form" onsubmit="addNewConcept()">
            <div class="form-group">
                <label for="new_concept_text">Nuovo concetto:</label>
                <input type="text" class="form-control" id="new_concept_text">
            </div>
            <div class="form-group">
                <label for="new_concept_lang">Lingua:</label>
                <select class="form-control" id="new_concept_lang">
                    <option>it</option>
                    <option>en</option>
                    <option>de</option>
                    <option>fr</option>
                </select>
            </div>
            <button type="submit" class="button-aggiungi btn btn-default">Aggiungi</button>
        </form>
    </div>

Upon clicking the button, the following JavaScript function is triggered successfully:

var ajaxphp = '../wp-content/plugins/freework/fw-ajaxphp.php';

function addNewConcept()
{
conceptName = document.getElementById('new_concept_text').value;
lang = document.getElementById('new_concept_lang').value;

alert('Inserting: ' + conceptName + " " + lang);

$.ajax({
    type: 'POST',
    url: ajaxphp,
    async: true,
    dataType: 'json',
    data: {conceptNm : conceptName, conceptLang : lang },
    success: function() {
        alert("--------------------------------  Data sent!!");
        console.log("--------------------------------  Data sent!!");
    }

});

return true;
}

However, I am unable to call another PHP file through AJAX. The expected alerts and console logs within the success function are not being displayed.

<?php
// HTML Page -> JavaScript -> fw-ajaxphp.php -> XML Vocabulary

echo 'alert("PHP called")';
// echo $_POST['conceptNm'];
// TODO change vocab when done testing
$xml_file = '../wp-content/plugins/freework/fw-custom-vocabulary-test.xml';

$xml_vocab = new DOMDocument;
if (isset($_POST['conceptNm']) && isset($_POST['conceptLang']))
{
    // ADD NEW CONCEPT
    echo 'alert("PHP chiamato")';
    // irrelevant business code here...
    echo 'alert("Modifica avvenuta")';
}
?>

The required jQuery/Bootstrap libraries are included in both the main HTML file and the HTML-generator PHP file (and are functioning properly).

Despite my attempts to resolve this issue by following various Stack Overflow answers, I have been unsuccessful in calling the server-side PHP script as a response to button clicks. The business code is irrelevant for now; the button trigger should at least call the alert outside of the if condition block. All of the files are located in the same folder as shown in this image: Files on Server. Can someone provide insight as to why I am unable to call this PHP script from JavaScript? Thank you.

EDIT: I have found a solution by taking a completely different approach. I am no longer using jQuery; instead, the page will be refreshed whenever a form is submitted and data will be retrieved through POST in the same file that generates the HTML. I do not understand why the original method of calling the server-side PHP script did not work in my case, as it has worked in other scenarios. Nonetheless, thank you all for your assistance.

Answer №1

This is the issue you're facing:

$.ajax({
    type: 'POST',
    url: ajaxphp,
    async: true,
    dataType: 'json',
    ^^^^^^^^^^^^^^^^ Incorrect data format

Then you execute:

<?php
// HTML Page -> JavaScript -> fw-ajaxphp.php -> XML Vocabulary

echo 'alert("PHP called")';
...

You have specified that the expected response data format is json. However, in your php script, you are outputting strings. As a result, your ajax call will fail as jQuery cannot interpret the returned data as json.

To resolve this issue, removing the dataType line should be sufficient. Keep in mind that without it, you won't be able to use the returned data as an object. Nevertheless, for this specific example where you aren't utilizing the returned data, this shouldn't pose any problem.

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

A DataTable featuring a contextual menu, the ability to make multiple selections, and the ability

My dataTable is quite complex, with the ability to edit a single row, select multiple rows, and display a context menu for each row. Single row editing and multiple selection are working fine, but the issue arises when trying to open a contextMenu on a rig ...

Potential memory leak detected in EventEmitter by Discord.js

One night while my bot was running on auto-pilot as I drifted off to sleep, a warning popped up out of the blue: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 guildMembersChunk listeners added to [Client]. Use emitter.setMaxLi ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

Pug: perform a task depending on the presence of an element within a variable

I'm currently working with Express js to create a web application. I make use of an API to fetch some data, which is then sent to a pug file in the following format. res.render('native.pug', {product_name: body.products, cart_items:body.car ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Having issues with incorporating a component into another component in VueJS

Having spent approximately 30 hours on diving into VueJS, I am encountering some difficulties when it comes to using a component within another component. Seeking assistance from someone knowledgeable in this area to provide me with some clarification. Pr ...

How to Set a Background Image for a Div in React?

render(){ const { classes } = this.props; const { imageDescription } = this.props.imgDesc; const { currentIndex } = this.state; var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`; con ...

Incorporating a JavaScript code into my SharePoint master page to automatically deselect a checkbox resulted in updating the page title

I've integrated the following JavaScript code into my SharePoint master page: <script type="text/javascript> function DefaultUploadOverwriteOff() { if (document.title== "Upload a document") { var input=document.querySelectorAll("input"); ...

jQuery Validate enabling submission even with invalid fields

I have encountered an issue with validation on an ASP.NET MVC form that uses jQuery Validate. The form contains multiple fields, all of which validate correctly except for the last field called 'AmtRemaining'. This particular field has an initial ...

Delete particular user inputs following a $.ajax request

I have created a search feature with inputs that allow users to search the database using ajax requests. Unfortunately, I am facing an issue where the response from the server includes the search inputs themselves. This is not what I want. Here's a ...

Avoid displaying duplicate items from the array

Utilizing react js, I am attempting to iterate through an array of objects and display the name of each object in the array: const arr = [ { name:"Bill", age:88 }, { name:"Bill", age:18 }, { name:"Jack", age:55 }, ] ...

Error: Unable to locate module - The specified file cannot be resolved when utilizing an external JavaScript library

I am currently integrating a WYSIWYG editor (TUI Editor) into my Angular2+ application. Since there is no official Angular wrapper available, I have decided to create my own based on an existing wrapper. Due to some installation issues with npm, I saved t ...

Expanding list item with jQuery

I am facing an issue with the dropdown functionality of my <li> elements. The problem occurs when clicking on the 4th option, as the expander appears on top instead of dropping down beneath the list item. If you check out this jsFiddle, you can see ...

Steps to remove a package from the npm registry

Is it feasible to eliminate or erase a complete module from the npm registry? Please be aware that using npm -f unpublish does not permit the deletion of packages older than 24 hours. ...

Swap out a component for another using a higher order component (HOC perhaps?)

I have noticed that certain libraries like "framer-motion" in react utilize this syntax, for instance to include an animated H1: <motion.h1> where the h1 tag is enhanced with animations specified in the component's props. What confuses me is ho ...

Troubleshooting: Issue with v-link to classname in Vue.js

This is the code I am working with: <div v-link="'/work/' + {{data.useClass}}" class="itemImg {{data.useClass}}"> When rendered in the browser, it looks like this: <div class="itemImg x50"> The expectation is that class="itemImg { ...

What are the reasons why emails are not being sent in CodeIgniter?

My email function using CodeIgniter Version 2.2.1 is encountering errors. Below is the PHP code snippet: $config = array( 'protocol'=>'smtp', 'smtp_host'=>'ssl://smtp.googlemail.com&a ...

Utilizing JQuery AJAX and PHP for Data Encoding

My webpage is encoded in HTML with the charset ISO-8859-2. All content on the page adheres to this charset and appears correctly. However, I am facing an issue when making an Ajax call to a PHP server. When I send the character á and receive the same valu ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

Issue with Bootstrap Table Style When Using window.print();

The color of my Bootstrap table style is not displaying correctly in the print preview using window.print(). Here is a screenshot showing that the table style is not working properly: https://i.stack.imgur.com/eyxjl.jpg Below is the code I am using: < ...