Using Twig in combination with Ajax to send requests using the Get method

Trying to utilize the Get method to send an Ajax request, I have encountered an issue. Despite adding an alert to my request function to confirm the link, no alert is displayed!

Here is my code:

Below is my html.twig view:

<a href="#" onclick="request( {{ path('mooniki_vote_acteur', { 'id' : 8 } ) }} );">Click here</a>

Here is my javascript code:

function request(path) { 
alert(path);
var xhr = getXMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            alert(xhr.responseText); // Retrieved text data
    }
};

xhr.open("GET", path, true);
xhr.send(null);
}

Interestingly, when I provide a string argument in the request function, the alert is displayed successfully.

Thank you.

Answer №1

When utilizing the path() function in Twig, it will consistently generate something like /app_dev.php/.... However, a challenge arises when passing this output as an argument to a function, as the function may interpret it as a regular expression literal.

The issue was pinpointed through the console (F12), where the Chrome Developer Console displayed the following error:

Uncaught SyntaxError: Invalid flags supplied to RegExp constructor

This error indicates that it is being treated as a regular expression. To resolve this, ensure that the output is represented as a string, like this:

<a href="#" onclick="request(' {{ path('mooniki_vote_acteur', { 'id' : 8 } ) }} ');">Je valide !</a>
----------------------------/\-------------------------------------------------/\

Take note of the '...' placed right after or before the opening/closing bracket.

By following this approach, I was able to accurately output my path and successfully perform an AJAX Request with it. Interestingly, the solution became apparent when utilizing a string argument.

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

Sorting and Uploading Images made Easy with Drag-and-Drop Functionality

Currently, I am developing a webpage and exploring the option of implementing a drag-and-drop image upload system that allows users to remove and sort images before uploading. I am seeking your opinion on this matter. I am concerned about potential issue ...

Creating interactive tooltips in Shiny applications with the help of ShinyBS

I am attempting to incorporate the shinyBS package into my basic app. My goal is to generate dynamic tooltip text based on each radioButton selection. To better illustrate my issue, I have drafted a simple code snippet in HTML & JS. While I came acro ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

The ng-switch functionality does not seem to be functioning properly, even when the is

My ng-switch is displaying both buttons instead of just one when isActive is false. Can anyone help me figure out what I am doing wrong? <div ng-switch="user.IsActive"> <div ng-switch-when="false"> <button type="button" (click)="activ ...

Exploring the power of intercepting response.send() and response.json() in express.js

Imagine having various instances where response.send(someData) is utilized. What if you wish to implement a universal interceptor that captures all .send functions and modifies someData? Is there a method within express.js to achieve this, such as hooks, ...

Is there a way to retrieve the present value of a dropdown menu once an ajax call is successful?

Currently, I am facing an issue where I am unable to retrieve the selected value from a dropdown menu. The logged value is always the first option in the dropdown menu, even though I have set it to a different value. Can someone help me identify what I may ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

Resuming AJAX requests after being aborted

Hey everyone, I'm curious to know if it's possible to resume interrupted ajax requests. I have an array of ajax calls stored as defferreds like this: var defferreds = []; defferreds.push( $soap.ajax({ type: "POST", dataType: ...

Encountering a TypeError while trying to run Pythonshell on my Mac device

When I run a python script in node.js using python shell, it works perfectly on my Windows system. However, I encounter an error when trying to run the same thing on my Macbook: Error: TypeError: can't multiply sequence by non-int of type 'float ...

Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result. <template> <select v-model="tutor_work.start_year"> <option>{{tutor_work.start_year}}< ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Failures occur when making simultaneous calls to the ColdFusion ORM database

Recently, I started to explore ColdFusion and decided to test out the ORM (Hibernate, as far as I know, but I'm not familiar with it at all). While experimenting with calling two ColdFusion pages in quick succession, I encountered an issue. The code ...

Manipulate the timing of css animations using javascript

I am currently working with a progress bar that I need to manipulate using JavaScript. The demo of the progress bar has a smooth animation, but when I try to adjust its width using jQuery $($0).css({'width': '80%'}), the animation disap ...

yii ajaxurl customization for table sorting

Here is some code I have: ajaxUrl : '<?php echo Yii::app()->createUrl("abc/def");?>&page={page}&size={size}&{sortList:col}&{filterList:fcol} ', Referenced from: http://mottie.github.io/tablesorter/docs/example-pager-aj ...

The outcome of the JQuery function did not meet the anticipated result

Here is the code I am using: $("p").css("background-color", "yellow"); alert( $("p").css("background-color")); The alert is showing undefined instead of the expected color value. I have tested this code on both Google Chrome and Firefox. Strangely, it w ...

Why isn't the import statement fetching the necessary function for me?

Hello, I am currently utilizing NextAuth for my application: The main file I am attempting to pull data into: [...nextauth].js import NextAuth from "next-auth" import Providers from "next-auth/providers" export default NextAuth({ // ...

How can we dynamically resize page content to fit varying browser window sizes across different devices with the help of jQuery/JavaScript?

Looking for a solution involving an HTML form that includes a text field and a submit button. The text field is where the user enters a URL, and upon clicking the submit button, they are redirected to that URL. Seeking a way to adjust the size of the new ...