pasza
pasza

Reputation: 67

Access to api via jquery

I have an example in php how to get to api, how can I do it using jquery? I do not know PHP and I would have to get data from api.

PHP example:

$address = 'https://mywebsite.com/api/?gate=clients/getNewsletter/0/json';

$request = array();
$request['authenticate'] = array();
$request['authenticate']['system_key'] = sha1(date('Ymd').'mypass');
$request['authenticate']['system_login'] = "mylogin";
$request['params'] = array();
$request['params']['shops'] = array();
$request['params']['shops'][0] = array();
$request['params']['shops'][0]['shop_id'] = 0;
$request['params']['shops'][0]['approval'] = 'y';
$request['params']['date'] = array();
$request['params']['date']['from'] = '2018-08-10';
$request['params']['date']['to'] =  '2018-08-13';
$request['params']['return_elements'] = array();
$request['params']['return_elements'][0] = "1";
$request['params']['results_page'] = 0;
$request['params']['results_limit'] = 100;

$request_json = json_encode($request);
$headers = array(
    'Accept: application/json',
    'Content-Type: application/json;charset=UTF-8'
);

$curl = curl_init($address);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
curl_setopt($curl, CURLINFO_HEADER_OUT, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_json);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($curl);
$status = curl_getinfo($curl);
curl_close($curl);

Can this be done on a jquery?

Upvotes: 1

Views: 91

Answers (1)

Richard
Richard

Reputation: 323

You can use the jQuery ajax function: https://api.jquery.com/jQuery.ajax/

var d = new Date();
var username = d.getFullYear() + d.getMonth() + d.getDate() + 'mypass';
var parameters = {
    'authenticate': {
        'system_key': crypto.subtle.digest('SHA-1', new TextEncoder("utf-8").encode(username)),
        'system_login': 'mylogin'
    },
    'params': {
        'shops': [{'shop_id': 0, 'approval': 'y'}],
        'date': []
    }
};
$.ajax({
    url: 'https://mywebsite.com/api/?gate=clients/getNewsletter/0/json',
    type: 'post',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(parameters),
    success: function(data) {
      // process data
      console.log(data);
    },
    error: function(a, b, c) {
      // error handling
      console.log(a, b, c);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions