M
M
Mikhail Kacherov2013-11-27 21:28:29
PHP
Mikhail Kacherov, 2013-11-27 21:28:29

How to AJAX load data from JSON using jQuery?

I have a JSON request via cURL. The data comes, I parse it and display it in html. By clicking on “Load 5 more”, the page is reloaded and &page=1 is added to the url, while the data is changed to new ones. Is it possible to make the exact same request with JavaScript but without reloading the page using jQuery.ajax() and jQuery.parseJSON()? How to do it?

$url = 'https://api.parse.com/1/functions/getItems';
$page = isset($_GET['page']) ? $_GET['page'] : 0;
$perPage = 5;
$data = array(
    'start' => $page * $perPage,
    'number' => 5,
);

 $MyApplicationId = '1234567890';
 $MyParseRestAPIKey = '0987654321';
 $json = json_encode($data);
 $headers = array(
     'X-Parse-Application-Id: ' . $MyApplicationId ,
     'X-Parse-REST-API-Key: ' . $MyParseRestAPIKey,
     'Content-Type: application/json',
     'Content-Length: ' . strlen($json),
);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$data_get = curl_exec($curl);
$data_in = json_decode($data_get, true);

$name_tb = $data_in['result'][0]['thumbnail']['url'];

foreach($data_in['result'] as $row) {
    echo '<div class="thumbnail_row clearfix">';
    echo '<img src="'. $row['thumbnail']['url'] .'">';
    echo '<div class="alignleft"><h2>'. $row['name'] .'</h2>';
    echo '<div><b>Autor: </b>'. $row['author'] .'</div></div>';
    echo '<a class="button" href="'. $row['file']['url'] .'">Download</a>';
    echo '</div>';
}
$get = array_merge($_GET, array('page' => $page + 1));
$getString = array();
foreach ($get as $p => $v) {
    $getString[] = $p . '=' . $v;
}
echo "<a href='" . $_SERVER['SCRIPT_NAME'] . "?" . implode('&', $getString) . "' class='get_more'>Load 5 more</a>";

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dennis Leukhin, 2013-11-28
@Mihkach

The browser's security policy will not allow cross-domain AJAX requests (without JSONp). But you can write functionality on the backend that sends a get request to an external resource and gives you a JSON response. Get this JSON using an AJAX request from your client.
The scheme would work like this: Your client makes an AJAX request to your server. Your server receives data by url and sends it to your application via AJAX.

A
Artem Marinov, 2013-11-27
@onexdrk

$.post(url, {page: pageNum}, function(data) {
  //json in data, parse and add to ui
});
//or $.get(...)

Approximately so, there already to rule under their realities

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question