0

I am trying to pass a javascript variable into a php code in the view file of the cakephp 2.

for (id in response) {

    var book = response[id];

    if (typeof(book.thumbnail_url) != "undefined") {
        var x= book.thumbnail_url; 

        <?php   
            $file11 = WWW_ROOT . 'img' . DS . 'book_images';
            define('DIRECTORY', $file11);

            $content = file_get_contents($abc);
            file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
        ?>
    }
}

i am trying to pass the value of x in the file_get_contents function in place of $abc so that it could save the image coming from the javascript's URL accordingly.

EDIT::

     for (id in response) {


                                   var book = response[id];

                                        if (typeof(book.thumbnail_url) != "undefined") {
                                        var x= book.thumbnail_url; 
                                         $.ajax({
                                           type: "POST",
                                           url: '/BookSearchs/test',
                                           data: {'yourX':x}
                                        }).done(function(result) {
                                            alert("yes");
                                        }).fail(function() {
                                            alert("no");
                                        });
                                      }



                                     }

This is what i wrote after implementing the answers i got . But Everytime it pops up "no". Here BookSearchs is my controller and test is my function inside it.

EDIT 2:

function handleResponse(response) {
    var target = '';

    for (id in response) {


        var book = response[id];

        if (typeof(book.thumbnail_url) != "undefined") {
            var x = book.thumbnail_url;



            $.ajax({
                    type: 'POST',
                    url: "BookSearchs/test",



                    data: {
                        myVal: x
                    },
                    success: function() {
                        alert('AjaX Success')
                    },
                    error: function() {
                        alert('AjaX Failed')
                    }
                })

                .done(function() {
                    alert('AjaX Done!');
                });
        }



    }

    return true;

}

Currently this is what i've have done so far , the form method did not work out . It was redirecting me to another page . Anyways this is my current code . And 'test' is the my function inside the controller where i want to access the myVal value using POST . Also i have this question do i need to create a physical file for test in order to make the ajax function work, because if i delete the test.ctp file then the ajax starts giving the fail message . So for now i have created a physical test.file in the BookSearchs folder in the view , although it's empty in order to make the ajax function work . I am having a doubt whether my Url in Ajax is wrong or i am not accessing the values properly in the controller.

3
  • I can show you how to send it to the controller if you want Commented Sep 11, 2017 at 12:33
  • ya .. that'd be good as well Commented Sep 11, 2017 at 12:54
  • that was actually my initial plan . Commented Sep 11, 2017 at 12:55

2 Answers 2

1

I don't think that this is a proper way to do that in theory. But, sometime we might need this.

Before we proceed to this way, you might need to think other technologies such as NodeJs (e.g fs.readFileSync)

Basically, you can't directly do that. Because, JavaScript run on client side and PHP is run on sever side.

Anyway, there might be a few tweak to do that. But, this approach might be slow and it depends on how many loop you making.

for (id in response) {
    var book = response[id];
    if (typeof(book.thumbnail_url) != "undefined") {
        var x= book.thumbnail_url; 
        $.ajax({
           type: "POST",
           url: '/yourcontroller/route',
           data: {'yourX':x}
        }).done(function(result) {
            //if success, execute other code
        }).fail(function() {
            //DO other if fail
        });
    }
 }

Then, read this value in your controller

$xValue = $_POST['yourX'];

$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($xValue);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
//do some checking success or fail
//I will assume success
$status = 'success';
echo json_encode(['status'=>$status]);    
Sign up to request clarification or add additional context in comments.

7 Comments

I think that the problem with ajax in this case is that it interact just with the same view, I mean that if we can't send a Js variable to the controller & then send it to another view, this is the issue with ajax, we must stay in the view;
@MehdiBouzidi No need to go to other view. It can be done in same view.
So it depends of your needs ^^
While you are correct about the problem, the PHP example is kinda problematic, security wise (it allows to read arbitrary files and write them to a public directory), and best practice wise (in CakePHP you should not access superglobals directly, and controllers should never echo data).
@ndm I agreed on that. But, I'm showing the way as a snippet. Anyway, thank for your information and will deploy it on upcoming answers. :)
|
0

Usally I use a Trick to pass JS variable to a CakePhp Controller(php variable). Actionly I create a form that contain a hidden input, I'll also put the link of the page that will receive the php variable.

.ctp

 <?=
$this->Html->link('<i class="fa fa-file-pdf-o"></i>' .__('Export'),
'javascript:myFunction();',
array('escape' => false, 'class' => 'btn btn-app  dispatch',  'id' => 'dispatch_packages',
'style'=>'margin-right:0px;background: #f39c12;color:white;',
'disabled' => 'false'));
?>
<form id="sampleForm" name="sampleForm" style="display: none" method="post" action="<?= $this->Url->build([
                        'controller' => 'YourController',
                        'action' => 'youraction']) ?>">
    <input type="hidden" name="variable" id="variable" value="">
</form>

JS

var jsVar=0;
    function  myFunction()
    {

        document.sampleForm.variable.value = jsVar;

        document.forms["sampleForm"].submit();
    }

I used it with the CakePhp 3.x framework & it's working very fine. You have just to write the url with the CakePhp 2.x Syntax.

Don't hesitate to comment my answer if you'll have any difficulties to apply it. Good Luck !

4 Comments

how am i supposed to access the value in the controller
@HarjeevSingh $phpVariable=$this->request->data('variable');
not yet.. anyways i have a question if i make a function in the controller apart from the index function , is it necessary to make the physical file as well .
@HarjeevSingh You're talking about a view file related to the function ? If Yes, then no it's not necessary !

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.