Ahmad Ajmi
Ahmad Ajmi

Reputation: 7281

Access php function data via ajax

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);
        }

    });
}

Upvotes: 0

Views: 224

Answers (3)

leet
leet

Reputation: 961

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

Upvotes: 1

Poonam
Poonam

Reputation: 4631

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);
}

Upvotes: 2

Brett Zamir
Brett Zamir

Reputation: 14345

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).

Upvotes: 0

Related Questions