0

I need to call php function inside javascript with js params. something like.

function test(data) {
    $.each(data,function(key, item) {
        let resVal = '{{encryptId('+item.id+') }}';
    })
}

encryptId is a function defined in php helper file.

Please suggest can it work

Thanks!!

SHARVAN
  • 21
  • 2
  • 1
    It can't. PHP is executed on the server before the page is sent to the user's browser. JS is executed in the browser after being received. You would have to write a JS function that performs the same as the PHP encryptId() function. – Giles Bennett Dec 24 '21 at 08:24
  • @GilesBennett Thanks!! I'll try the same as suggested – SHARVAN Dec 24 '21 at 08:31
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Nico Haase Dec 24 '21 at 10:32
  • You can try add result of PHP function to page hidden field and in JS get this data.. or use `AJAX` – Pavlo Mezhevikin Dec 24 '21 at 10:37

3 Answers3

2

That's not possible but a way around it could be using ajax requests. You can hit the function of php through javascript and also send parameters.

p4avinash
  • 548
  • 2
  • 4
  • 15
  • can not use ajax as the loop may be in thousands. – SHARVAN Dec 24 '21 at 08:29
  • You can use a global flag, and run only if the flag is true. set the flag to true in the start and once the ajax request has been made, set the flag to false. Then it'll only run 1 time. – p4avinash Dec 24 '21 at 08:31
1

This is not possible, PHP and javascript are executed at different time,

Your PHP is executed on the server, before any data is sent to the client, the server himself has no idea about what javascript is

Your javascript is executed on the client, after he received all the code preformated by PHP, the client doesn't know what PHP is nor how to interpret it

The only way to do it is to have the same function in javascript

jonatjano
  • 3,576
  • 1
  • 15
  • 20
1

Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

you can try with AJAX

#JS FILE
function encryptId(item) {
    .ajax {
        file : phpFile
        item : item
    }
}

function test(data) {
    $.each(data,function(key, item) {
        encryptId(item.id)        
    })
}

#PHP FILE
Here You can catch that variable and call this function
TarangP
  • 2,711
  • 5
  • 20
  • 41