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!!

4
  • 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. Commented Dec 24, 2021 at 8:24
  • @GilesBennett Thanks!! I'll try the same as suggested Commented Dec 24, 2021 at 8:31
  • Does this answer your question? What is the difference between client-side and server-side programming? Commented Dec 24, 2021 at 10:32
  • You can try add result of PHP function to page hidden field and in JS get this data.. or use AJAX Commented Dec 24, 2021 at 10:37

3 Answers 3

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.

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

2 Comments

can not use ajax as the loop may be in thousands.
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.
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

Comments

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

Comments

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.