Yii2 jquery post request page not found

Hi,

It is very bad happening with my code here.

When I make a post request from Yii2 in my view, it says url not found.

My customFunction in view:




<script>

var serverURL = 'change-status';


function customFunction(){


$.post(serverURL,{id:proiverid, status:status})

               .done(function(res){

alert(res);

}

});


</script>



Error:

http://localhost/yii2advanced/backend/change-status

404 Not Found

but my original url is:

http://localhost/yii2advanced/backend/testcontroller/change-status

How I can set current controller in this url?

Hi!

To ensure URLs are always correct I suggest to create the URL through yii.

Example:




use yii\helpers\Url;

// Example Usage

Url::to(['controllerID/actionID'])



For EXAMPLE:




var serverURL = <?= Url::to(['test/change-status']); ?>;



You can read more about URL creation here:

http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html

Regards

You can use the following code snippet.


<?php


$this->registerJs('




var serverURL = ' . \Yii::$app->urlManager->createUrl(['controller/action']) . ';


function customFunction(){


$.post(serverURL,{id:proiverid, status:status})

               .done(function(res){

alert(res);

}

});


');

?>

It will automatically create link to your action in controller.

I used your method but got this error:

SyntaxError: invalid regular expression flag b

var serverURL = /yii2advanced/backend/testcontroller/change-status;

I used your method but got this error:

SyntaxError: invalid regular expression flag b

var serverURL = /yii2advanced/backend/testcontroller/change-status;

Try the code below…




<?php

$this->registerJs('

$.ajax({

	url: '" . \Yii::$app->urlManager->createUrl(['testcontroller/change-status']) . "',

	type: 'post',

	data: { id:proiverid, status:status },

	dataType: 'json',

	async: false,

	success: function(res) {

	alert(res);

	},

	error: function() {

	alert('An error has occured');

	}

});

				

');

?>

Thanks I will try.

You are getting 404 which states that the URL is not property formed. You can also check this error on google chrome browser console area. You can also use the .fail() callback of jQuery Post method like this:


.fail(function (xhr, status, error) {

        $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)

    }

Static url sometimes causes this problem and you should always check whether the url formed is correct or now.