JIRA Rest API error. Unrecognized token creating a issue - ajax

No luck in adding a issue via AJAX and the REST API. I can get it to work with Postmen, unfortunatly, can't get it with an Ajax request.
The JSON I create is fine, the post request also. The issuetype is something I created myself, using Bug gives the same problem. See the JSON object created, my error and my code:
JSON object (this is a snippet from console.log):
The Error
0: "Unrecognized token 'fils5poet5': was expecting 'null', 'true',
'false' or NaN↵ at [Source:
org.apache.catalina.connector.CoyoteInputStream#7b958ed2; line: 1,
column: 21]"
jira = {
fields : {
project : {
key : "CIC"
},
summary : "test",
description: "test",
issuetype : {
name : "Sandbox item"
}
}
};
console.log(jira); //Also see image at top of this post.
// Submit to Jira api
$.ajax({
type : "POST",
dataType : "JSON",
url : configuration.api_url,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic ItsAWrap!(itworks...)"),
xhr.setRequestHeader ("Content-Type", "application/json");
},
data : jira,
success : (function(response) {
//Do something
}})

You need to JSON.stringify your jira variable before you send it.

You could try something like this:
jira = {
"fields":
{
"project":
{
"key": "CIC"
},
"summary": data["story.name"],
"description": data["story.notes"],
"issuetype": { "name": "Sandbox item" }
}
};
//THIS BADASS FUNCTION!!!
jira = JSON.stringify(jira);
$.ajax({
type : "POST",
url : configuration.api_url,
dataType : "JSON",
async : false,
headers: {
"Authorization": "Basic YeahSomethingInAWrap",
"Content-Type": "application/json",
"Accept": "application/json",
"Cache-Control": "no-cache"
},
data : jira,
success : (function(response) {
// Hide loader
l.removeClass("show");
// Alert Success Message
alert("Melding succesvol ontvangen, bedankt!");
// Close dialog
$(".chrome-extension-dialog a.close").trigger("click");
})
});

Related

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

Laravel 5: Retrieve JSON array from $request

I'm a Laravel newbie and I'm converting a php/jquery app to Laravel. The original code used a JSON array with an ajax POST, which was retrieved like this:
$json = file_get_contents('php://input');
$data = json_decode($json,true);
I'm doing much the same thing on the POST side, but I don't see any data coming through in my Laravel $request collection. Is there something special that I need to do to retrieve JSON data structured like this:
[
{ "name": "John", "location": "Boston" },
{ "name": "Dave", "location": "Lancaster" }
]
Here is my jQuery ajax POST code (with hard coded data)
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
success:function(data) {
$('#save_message').html(data.message);
}
});
Here is the code in my Controller that receives the POST
public function store(Request $request)
{
dd($request->all());
}
But all I get is:
[]
Any ideas on how I can retreive my data?
You need to change your Ajax call to
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
contentType: "json",
processData: false,
success:function(data) {
$('#save_message').html(data.message);
}
});
change the dataType to contentType and add the processData option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());
$postbody='';
// Check for presence of a body in the request
if (count($request->json()->all())) {
$postbody = $request->json()->all();
}
This is how it's done in laravel 5.2 now.
Just a mention with jQuery v3.2.1 and Laravel 5.6.
Case 1: The JS object posted directly, like:
$.post("url", {name:'John'}, function( data ) {
});
Corresponding Laravel PHP code should be:
parse_str($request->getContent(),$data); //JSON will be parsed to object $data
Case 2: The JSON string posted, like:
$.post("url", JSON.stringify({name:'John'}), function( data ) {
});
Corresponding Laravel PHP code should be:
$data = json_decode($request->getContent(), true);
You can use getContent() method on Request object.
$request->getContent() //json as a string.
As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the
JSON data via the input method as long as the Content-Type header of
the request is properly set to application/json. You may even use
"dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all() should work.
My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all() in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.

How to pass parameters without using url

I have number of values.
I need to pass these values to another page without using the window.location
function sample(cID){
var clg = ${param.clg};
$.ajax({
type : "post",
url : "sampleShow?clg="+clg+"&cID="+cID+"&level="+level,
dataType : "json",
cache : false,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
window.location= "cc"
},
error : function(xhr) {
console.log("error"+xhr.status);
},
complete : function() {
}
});
}
This is my controller ajax function:
#RequestMapping(value = "sampleShow", method = RequestMethod.POST)
public #ResponseBody
String showc(HttpServletRequest request,Model model)
{
model.addAttribute("ccID", request.getParameter("cID"));
model.addAttribute("clg", request.getParameter("clg"));
model.addAttribute("level", request.getParameter("level"));
return "{\"sucess\":\"true\"}";
}
I need to get the values in cc page.
Your ajax call should like:
$.ajax({
type : "post",
url : "sampleShow",
data : {clg: clg, cID: cID, level: level },
success : function(response) {
window.location= "cc"
},
error : function(xhr) {
console.log("error"+xhr.status);
},
complete : function() {
}
});
No need to specify dataType: "json", as you are not sending json. Data is passed using 'data'. Refere jQuery.ajax() for more details.
You can also use shorthand method jQuery.post(), to post instead of jQuery.ajax()
You may also like to read on what-is-the-difference-between-post-and-get.

is this ajax call for below rest Service is correct or not?

Sample rest Service is below:
#RequestMapping(value = "/image/upload", method = RequestMethod.POST)
public void uploadImage(#RequestParam("image") MultipartFile fileObj)
throws Exception
{
System.out.print("File Name:"+fileObj.getOriginalFileName());
}
and i wrote ajax code like this :
and my accept application format is Json when i call this i get 400 error
$('#user_click').click(function(){
var data = {
image:$("#file_1").val
};
$.ajax({
url : "http://localhost:8080/MyProject/image/upload",
type : "POST",
contentType : false,
crossDomain : true,
data : JSON.stringify(data),
dataType : 'json',
async : true,
success : function(result) {
alert('The Selected Items uploaded');
},
error: function(message){
alert("Error:"+JSON.stringify(message));
}
});
is this ajax code is correct or not?
No, it will not work since ajax request will not transfer file data.
The solutions are
Use a file upload plugin like jquery-form
Ex:
$('#myForm').ajaxSubmit({
url : 'http://localhost:8080/MyProject/image/upload',
type : "POST",
dataType : "json",
success : function(response) {
},
error : function(response) {
}
});
Use html5 FormData (Sadly no IE support)

AJAX : How to get info about permission reject

I have an ASP.NET MVC application, where I call method by AJAX:
$.ajax({
dataType: 'json',
url: "/Admin/AllowVideoUpload",
type: "POST",
data: { val: val },
error: function () {
alert('Error');
}
});
if success - nothing happens on client side, if error - get 'Error' message. But error can be by different reasons - problem inside "AllowVideoUpload" method or user lost his credentials (AdminController has attribute 'Authorize(Roles = "Admin")'). I want to differ these 2 types of error. How to do it?
Those are your application level errors. So it should be handled in the success handler.
You may return json from your action method which has a Status /Error code/Message element where you mention what is the error reason.
Sample Json for Error
{
"Status": "Failed",
"Message": "Authentication Failed"
}
Sample Json for Success
{
"Status": "Success",
"Message": "Successfully Updated"
}
Read the jSon and then you can decide what to do next.may be show message to user
$.ajax({
dataType: 'json',
url: "/Admin/AllowVideoUpload",
type: "POST",
data: { val: val },
success:function(data){
if(data.Status=="Success")
{
//operation success. do whatever
}
else if(data.Status=="Failed")
{
alert(data.Message);
}
},
error: function () {
alert('Error');
}
});

Resources