0

I have searched everywhere to get an answer for my question. I really need an expert to help me with my problem. I have created code to POST data using ajax to an external api url.

The code I create is like below :

$.ajax({

  url: "https://www.billplz.com/api/v3/collections",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + "73eb57f0-7d4e-42b9-a544-aeac6e4b0f81:");
  },
  type: "POST",
  data: {
    "title": "My First API Collection"
  },
  contentType: 'application/json',
  dataType: 'jsonp',
  success: function(data) {
    alert("Successfully Registered..");
  },
  error: function(xhRequest, ErrorText, thrownError) {
    alert("Failed to process correctly, please try again");
    console.log(xhRequest);
  }

});

I tried to get this sample curl code from API doc :

# Creates an open collection
curl https://www.billplz.com/api/v3/open_collections \
  -u 73eb57f0-7d4e-42b9-a544-aeac6e4b0f81: \
  -d title="My First API Open Collection" \
  -d description="Maecenas eu placerat ante. Fusce ut neque justo, et aliquet enim. In hac habitasse platea dictumst." \
  -d amount=299

The API doc is here

I had tried all methods given by the previous problem but no luck. I also tried to do this in JQuery/AJAX without PHP.

Jonathan Portorreal
  • 2,730
  • 4
  • 21
  • 38
Aizuddin Badry
  • 454
  • 3
  • 9
  • 22
  • what is your server address ? `http` or `https`? – Ataur Rahman Munna Feb 13 '17 at 09:28
  • The external api using https @AtaurRahmanMunna – Aizuddin Badry Feb 13 '17 at 09:30
  • What is the error showed in browser console? can you check this ? – Ataur Rahman Munna Feb 13 '17 at 09:33
  • Its say "Object Could not fetch properties. Object may no longer exist." but the object is still there. @AtaurRahmanMunna – Aizuddin Badry Feb 13 '17 at 09:47
  • 1
    Read the answer and tell me what is your criteria here. http://stackoverflow.com/questions/9310112/why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error/9311585#9311585 – Ataur Rahman Munna Feb 13 '17 at 09:48
  • @AizuddinBadry that doesn't sound like a HTTP error. Check the actual ajax request in your network tab - what's the HTTP error code? And what's in the response data? Also try `dataType:'json'` instead of jsonp - there's nothing in the API docs to say jsonp is supported, and you haven't provided a callback for it anyway. Also I assume your real request will use your own secret key, not the example one from the docs. – ADyson Feb 13 '17 at 10:03
  • @ADyson i dont get any HTTP error its just failed to load resource i dont know why. I already change the jsonp > json but still no luck. I dont know what should i do. – Aizuddin Badry Feb 13 '17 at 10:22
  • if you made an ajax request then there **must** be a HTTP response. So unless there's an error in your script _before the ajax even runs_, then there will be something to view. Something a bit like this (as seen in Chrome): http://commandlinefanatic.com/art034f003.png . The list of files on the left-side will show you any requests for resources - you will need to find your request to the billplz API. Click on it. Then In the headers tab you can see the response code (200 OK in that example). The Response tab will show you any message returned by the server. – ADyson Feb 13 '17 at 10:31

1 Answers1

0

I don't know how i can managed to do this. But here's the answer for my question. I hope it can help others.

The first thing is don't use AJAX to POST your authorization key because AJAX will post JSON object that can be read by anyone. For curl process we need to use server side script like Perl, PHP, Python, Ruby, JavaScript (Node), Scala, Java, Go, ASP.NET, or ColdFusion.

In my case here i use PHP to do curl process. Below is my code for ajax post :

$.ajax({
            url: 'creating_bill.php',
            data: { 
                item : 'item'
            },
            type: "POST",
            dataType: "json",
            success: function (data) {
               alert('Success ! You will redirect in 100 seconds');
               console.log(data)               
               window.open(data.url, '_blank');
                 setTimeout(function()
                 {
                    window.location = 'index.html';
                 },10000);
            },
            async: false,
            error: function(data) {
                handleRequestError(data);
            }
        })   
}

Below is my code in php to do curl process :

<?php

$item = $_POST['item'];


$api_key = '';
$api_url = '';
$collection_id = '';
 
$data = array(
          'item' => $item,
);
 
$process = curl_init($api_url);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $api_key . ":");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($data) );
 
$result = curl_exec($process);
curl_close($process);


print_r($result);
$return = json_decode($result, true);
?>
Aizuddin Badry
  • 454
  • 3
  • 9
  • 22