0

I have this php function inside a class the returns json data

function getPhotoDetails( $photoId ) {
   $url = $this::APP_URL . 'media/' . $photoId . $this::APP_ID;
   return $this->connectToApi($url);
}

and this ajax request

function getPhotoDetails( photoId ) {
    $.ajax({
        type: "GET",
        cache: false,
        url: 'index.php',
        success: function (data) {
               console.log(data);
        }
    });
}

The question is how I can call the php function to get the json data.

Solution: A big thanks to all of you guys and thanks to Poonam

The right code

PHP: I created a new object instance in php file

$photoDetail = new MyClass;
if(isset($_REQUEST['image_id'])){
  $id = $_REQUEST['image_id'];
  echo (($photoDetail->getPhotoDetails($id)));
}

JavaScript

function getPhotoDetails( photoId ) {

    $.ajax({
        type: "GET",
        cache: false,
        url: './instagram.php?image_id=' + photoId,
        success: function (data) {
            var data = $.parseJSON(data);
            console.log(data);
        }

    });
}
1
  • 2
    your php script is just like any normal script - an ajax connection is just another "kind" of browser. You call the function just like you would on a regular PHP page - passing data with either POST or GET. Then you would need to echo the return value of the php function, with json headers. Commented Sep 20, 2012 at 14:42

3 Answers 3

2

Try with setting some parameter to identify that details needs to send for e.g assuming photoid params needed for function

function getPhotoDetails( photoId ) {
    $.ajax({
        type: "GET",
        cache: false,
        url: 'index.php?sendPhoto=1&photoid=23',
        success: function (data) {
               console.log(data);
        }

    });
}

and then on index.php check (You can make check for photoid whatever you need as per requirement)

if(isset($_REQUEST['sendPhoto'])){
      $id = $_REQUEST['photoid'];
      return getPhotoDetails($id);
}
Sign up to request clarification or add additional context in comments.

Comments

1

setup a switch-case. Pass the function name as GET or POST variable such that it calls the php function

Comments

0

You need a file which calls the PHP function. You can't just call PHP functions from Ajax. And as pointed out by Tim G, it needs to use the proper header, format the code as JSON, and echo the return value (if the function is not already doing these things).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.