简体   繁体   中英

Ajax JQuery Send POST data to external api

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.

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); ?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM