0

I have a function in helper.php:

public static function getFristImageSearch($slug)
{
    $slug = str_replace("-", " ", $slug);
    $image = Images::select('thumbnail')->where( 'metakeywords','LIKE', '%'.$slug.'%' )
    ->where('status', 'active' )
    ->groupBy('id')
    ->orderBy('DATE', 'desc' )
    ->first();
    if( isset( $image ) ) {
        return $image->thumbnail;
    }
    else
    {
        return "";
    }
}

now I want to call this function in Javascript abc.js:

var n = e.replace(t, "<b>" + myvariable + "</b>");
var gotme = getFristImageSearch(n);

but variable gotme doesnot work

getFristImageSearch is not defined

2
  • You should use AJAX request to get values from PHP function. Commented Aug 7, 2021 at 5:07
  • 1
    You have to call by using route name method AJAX Commented Aug 7, 2021 at 5:43

1 Answer 1

1

PHP code can't be run on JavaScript. They're completely separate here.

Based on your tags, I guess you're using Laravel. You need to return your data as a REST API endpoint with JSON data type.

Let's assume you've written an endpoint for the output of the function with this address: /api/getFristImageSearch/slug

Then you have to call it from your JavaScript side like this:

fetch(`'/api/getFristImageSearch/${slug}'`).then((response) => {
        // get your response data here
      })

You can use jQuery to fetch your data as well.

And if you're using this code in production, don't forget to protect your routes if needed.

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

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.