PHP and JavaScript (jQuery) do not have at all in common with each other, you can only transfer variables through AJAX.
$.ajax({ url: "",//файл который обрабатывает скрипт type: "POST",// метод data: {'image': imageValue }, // переменная которая передается в PHP success: function (response) {}, // если успешно выполнено error: function (jqXHR, textStatus, errorThrown) // если ошибка { console.log(textStatus); } });
Well, in PHP we do this:
if (!empty($_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) && strtolower($_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) == 'xmlhttprequest') { if (isset($_POST[ 'image' ])) { //делаем то что нам нужно //если скрипт что то возвращает, и надо выводить эту инфу, //то делаем так echo json_encode($printThisText); } } die(); //забыл добавить сначала. Нужно для того чтобы прекратить //выполнение после нужных действий
UPDATE: Approximate implementation for your project
I’ll write a small example now, and you’ll have it customized: Unfortunately, I have never worked with base64 and with downloading files via AJAx, but the principle will be about the same.
HTML:
Form with input:
<form method="post" action="file.php" enctype="multipart/form-data"> <input type="file" name="uploadImage" value="" /> <input type="submit" value="Загрузить изображение" name="uploadImage"> </form>
enctype="multipart/form-data" - the attribute is needed if the form will upload files.
The input'a attribute - the name for one image can be specified as: name="uploadImage" , and if you want to take several images, then you specify the name="uploadImage[]" - now it will accept the whole array. Block where this image will be displayed:
<div> <img id="dinamycImage" src=""/> </div>
For example, the user selects a file, clicks the "Download" button. To begin with, in order for you to get the base64 this image, you need to upload it to your server (unless you provide the opportunity to select images for this user).
To organize this, you need to upload files using the AJAX method, without reloading the page, I don’t really help you here, as I haven’t figure out how to upload files to the server using AJAX, but the Internet is full of all sorts of plugins / methods / functions who do it.
Further, I really hope that you are not writing all the PHP code and HTML markup in one file. In the file where the PHP code is located (you can make a new file to process this particular request), something like this will be:
if (!empty($_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) && strtolower($_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) == 'xmlhttprequest') { if (isset($_POST[ 'image' ])) { $uploadFile = $_FILES['uploadImage'];//Если ты хочешь принимать $imageUpload = uploadImageFunction($UploadFile); //функция загрузки изображений на сервер //которая додэна возвращаться твой base64 echo json_encode($imageUpload); //после того как изображение обработалось, и //загрузилось, ты возвращаешь это всё дела в AJAX, //та оно само примется, как результат выполнения //выше указаной ф-ции. } } die();
In the uploadImageFunction uploadImageFunction($UploadFile) at the end of processing there should be the following, you should return this cipher to AJAX:
$path = 'myfolder/myimage.png'; // путь к файлу $type = pathinfo($path, PATHINFO_EXTENSION); $data = file_get_contents($path); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); return $image = $base64;
Now for an AJAX account:
$.ajax({ url: "",//файл который обрабатывает скрипт type: "POST",// метод data: {'image': imageValue }, // переменная которая передается в PHP success: function (response) { //здесь будет функция загрузки изображений //которая возвращает этот base64 if(response.imagePath){ $('#dinamycImage').attr('src', response.imagePath); //и так вставляется фотография } }, // если успешно выполнено error: function (jqXHR, textStatus, errorThrown) // если ошибка { console.log(textStatus); } });
I did not check the performance, but something like this should happen. Without downloading the image to the server, you will not succeed. I would not recommend doing downloads via AJAX, but if you only need it, then sort it out.