Build cusom json for ajax rest request - javascript

Im trying to send a request to a rest API and granted my knowledge using jquery is not advance however through numerous tutorials I'm struggling a bit to build a request based on this swagger documentation.
{
"fields": {
"": [
{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
}
This is the model of how i need to send the Rest request, im able to do this using postman however i struggle to do this in javascript.
var data = {};
var json = [{ "NAME": "name", "ADDRESS": "address", "EMAIL": "email" }];
data.fields ={json};
My problem is that in the model there is an empty quotation which im unable to replicate. I suspect that either the rest API is not the best or im missing something quite vital in building a request. See below for the actual ajax jquery request.
var request = $.ajax({
type: "POST",
url: urlBase,
contentType: 'application/json',
data: JSON.stringify({json}),
});
request.done(function (msg) {
alert(msg);
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
Error message based on the above request
Invalid field groups: [json] used in the search fields not found in duplicate store schema

You can create a json like this:
var obj = {
"": [{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
console.log(obj)
Hope it helps. Revert for any doubts.

Related

Jquery .unable to get jSOn values

I have the following code and i am trying to retrieve the userid , firstname and some values from JSON but I am getting undefined.
How can i fix this?
function getVal(val1,val2) {
var myval2 =URL +"webUser?email="+email;
var uId='';
$.ajax({
url: myval2,
dataType: "json",
cache: false,
success: function(data, textStatus, jqXHR) {
jQuery.each(data, function(k,v) {
console.log( " k " +k + " v" + v);
uId =v.uId;
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('FAILED to get JSON from AJAX call' + jqXHR + textStatus + errorThrown);
}
});
console.log("userid " +userId);
return userId;
}
JSON
{
"userId": 2,
"emailAddress": "some#some.com",
"roleId": 1,
"firstName": "Hulk",
"lastName": "Ogan",
"company": "MTT",
"title": "Lord Vader",
"phoneWork": "",
"phoneMobile": "",
"lastModifiedBy": "system",
"versionNumber": 1
}
You can simply get value of userid and other properties like this
userID = data.userId;
No need of loop because your data is only a single object you will need loop if your data was an array of objects
One problem I can see is that your json record is just that: a single record; so, you don't need $.each to iterate through the ajax result - that would only be necessary if your returned data consisted of a json array with potentially many records.
Other than that, you will just need to do some bug tracking:
Is your http action on your website set up to handle GET actions? If it needs a POST action you will need to specify that in your ajax call.
Leading on from 1 - are you certain that your call to the url does return a json result? Can you navigate to that url in a browser and see the json result?
If both of those are taken care of, check what "data" contains when it returns. If it is empty or not well formed json, figure out why.
You don't need to jQuery.each, because you don't have a JsonArray and you have JsonObject.
You can easily get you data with:
userID = data.userId;
and
userID = data['userId'];
(like as Madalin & Leopars answers)
You can simply get value of userid and other properties like this
userID = data['userId'];
var data = {
"userId": 2,
"emailAddress": "some#some.com",
"roleId": 1,
"firstName": "Hulk",
"lastName": "Ogan",
"company": "MTT",
"title": "Lord Vader",
"phoneWork": "",
"phoneMobile": "",
"lastModifiedBy": "system",
"versionNumber": 1
};
console.log(data['userId']);
Note: you can't return any values from a asynchronous ajax request, do all your logic in the success function of your ajax call

Mandrill "reject_reason":"unsigned"

I'm trying to send emails using mandrill email service but I get the following error:
[
{
"email": "pranav_withyou#hotmail.com",
"status": "rejected",
"_id": "daab0daa538a4fe9b161be709593be0b",
"reject_reason": "unsigned"
}
]
I am trying to send email using ajax call in javascript like :
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
"key": "RemovedforSecurityitscorrect",
"message": {
"html": "<p>Example HTML content</p>",
"text": $('#emailText').val(),
"subject": $('#emailSubject').val(),
"from_email": $('#fromEmail').val(),
"from_name": $('#fromName').val(),
"to": [{
"email": $('#toEmail').val(),
"name": $('#recipientName').val(),
"type": "to"
}],
"headers": {
"Reply-To": $('#fromName').val()
}
},
success: function (data) {
console.log("Email Sent");
},
error: function (xhr, status, error) {
console.log("Error while sending mail");
}
}
});
all values are coming to ajax call & call is made to server evident from response. What can be issue?
I got the reason, it was silly mistake. I was trying to send mail through my personal email id which is on different domain than to for which Mandrill is configured & verified.
Searching for the reason of error, I found that this error is sent from Mandrill when Mail sent from unverified domains or domains without valid SPF and DKIM records will be rejected with the reject_reason, unsigned.
For more information refer
https://mandrillapp.com/api/docs/messages.html
https://mandrill.zendesk.com/hc/en-us/articles/205582247-About-Domain-Verification
https://mandrill.zendesk.com/hc/en-us/articles/205582267-About-SPF-and-DKIM
For doing required setting related to SPF & DKIM for Mandrill please refer:
https://mandrill.zendesk.com/hc/en-us/articles/205582277-How-do-I-add-DNS-records-for-my-sending-domains-

How can I get response from webservice in jquery?

I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help

MediaWiki JSON Api always returning "undefined"

I'm trying to retrieve some data from the MediaWiki Api; especifically the registration date of a certain user. Taking Wikipedia as a live example, according to their Api sandbox, the request URL to get the information of Jimmy Wales would be:
/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales
So I make an Ajax call:
$.ajax({
dataType: "jsonp",
url: "/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales",
success: function (data) {
var timestamp = data.query.registration;
console.log(timestamp);
}
});
But if I run that script on Firebug, I simply get "undefined". What am I missing?
The resulting JSON data is something like:
{
"batchcomplete": "",
"query": {
"users": [
{
"userid": 24,
"name": "Jimbo Wales",
"registration": "2001-03-27T20:47:31Z"
}
]
}
}
Of course, data.query.registration is undefined. it is not available. Your have to "address" the user itself. Like data.query.users[0].registration.

POST request is returning response success but is not posting the data

I am making a POST request to the MOXTRA API and it should return me the following response :
{
"data":
{
"id": user_id, //some user id
"revision": 5,
"name": "My First Binder",
"created_time": 1402384947587,
"updated_time": 1402384947587
},
"code": "RESPONSE_SUCCESS"
}
And I am making this POST request using Java Script
var d =
{
'name': 'My First Binder'
};
var bind = JSON.stringify(d);
$.post('https://api.moxtra.com/user_id/binders?access_token=' + access_token+ '&callback=?', bind, function(response) {
alert( response.data.id);
},'json');
})
But the alert that i get for alert(response.data.id) is "undefined"
and the alert if i write alert(response.code) is "RESPONSE_SUCCESS"
What is wrong with the above code , how am i getting a response success and getting undefined at the same time

Categories