質問

This is my first post so please be patient ;)

My question:

I use my own MVC. The model (i.e. to upload images) contains a php function that validates if a file exists, matches the allowed extentions and the allowed size and then uploads the file. It returns an array with the filenames so that I can show the user on the next page which files have been uploaded and which haven't.

Now i want to add jQuery functionality. JQuery, however, doesn't want to have an array with filenames 'returned' like

return $messageArray;

but 'echoed' instead:

echo json_encode($messageArray);

BUT: I don't want to change the php-function's return to echo. Why? The php script should work fine without Javascript. Javascript should only be added to make the user feel more comfortable.

So: how would you basically plan the php function to be able to return messages (stored in an array) for 'php-only' AND jQuery?

I'm thinking of adding an additional parameter to the function, like:

$.Ajax({
type: 'POST',
URL: 'uploadhandler.php?files=...&jquery=true',
...
dataType: "json",
        success: function(data){...;},
    ...})

If within the php-function the parameter jquery == true I would echo the result instead of returning it.

What would be your solution?

役に立ちましたか?

解決 2

Thanks a lot! However 'HTTP_X_REQUESTED_WITH' did not work for me - I read that $_SERVER is not an official PHP request.

I went with my idea of sending an additional parameter with ajax (i. e. "&query=query"). The php-function outputs "echo" if the parameter "query" is set. Works perfectly!

他のヒント

Instead of adding a parameter specifically in AJAX requests, you can check the request type using the following piece of PHP code:

/**
 * Check to see if a page was requested using XMLHTTP (using AJAX for example)
 *
 * @return bool
 */
public function isAJAX()
{
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

Then use it in your PHP method:

if (isAJAX()) {
    echo $result;
} else {
    return $result;
}

It's not ideal but it should get you started :)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top