I'm having an issue with making a post request with a project I created to take in contact info from a form. When I run the function to make the post request I get nothing back in the console. heres the code:
function postContact(token) {
firstName = $('#agentfirst').val();
lastName = $('#agentlast').val();
workNumber = $('#agentwork').val();
cellNumber = $('#agentcell').val();
faxNumber = $('#agentfax').val();
agentEmail = $('#agentemail').val();
agentLicense = $('#agentlicense').val();
companyName = $('#companyname').val();
streetAddress = $('#companyaddress').val();
addressCity = $('#companycity').val();
addressState = $('#companystate').val();
addressZip = $('#companyzip').val();
companyLicense = $('#companylicense').val();
var data = `{
"categoryId": 9,
"companyName": "${companyName}",
"personalContactLicense": {
"licenseNumber": "${companyLicense}"
},
"businessContactLicense": {
"licenseNumber": "${agentLicense}"
},
"noSpam": true,
"firstName": "${firstName}",
"lastName": "${lastName}",
"accessLevel": "1",
"currentMailingAddress": {
"street1": "${streetAddress}",
"city": "${addressCity}",
"state": "${addressState}",
"zip": "${addressZip}"
},
"workPhone": "${workNumber}",
"mobilePhone": "${cellNumber}",
"faxNumber": "${faxNumber}",
"businessEmail": "${agentEmail}"
}`;
var options = {
"async": true,
"crossDomain": true,
"url": "https://api.elliemae.com/encompass/v1/businessContacts",
"method": "POST",
"headers": {
"Content-Type": "application/javascript",
"Authorization": token
},
"processData": true,
"data": data
};
console.log(options.data);
$.ajax(options).done(function (response) {
console.log(response);
});
}
I dont if the problem is me using varibles in the options for the ajax call but any help or being pointed in the right direction would greatly appreciated.
If you have form, you can simply do
var form_data = $('#yourformId').serialize();
And on your ajax options, simply include this
data: form_data,
I am not sure, how you are handling this ajax call and how you are preparing your response. You can debug to see where you is the problem.
Related
I am trying to write a test post to the Zip API:
Zip Api
JSON posted, as per Zip Pay's example -
{
"shopper": {
"title": "Mr",
"first_name": "John",
"last_name": "Smith",
"middle_name": "Joe",
"phone": "0400000000",
"email": "test#emailaddress.com",
"birth_date": "2017-10-10",
"gender": "Male",
"statistics": {
"account_created": "2015-09-09T19:58:47.697Z",
"sales_total_number": 2,
"sales_total_amount": 450,
"sales_avg_value": 250,
"sales_max_value": 350,
"refunds_total_amount": 0,
"previous_chargeback": false,
"currency": "AUD"
},
"billing_address": {
"line1": "10 Test st",
"city": "Sydney",
"state": "NSW",
"postal_code": "2000",
"country": "AU"
}
},
"order": {
"reference": "testcheckout1",
"amount": 200,
"currency": "AUD",
"shipping": {
"pickup": false,
"tracking": {
"uri": "http://tracking.com?code=CBX-343",
"number": "CBX-343",
"carrier": "tracking.com"
},
"address": {
"line1": "10 Test st",
"city": "Sydney",
"state": "NSW",
"postal_code": "2000",
"country": "AU"
}
},
"items": [
{
"name": "Awesome shoes",
"amount": 200,
"quantity": 1,
"type": "sku",
"reference": "1"
}
]
},
"config": {
"redirect_uri": "http://www.redirectsuccess.com/zipmoney/approved"
},
"metadata": {
"name1": "value1"
}
}
but I am getting an error message:
{"error":{"code":"request_invalid","message":"There are errors with the request, please see error items for more detail","details":[{"name":"Amount","message":"'Amount' must be greater than '0'."},{"name":"Currency","message":"Currency must be either 'AUD' or 'NZD'"},{"name":"Authority","message":"'Authority' must not be empty."}]}}
Cant figure out what is wrong. These elements exist in the data sent. Have used Axios and the request comes back fine. But Node's HTTPS object doesnt work. Why? :(
TIA
const postData = JSON.stringify(data);
let options = {
"host": 'api.sandbox.zipmoney.com.au',
"path": '/merchant/v1/charges',
"method": 'POST',
"port": 443,
"encoding": "utf8",
"headers": {
'Authorization': 'Bearer test',
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Zip-Version': '2017-03-01'
}
};
const req = https.request(options, (response)=>{
console.log(`statusCode: ${response.statusCode}`)
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log("have end data")
console.log(str);
});
})
req.on('error', error => {
console.log("zip errors...")
console.error(error)
})
req.write(postData)
req.end();
I had some time to take another look at your question, today, but still haven't found a definite solution to your specific issue. While this post may not answer your question, I wanted to post my findings here.
Here is the code that I tried (based on your code) on my side using a different test API:
// ref: https://stackoverflow.com/q/66218603/1167750
// ref: https://attacomsian.com/blog/node-http-post-request
const https = require('https');
let data = {
"title": "test",
"body": "Content",
"userId": 1
}
const postData = JSON.stringify(data);
let options = {
"host": 'jsonplaceholder.typicode.com',
"path": '/posts',
"method": 'POST',
"port": 443,
"encoding": "utf8",
"headers": {
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Zip-Version': '2017-03-01'
}
};
const req = https.request(options, (response)=>{
console.log(`statusCode: ${response.statusCode}`)
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log("have end data")
console.log(str);
});
})
req.on('error', error => {
console.log("zip errors...")
console.error(error)
})
req.write(postData)
req.end();
When I run this with Node, I get the output:
$ node test.js
statusCode: 201
have end data
{
"title": "test",
"body": "Content",
"userId": 1,
"id": 101
}
So I'm able to get a normal response back from this other API while using a lot of your code from your post. This seems to show that your approach with using Node's https module works for another API at least. Maybe this can help you narrow down where the issue is based on this test information.
Additionally, from your example json data, I don't see a place where the Authority field is filled out in your request. The error message you got indicated that it was required and the related documentation seems to require that too. But maybe this was simply removed from your json data before it was posted in your question for security reasons?
Seeing that you do have the amount and currency values set in your json order data, that seems to indicate that the API is not recognizing your json data that is being sent. But hearing that the axios approach works makes this issue still confusing.
Though it might not be necessary, I also checked your json data in a linter and it came back as valid (as you already know). Wanted to double check if there was some issue related to that, though.
I'm trying to get this code to track user visit but I can't manage to get it to work.
When I do this in Postman, I get successful, but to put it in the HTML I get nothing.
How do I make the script activate when user visit website? I need to pass on the values to a /registerLead on form submission afterwards.
<script>
var settings = {
"url": "https://api31.trackinglink3.com/SignalsServer/api/trackVisit",
"method": "GET",
"timeout": 0,
"headers": {
"apikey": "apikey",
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"devicetype": "",
"Offer": "",
}
};
</script>
Just use ajax function for this. check snippet below..
$(function(){
$.ajax({
method: "GET",
url: "https://api31.trackinglink3.com/SignalsServer/api/trackVisit",
"timeout": 0,
"headers": {
"apikey": "apikey",
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"devicetype": "",
"Offer": "",
}
})
.done(function() {
// your done code here
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have this function which is meant to POST JSON obtained from a GitHub API call:
postToDb: function(body) {
var http = require("http");
var options = {
hostname: 'localhost',
port: 9000,
path: '/issues',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: body
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('{"string": "Hello, World"}');
req.end();
}
However something like {"_id":"5b7c6d0457de7d6c7c4ae85b","__v":0} gets POST'ed instead. This is what I expected:
{
"url": "https://api.github.com/repos/TestOrg/test2/issues/4",
"repository_url": "https://api.github.com/repos/TestOrg/test2",
"labels_url": "https://api.github.com/repos/TestOrg/test2/issues/4/labels{/name}",
"comments_url": "https://api.github.com/repos/TestOrg/test2/issues/4/comments",
"events_url": "https://api.github.com/repos/TestOrg/test2/issues/4/events",
"html_url": "https://github.com/TestOrg/test2/issues/4",
"id": 347593311,
"node_id": "MDU6SXNzdWUzNDc1OTMzMTE=",
"number": 4,
"title": "test issue 2",
"user": {
"login": "my-repo",
"id": 32067576,
"node_id": "MDQ6VXNlcjMyMDY3NTc2",
"avatar_url": "https://avatars1.githubusercontent.com/u/32067576?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/my-repo",
"html_url": "https://github.com/my-repo",
"followers_url": "https://api.github.com/users/my-repo/followers",
"following_url": "https://api.github.com/users/my-repo/following{/other_user}",
"gists_url": "https://api.github.com/users/my-repo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/my-repo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/my-repo/subscriptions",
"organizations_url": "https://api.github.com/users/my-repo/orgs",
"repos_url": "https://api.github.com/users/my-repo/repos",
"events_url": "https://api.github.com/users/my-repo/events{/privacy}",
"received_events_url": "https://api.github.com/users/my-repo/received_events",
"type": "User",
"site_admin": false
},
"labels": [],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [],
"milestone": null,
"comments": 0,
"created_at": "2018-08-04T06:34:50Z",
"updated_at": "2018-08-04T06:34:50Z",
"closed_at": null,
"author_association": "CONTRIBUTOR",
"body": "In order to help resolve your issue as quickly as possible please provice the following information when \r\n\r\n1. What is the issue?\r\nAnother one!\r\n\r\n2. What are the steps to recreate the issue?\r\n\r\n\r\n3. Do you have any relevant code samples? If so, please provice them.\r\n\r\n\r\n4. Have you made any specific configurations?\r\n\r\n\r\n5. Do you get an error? If so please include it and any stack trace.\r\n\r\n\r\n6. What version of the API are you using?\r\n",
"performed_via_github_app": null,
"score": 1
}
It seems getGitHubIssues.postToDb(issueFormatForDb); passes the correct JSON but the body inside var req is different. I'm sure this is just something I don't yet understand. Could somebody please explain what is happening here and how I could change this function to POST the correct JSON?
See comments above. I had updated the JSON I'm POST'ing but forgot to update my schema.
Im trying to access to parameter value from response.
$.ajax({
type: "POST",
url: "",
dataType: 'text',
async: false,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: '{ "action" : "create", "resource" : {"name" : "teddssssssssddsssdsddddsdddwdsdssdsddi", "description": "Test Tenant Description","parent": {"href": "localhost"}}}',
success: function(as) {
alert(as[0][0]["id"]);
}
});
in the success area i got the response, in json. I want to access to the id value, but i cant. always says undefined, i tried different options.
this is the response format.
{
"results": [
{
"href": "localhost/1111111",
"id": "100000000111",
"name": "test",
"ancestry": "1000011111",
"divisible": true,
"description": "Test Tenant Description",
"use_config_for_attributes": false,
"default_miq_group_id": "10021200000173"
}
]
}
I dont know if i can access direct to the parameter or better get the response as text and split.
The response has a different structure.
Your response is an object with one property and value is an array of objects.
something like {'results': [...{}]}
Key 0 does not exist.
const data = {"results":[{"href":"localhost/1111111","id":"100000000111","name":"test","ancestry":"1000011111","divisible":true,"description":"Test Tenant Description","use_config_for_attributes":false,"default_miq_group_id":"10021200000173"}]};
console.log(data.results[0].id);
I am using auto generated the ajax with Postman 3, so you can tell if it's the correct way to do it, but this isn't my main question. Now, when I type the "data" field like this, it works
var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "8de908df-f970-524c-eb8b-d2f7f621a3ac"
},
"processData": false,
"data": "{\"name\":\"Peter\",\"id\":11}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Now my question is, how do I put custom parameters in the "data" field.
I want something like this
var arr = [{"name": "Peter", "id": 12}, {"name": "Demeter", "id": 15}];
var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "e37d3063-406d-02c3-803f-0f32666b9d70"
},
"processData": false,
data: {"name": arr[0].name, "id": arr[0].id}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When i send this POST request it gives me back 400(Bad request)
jQuery does not format your request as JSON but only as data url. You have to do this yourself:
data: JSON.stringify({"name": arr[0].name, "id": arr[0].id})
You need to convert the string to JSON format using stringify. Here is link to explanation:
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify