Make an ajax request to a method in YII framework

I need to send an AJAX call to a function within the directory structure outlined below:

Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile";

Here is my view function:

  function uploadImage(){
      var url = '<?php echo Yii::app()->request->baseUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; ?>';
      console.log(url);
      return false;
        $.ajax({
          url:'<?php echo Yii::$app->createUrl("Post/UploadMusicFile"); ?>',
          method:'post',
          data:{file:$('input[type="file"]')},
          dataType:'',
          contentType:false,
          processData:false,
          success:function(data){
            var parsed_data = $.parseJSON(data);
          },
          error:function(data){
            console.log("Error "+data);
          }
        });

    }

This is the function I am posting to:

  public function UploadMusicFile(){
      $file = Yii::$app->request->post('file');
      echo "<pre>";
      print_r($file);
      echo "</pre>";
      exit();
      $target_dir = "/home/jmwglobaladmin/public_html/melmory/uploads/music_memory/";
      $target_file = $target_dir . basename($_FILES["files"]["name"][0]);
      foreach ($_FILES["files"]["error"] as $key => $error) {
          if ($error == UPLOAD_ERR_OK) {
              $tmp_name = $_FILES["files"]["tmp_name"][$key];
              move_uploaded_file($tmp_name, $target_file);
              $connection = Yii::$app->getDb();
              $command = $connection->createCommand('select id from post order by id desc limit 1');
              $result = $command->queryAll();
              $new_id = $result[0]['id']+1;
              $file_name = "abc.mp3";
              $connection = Yii::$app->getDb();
              $command_insert = $connection->createCommand('insert into memory_music (post_id,memory_music) values ("'.$new_id.'","'.$file_name.'")');
              $result = $command_insert->execute();
          }
      }
    }

I am encountering a 404 error. What is the correct way to pass a URL in Yii to a function located within a directory structure like the one mentioned above?

Answer №1

Foundations. Your function does not qualify as an action.

Modify this:

public function UploadMusicFile()

Into this:

public function actionUploadMusicFile()

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

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

AngularJS Module Instantiation Error

My angularjs module is not loading correctly and I'm struggling to figure out why. Despite reading numerous tutorials, I can't seem to get it to work. [17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due t ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

What is the process for transferring an object to a different file?

Currently, I am working on a web application using Node.js. In my project, I have two main files. The first one is Server.js, where I handle server actions such as going online. The second file contains a large object filled with data. I successfully impo ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Organizing objects into arrays in Node.js

I have an array and I need to concatenate an object after the array. Here is my array: const users = [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ] And here is my object: ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Looping through the Ajax calls until the final value is returned

While making an Ajax call, the returned value is always the last one. This issue has me stumped. Below is the code snippet: if(f_ref==209){ array1=[1,2,3,4,5,6]; for(var i = 0; i < array1.length; i++) { console.log("loo ...

Utilizing jQuery to Uppercase the Ajax Attribute

Lately, I've encountered an issue where I need to format the text input before sending it to ajax and saving it in the database. Specifically, I want to convert the text to lowercase and then capitalize the first letter before storing it. Here's ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...

Having trouble retrieving the JSON value as it returns undefined

Having trouble extracting specific values from JSON data. I'm trying to retrieve the value of result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand, but it keeps returning as undefined. To investigate further, I examined the stru ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Converting XML into an Array Using PHP

I attempted to parse an XML string using PHP. Here is an example of the XML: <?xml version="1.0"?> <root> <Log> <Item> <name>![CDATA[James]]</name> <address>![CDATA[Korea]]< ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

Creating a webpage with a feature that allows users to click a button and instantly change the background to a

Here is the code I have for generating random colors: const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById('btn'); const color = document.querySelector('.color'); btn.addEventListener(&a ...

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

Increasing the size of the .ui-btn-left component

Seeking advice on a Javascript query that I can't seem to resolve online. As a beginner in Javascript, I'm struggling with what seems like a simple issue. My dilemma lies in enlarging the close button on a jQuery page. .ui-dialog .ui-header .ui- ...

Tips for incorporating user access control logic into a lazy-loaded Angular Monorepo application without embedding the logic in the main application

In our current project, we are developing an Angular application utilizing the Angular monorepo structure. This setup includes a parent application and several children applications, with the parent application located in the `app` folder and the children ...

Fade the current Div out and fade in the following Div while also animating its child element

Looking to achieve a fade in and out effect for 3 divs, with the child element animating its way up from the bottom right once the divs have faded in. I've been working on it but haven't made much progress, does anyone have any ideas? Check out ...