Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

url data to json

I have a url which is returning JSON, but due to cross browser request issue I am requesting it with CURL in PHP, now its returning json data as string. I want that string to be converted in to json so I can use it with my javascript function.

Ajax request which is printing JSON string

$.ajax({
        url: 'tweet.php',
        cache: false,
        dataType: 'json',
        type: 'POST',
        data: {
            url : url,
        },
        success: function(tweet){
            var tweets = $.parseJSON(tweet);

            console.log(tweets);
        }
    }); 

and in tweet.php

header('Content-type: application/json');
$ch = curl_init() or die('cURL not available');
curl_setopt($ch, CURLOPT_URL, $_POST["url"]. $location);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  //to suppress the curl output 
$result = curl_exec($ch);
curl_close ($ch);
print ($result);

Getting Invalid json error

SOLVED

Although answers didn't helped, but somehow I figured it out. Posting here if someone need it.

Whenever you request JSON from PHP using Curl it will return the JSON object but as a string, you can check it via javascript typeof() function. If you want to convert that string to real javascript object you need to use some sort of parser. Here what I use JSON PARSER

var myJson = '{ "x": "Hello, World!", "y": [1, 2, 3] }';
var myJsonObj = jsonParse(myJson);
console.log(myJsonObj);

Regards

Upvotes: 1

Views: 1818

Answers (3)

poncha
poncha

Reputation: 7866

Change dataType from 'text' to 'json' in your $.ajax call

Upvotes: 0

T. Junghans
T. Junghans

Reputation: 11683

Try jQuery.parseJSON

Also as an extra, if you want your php response to be treated as json content use the following pattern in php:

// Convert to JSON
$json = json_encode($yourData);

// Set content type
header('Content-type: application/json');

// Prevent caching
header('Expires: 0');

// Send Response
print($json);

exit;

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57690

In your html file do this assuming $json holds the string returned form remote url

<script type="text/javascript">
var data = JSON.parse("<?php echo $json; ?>");
</script>

Upvotes: 1

Related Questions