Karuvägistaja
Karuvägistaja

Reputation: 293

PHP decodes the ajax sent variable wrong

I try to send a variable using jquery and ajax to php script. Then I want to use that variable in creating a file name but it fails. The file name is always "0" and does not locate at the dir "redirect".

Here is the code:

Ajax:

    var pageName=$('#movie').val();

    $.ajax({
        type: "POST",
        url: "phpstuff.php",
        data: { pageName: 'pageName'},
        cache: false,
        success: function()
            {
                alert(pageName);
            }
    });

the "pageName" variable gets the value from an input box with an id "movie"

The php file

function createPage ($newPage){

$file=fopen("redirect/"+$newPage+".php","w") or exit("Fail to create the page");
$data = "some text I want to be in a file";
fwrite ($file, $data);
fclose($file);
}

$newPage = $_POST["pageName"];
createPage($newPage);

I have searched the net for hours and still can't fix the problem.

Upvotes: 0

Views: 74

Answers (3)

John Griffiths
John Griffiths

Reputation: 51

Line

data: { pageName: 'pageName'},

should be

data: { pageName: pageName},

A print_r( $_POST["pageName"] ) would show you what is being passed, in the first version $_POST["pageName"] is 'pageName'

You could also use

data: 'pageName='+pageName,

The description on http://api.jquery.com/jQuery.ajax/ for data parameter is'nt very clear as it talks about GET and dosn't mention POST.

Upvotes: 4

Joshua Dwire
Joshua Dwire

Reputation: 5443

Try changing this line:

$file=fopen("redirect/"+$newPage+".php","w") or exit("Fail to create the page");

to

$file=fopen("redirect/".$newPage.".php","w") or exit("Fail to create the page");

Notice the changes from + to .. In PHP + is for addition, and . is for string concatenation.

Upvotes: 1

Waleed Khan
Waleed Khan

Reputation: 11467

String concatenation should be done with .:

"redirect/" . $newPage . ".php"

Upvotes: 3

Related Questions