Pergunta

$(".btn-delete-news").click(function() {
    if (!confirm('Are you sure to delete ?')) return false;
    var idNews = $(this).attr('news-info');

    console.log(idNews);
    $.ajax({
        url:"<?php echo Yii::app()->createUrl('/news/delete'); ?>",
        data: { id : idNews },
        type:"POST",
        success: function(data){
            if(data == "1") {
                window.location = "/news/";
            }
        }
    });
});

In script upon, when i insert that script to view file, it working well. But i cut them, and insert them to the js file, such as script.js => script run wrongly, it dont understand the code : url:"<?php echo Yii::app()->createUrl('/news/delete'); ?>" , i must change it to url:'/news/delete' . Who can help me to js file which can run the code url:"<?php echo Yii::app()->createUrl('/news/delete'); ?>".

ps: Yii Framework is used here.

Thanks in advanced.

Foi útil?

Solução

I think a nice solution would be to add a data attribute to .btn-delete-news and fill it with the target url so that in your JS you can read it out and use it as target url:

PHP:

<button class="btn-delete-news" data-target="<?php echo Yii::app()->createUrl('/news/delete'); ?>" />

JS (with jQuery):

$(".btn-delete-news").click(function() {
    if (!confirm('Are you sure to delete ?')) return false;
    var idNews = $(this).attr('news-info');

    console.log(idNews);
    $.ajax({
        url: $(this).data('target'),
        data: { id : idNews },
        type:"POST",
        success: function(data){
            if(data == "1") {
                window.location = "/news/";
            }
        }
    });
});

You could do the same for the target location if you'd want to

Outras dicas

It happens because .js files are not parsed as PHP files unless you set your server to do so (not recommended).

Since PHP there is used just to build URL, you can pull off something much more natural by making a JS variable in your header/main PHP file. The variable should contain the base URL of your app:

var baseUrl = '<?php echo Yii::app()->createUrl(); ?>';

That variable will be available everywhere, since it's in the global scope.

The change in the URL parameter is simple and it no longer requires PHP:

...
$.ajax({
    url: baseUrl + "/news/delete",
    ...

However, since you say your app works with just /news/delete, you probably don't even need the PHP/baseUrl parts...


Here is another suggestion if you're using more complex URL rewriting (thanks @MrSoundless).

You could define all those complex urls in the header, not just baseUrl, so you can have:

var deleteNewsUrl = '<?php echo Yii::app()->createUrl('/news/delete'); ?>';

And in your .js file, just this:

...
$.ajax({
    url: deleteNewsUrl,
    ...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top