0

http://www.shedlimited.debrucellc.com

The site allows users to upload an image, via PHP script(ajaxupload.php) which is stored in $uploaded_img , inside of the php script. I want to pass the PATH of my newly stored image to a JS file, and the only way I've found to do it is by writing the value to a text file, which is extreme overkill

file_put_contents("testFile.txt", "");
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

$stringData = $upload_image;
fwrite($fh, $stringData);
$stringData = "\n";
fwrite($fh, $stringData);
fclose($fh);

At the same time, I have an external .js file running which loads my html5 Canvas etc,

I set a global variable sourcer , inside the external .js file, which I'm able to access and update from my index.php by reading the URL from the file which I wrote the url to in my php script.:

jQuery.get('scripts/testFile.txt', function(data) {
sourcer = data;
});

Is there any way that I can pass the URL value to sourcer without having to manually insert it in a text file?

2 Answers 2

1

Add a block to your head on your php template.

<script type="text/javascript">
    var uploaded_img = '<?php echo json_encode($uploaded_img); ?>';
</script>

The json encode makes sure the variable is properly encoded, even if it is an object or array.

If it is purely an ajax thing. Just return the filename in your ajax response. So post to your ajax upload, and make your ajax script return a json object with the filename.

So in your upload script, at he bottom:

header('Content-type: application/json');
echo json_encode(array('filename'=>$uploaded_img));

And read the response.filename in javascript.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok so I will test the second option you put there
i ended up using jquery .ajax combined with json encoding, but it works etc, thanks!
0

What about using a session variable to store the uploaded image AND an ajax response to work with ?

I see an advantage to use both : you can use the value directly on the upload page right after the image is uploaded. And for the session var, it will ensure that the server side is always able to get the value if you ever need to access it from another context.

3 Comments

like using a session variable to pass from ajax_upload.php to index.php, I didn't think of that, sounds pretty convenient, will it update etc correctly though? I will test this too
A session variable can be updated from the server side. In exemple : $_SESSION['uploaded_image'] = $uploaded_image;
my session variable doesn't update until I reload the initial page index page, so I ended up using .ajax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.