-1

I have an API based on Php Slim Framework and want to generate JSONP for my website. When I call the website on: 'http://api.mysite.com/users?callback=JSON_CALLBACK'. It returns a blank page with JSON CALLBACK() write on it. When logged to the console it is undefined.

API's index.php

<?php
require 'vendor/autoload.php';

$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->run();

function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $dbh;
}

function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo $_GET['callback'] . '('.json_encode($users).')';
}
catch(PDOException $e) {
echo $_GET['callback'] . '('.json_encode($e->getMessage()).')';
}
}

var_dump($users), Call on http://api.mysite.com/users and result is:

function getUsers() {
$sql = "select * FROM manga";
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
var_dump($users);
}

Result:

array(2) {
[0]=>
object(stdClass)#35 (10) {
["id"]=>
string(1) "1"
["ad"]=>
string(6) "Naruto"
["yazar"]=>
string(17) "Masashi KISHIMOTO"
["icerik"]=>
string(28) "Ninja, Dövü?, Aksiyon, Drama"
["tarih"]=>
string(4) "1999"
["tur"]=>
string(5) "Manga"
["durum"]=>
string(9) "Sona Erdi"
["konu"]=>
string(560) "Yondaime Hokage, gizli bir ninja kasabas? olan Konohagakure'ye sald?ran cehennemin iblislerinden Kyuubi'yi durdurmak için, Onu yeni do?mu? bir çocuk olan Naruto'nun içine mühürler. Böylece kahram?n?m?z Naruto ortaya ç?km?? olur. ?çine mühürlenen korkunç iblis sebebiyle kasaba halk?n?n nefretini kazanan Naruto daha bebekken yetim kalm?? biridir. Kasaba halk?n?nda kendini d??lamas?ylada oldukça yaramaz ve haylaz biri çocuk olur. Fakat ninja akademisinden mezun olaca?? gün, hayat?nda ilk defa olarak arkada? edinmesi Naruto'nun hayat?n? bütünüyle de?i?tirir."
["kapak"]=>
string(10) "naruto.jpg"
["son"]=>
string(3) "300"
}
[1]=>
object(stdClass)#36 (10) {
["id"]=>
string(1) "2"
["ad"]=>
string(9) "One Piece"
["yazar"]=>
string(12) "Eiichiro ODA"
["icerik"]=>
string(32) "Macera, Komedi, Dövü?, Fantastik"
["tarih"]=>
string(4) "1997"
["tur"]=>
string(5) "Manga"
["durum"]=>
string(12) "Devam Ediyor"
["konu"]=>
string(881) "Korsan Kral Gold Roger, bu dünyadaki her?eyi elde eder ve idam edilirken, tüm servetinin Grand Line'da oldu?unu, onu aray?p bulmalar? gerekti?ini söyler. Bu olaydan sonra herkes Grand Line'a gider. Ancak Grand Line'a girmek çok zor, Grand Line'da canl? kalabilmek imkans?zd?r.

Kahraman?m?z Monkey D. Luffy'nin rüyas?, Korsan Kral olmak ve One Piece denen kimsenin bilmedi?i, görmedi?i hazineyi ele geçirmektir. Küçük ya?lardan beri hep korsan olmak isteyen Luffy, kazara bir ?eytan meyvas? (Akuma No Mi) yemi?tir. 3 farkl? ?eytan meyvas? vard?r ve bu meyvalar yiyenlere çok üstün güçler sa?lamaktad?r ancak bu güçlerin bedeli asla yüzememektir. Luffy'nin yedi?i meyva onu bir lastik çocu?a çevirir. Bu olaydan y?llar sonra Luffy denize aç?l?r. Yolculu?u s?ras?nda ekibini toplayacak ve One Piece'i bulmak için Grand Line'da birbirinden tehlikeli ve komik maceralara at?lacakt?r."
["kapak"]=>
string(13) "one_piece.jpg"
["son"]=>
string(3) "788"
}
}
Nasuh
  • 355
  • 3
  • 20
  • Check your json for validity: Take a look at @"Madan Sapkota" answer [here](http://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php) – 0yeoj Oct 13 '15 at 02:47
  • @Paul Crovella ,0yeoj Problem is in my database table. Table has data with Turkish chars. I dont understand Turkish chars are in the UTF-8? – Nasuh Oct 13 '15 at 03:48

1 Answers1

1

No where in your HTTP response are you defining a javascript function to handle the JSONP response. I assume this function is then defined in another JavaScript resource (inline or script) in your web app. Therefore an undefined error would be caused by your javascript elsewhere and not from this segment of code.

To test this, load up your web app and launch the console. You can manually run: myCallbackFunction({field:"value"}); // some test JSON document to determine if the callback function exists.

However.

IMHO JSONP is generally a terrible idea, and best described by jQuery's page on the topic.

JSONP is essentially a consensual cross-site scripting hack

It opens your client side application to easier MITM attacks, here's a SO question on this very issue.

Since you are ultimately just returning the JSON data and not custom logic, I would recommend trying the following:

  1. Return the JSON encoded response with header('Content-Type: application/json);. You're very close to doing this already with your existing code.
  2. Have the same callback function in JavaScript, i.e. it doesn't need to be passed as part of your HTTP request and the function name wouldn't need to differ.
  3. Handle the JSON in almost exactly the same way client side. You'll need to make minimal changes to the JavaScript since all you're doing is passing the JSON object into the function as it is.
Community
  • 1
  • 1
developerjack
  • 1,173
  • 6
  • 15