Maurício Giordano
Maurício Giordano

Reputation: 3276

Unexpected token ILLEGAL javascript + php

Here is the source code:

    $(document).ready(function(){

        $.post("scan.php?dir=<?=$_POST['dir']?>", function(data){

            alert(data);

        });

    });

The generated code is:

    $(document).ready(function(){

        $.post("scan.php?dir=C:\xampp\htdocs\windowsMedias\music", function(data){

            alert(data);

        });

    });

But it won't work (google chrome returns the error in the title).

If I add the generated code manually, without PHP, it works.

Someone knows how to fix it?

Upvotes: 2

Views: 1269

Answers (4)

bfavaretto
bfavaretto

Reputation: 71908

As other answers say, you have to properly encode yourURL parameter. For that, you can use encodeURIComponent:

$.post("scan.php?dir=" + encodeURIComponent( "<?=$_POST['dir']?>" ), function(data){
    alert(data);
});   

What is causing the error are the unencoded backslashes. Your URL contains \x, which is a special hexadecimal escape sequence mark. It expects the following two characters to be valid hexadecimal digits (i.e., [0-9a-fA-F]), otherwise it will cause an error.

Upvotes: 0

Sirko
Sirko

Reputation: 74036

The variable you're using contains characters (:, /, ...), that can not be a part of a URL parameter.

Use encodeURI() to transform your path into a parameter, that can be passed within a URL:

$(document).ready(function(){

    $.post("scan.php?dir=" + encodeURI( "<?=$_POST['dir']?>" ), function(data){

        alert(data);

    });

});

Upvotes: 4

Tahir Yasin
Tahir Yasin

Reputation: 11699

Problem is with backslashes, you have to json_encode your path like this

$(document).ready(function(){
    $.post("scan.php?dir=C:\xampp\\htdocs\\windowsMedias\\music", function(data){
        alert(data);
    });
});

Upvotes: 0

xdazz
xdazz

Reputation: 160833

You need to urlencode your parameter.

$.post("scan.php?dir=<?= urlencode($_POST['dir']) ?>", function(data){
  alert(data);
});

Upvotes: 1

Related Questions