ASP.NET MVC 6 API and Jquery ajax problems - javascript

I made an easy service to sort a list of integers for a class using ASP MVC 6.
My ajax post request to the API on a different local host is not working correctly. The HTML/Javascript is here.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-2.0.0.min.js"></script>
<script src="Scripts/bootstrap.js"></script>
<link rel="stylesheet" href="Content/bootstrap.css" />
</head>
<body>
<form>
<input type="text" id="arr" />
<button class="btn btn-lg" id="arrbtn">Push Me</button>
<script type="text/javascript">
$("#arrbtn").click(function () {
var thing = $("#arr").val().split(' ').map(Number);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://localhost:58453/api/sort",
data: JSON.stringify({ arr: thing }),//have also tried this without stringify, encoding as string, hardcoding a json with and without stringify
}).done(function (data) {
alert("plx");
}).error(function () { alert("error");});
});
</script>
</form>
</body>
</html>
When I run this on localhost, fiddler shows me that there is no header for "Content-type application/json", and the body of the request is blank.
If I remove the contentType and dataType fields from the request, data is sent, but the header now has
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
My API promptly passes null into my action and returns a bad request.
I know my API is working correctly as I can make a fiddler post and get a proper response back.
Edit 1: Action Method on request. Here is the whole controller
Edit 2: Changed the string to array of numbers.
[Route("api/[controller]")]
public class SortController : Controller
{
[FromServices]
public ISortRepository sortArray { get; set; }
// POST api/sort
[HttpPost]
public IActionResult Submit([FromBody]SortItem item)
{
if (item == null)
{
return HttpBadRequest();
}
//sortArray.stringToInts(item);
sortArray.sort(item);
return new ObjectResult(item);
}
}

Related

Ajax post multiple data to flask

The way I send one data to flask
.js
function func(s) {
let toPost = {name: f.name, sf: split.f};
let jsonStr = JSON.stringify(toPost);
$.ajax({
url: "temp",
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
success: function(){
console.log("success")
}
});
}
.py
#app.route('/temp', methods = ['POST'])
def temp() :
jsonStr = request.get_json()
file_object = open('temp.txt', 'a')
file_object.write(jsonStr)
file_object.write("\n")
file_object.close()
return render_template('temp.txt')
But I would like to send multiple data, so the ajax look like this:
data: {str: JSON.stringify(data), method: "add"}
Everything else remains the same.
In the .py file how could I get both str and method as well?
errors
console
jquery-3.2.1.min.js:4 POST FILENAME 400 (BAD REQUEST)
com
127.0.0.1 - - [] "POST /FILENAME HTTP/1.1" 400 -
full error
Your code leaves a lot of room for speculation.
The error message you get results from the fact that you want to send data as JSON but do not format it completely compliantly.
Normally, submitted objects are automatically sent as form data and formatted accordingly beforehand. You suppress this behavior by setting the processData parameter to false. However, this also means that the formatting to JSON must also be done by you. Otherwise a string representation of the transferred object would be sent, which the server cannot interpret.
As the following example shows, you should convert all data to JSON using JSON.stringify(...) before sending it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
<style media="screen">
output {
white-space: pre;
}
</style>
</head>
<body>
<form name="my-form">
<input type="text" name="name" />
<input type="text" name="sf" />
<input type="submit" />
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(() => {
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
const form = $(this);
const formData = {};
$.each(form.serializeArray(), (_, row) => {
formData[row.name] = row.value;
});
// => { name: <anything>, sf: <something> }
console.log(formData);
const method = 'add';
const data = { data: formData, method: method };
// => { data: { name: <anything>, sf: <something> }, method: "add" }
console.log(data);
$.ajax({
url: '/temp',
type: 'post',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
processData: false
}).done(data => {
$('output[name="result"]').html(data);
});
});
});
</script>
</body>
</html>
Depending on the requirements, you can query the data on the server side using its key, since it has already been parsed from the JSON format.
Since you get a dict for your nested object because of this, a conversion to a string is necessary before you can write it to the file.
import json, os
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/temp', methods=['POST'])
def temp():
data = request.json.get('data')
method = request.json.get('method', 'add')
if method == 'add' and data:
path = os.path.join(app.static_folder, 'temp.txt')
with open(path, 'a') as fp:
print(json.dumps(data), file=fp)
return app.send_static_file('temp.txt')
Please note that this is a simplified example trying to be based on your specifications.

"MultipartException: Current request is not a multipart request" when trying to upload file using javascript+ajax (works from postman)

I am trying to create a web form that will allow uploading a single file from the browser to my own server.
The backend API is spring boot based, the specific controller was tested with postman and worked well. Now when I am trying to make the same for my website using JavaScript and ajax I get the following error:
Client side: Error 400 and
> {"status":"NOT_FOUND","message":"Current request is not a multipart
> request","timestamp":1604939158692}
server-side:
org.springframework.web.multipart.MultipartException: Current request
is not a multipart request
I have tried ~10 of the accepted solutions from other question on stackoverflow, but nothing helped.
These are the relevant code parts.
Spring controller:
#PostMapping("/add_users_from_csv")
public ResponseEntity<String> addUsersListFromCSVFile(#PathVariable String id, #RequestParam("file") MultipartFile file, #RequestParam("club") String clubId, #RequestParam("notifyByEmail") boolean notifyByEmail, #RequestParam("notifyBySMS") boolean notifyBySMS) throws UnauthorizedRequestException {
businessService.securityCheckID(id);
return clubService.addUsersListFromCSVFile(clubId, file, notifyByEmail, notifyBySMS);
}
Client:
<html>
<body>
<form name="uploadForm" id="fileUploadForm" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file" value="Import"">
<input type="submit" value="Import" id="Import" />
</form>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('form[name="uploadForm"]').submit(function(event){
event.preventDefault();
var formData = new FormData($('#fileUploadForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
formData.append("club", "5cc5fd05569a720006169111");
formData.append("notifyByEmail", "true");
formData.append("notifyBySMS", "true");
$.ajax({
url: 'http://localhost:8090/business/5cc625ed3ba686000665f111/add_users_from_csv',
data: formData,
type: "POST",
contentType: false,
processData: false,
cache: false,
"headers": {
"Content-Type": "application/json",
"Authorization": "bearer 0278e739-fbe0-4e3d-9acf-57544b011111"
},
success : function(response){
alert(response);
},
error: function(xhr,status,errorThrown) {
alert(xhr.status);
}
});
return false;
});
</script>
</body>
</html>
Postman request (that works well with the same server):
What makes the request from browser fail and how to fix it please ?

Sending POST request with AJAX which is intercepted by Burp Suite

I intercepted a POST request with Burp Suite and I want to send this request manually from JavaScript Ajax call.
This is my request's raw:
I tried to send POST request like that:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: 'POST',
url: 'http://10.10.20.103/mutillidae/index.php?page=add-to-your-blog.php',
data: {
'csrf-token': '',
'blog_entry': 'post from ajax',
'add-to-your-blog-php-submit-button': 'Save+Blog+Entry'
};
});
</script>
</head>
<body>
</body>
</html>
But I couldn't manage it. Where is my mistake? Or, how should I do this? How could I convert raw request to Ajax request?
Thanks!
The correct solution is:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
method: 'POST',
url: 'http://10.10.20.103/mutillidae/index.php?page=add-to-your-blog.php',
data: {
'csrf-token': '',
'blog_entry': 'post from ajax',
'add-to-your-blog-php-submit-button': 'Save+Blog+Entry'
},
xhrFields: {
withCredentials: true
}
});
</script>
</head>
<body>
</body>
</html>
I forgot a semicolon at the end of the data field's closing curly brace. An addition, I must add xhrFields field for bypassing cookie needing.

JavaScript/JQuery/HTML - Use output of one script as variable in another script

I am making a small chrome extension. Its purpose is to make an API call to retrieve some JSON which is then stripped out to show only Name, Email & Team which is then presented to the user. The user then has the option to send that information to a slack channel via a button.
Everything works fine, my API call shows the correct information, My Webhook for slack works fine with a test message.
My issue is I dont know how to put whats returnd from my API call as variables to send to slack
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
I.e.
var text = '$('.Name') + 'was contacted from' + $('.Teams') + 'Their email addres is' + $('.Email')''
Example slack message
John Smith was contacted from Sales Team Their email address is jsmith#mysite.com
HTML
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<meta content="noindex, nofollow" name="robots">
<meta content="noindex, nofollow" name="googlebot">
<script src="jquery-git.js" type="text/javascript"></script>
<script src='apicall.js'></script>
<script src='slackapi.js'></script>
<title>Call Logger</title>
</head>
<style>
</style>
<body>
<div class="container">
<form id="contact" action="" method="post">
<h3>Call Logger</h3><br>
<h2><div class="Name"></h2>
<h2><div class="Address"></h2>
<h2><div class="Teams"></h2>
<h2><div class="Email"></div></h2>
<h2><div class="Role"></div></h2>
<br>
<br>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Send</button>
</fieldset>
</form>
</div>
</body>
</html>
apicall.js
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Teams').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
slackapi.js
$(document).ready(function(){
$('#contact-submit').on('click',function(e){
e.preventDefault();
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'This is a message'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text // What I want to dynamically change
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});
I obviously can't reproduce your setup, but, depending on what kind of pages are apicall.js and slackapi.js - there are some restrictions and particularities in the case of content/background pages -, I think you can send the text variable (or even its constituent parts, e.g. name, teams, email, using an array) to slackapi.js by message passing.
You send the message from apicall.js usually using chrome.runtime.sendMessage() (other options are available, depending on context), and you receive the message using a listener, e.g. chrome.runtime.onMessage.addListener(). For the message to be received, slackapi.js or any other JS file needs to run, so if it doesn't it needs to be injected using chrome.tabs.executeScript(), for example.
I'm not sure if this will help you, but at least I tried.

Can not make ajax call to server

I've tried to use ajax in Spring MVC App but it seems not working I searched for that and found many resources but as I'm not a pro I could not understand any of those, finally I found this tutorial as a grace and tried in Controller as
#RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestParam String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
and javascript is
$(document).ready(function() {
$(function() {
$("#bar-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getBars",
type: "POST",
data: { term: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
});
and finally my view.jsp is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="initial-scale=1.0, width=device-width" name="viewport">
<title>Ask Question</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"/></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="/app/resources/js/autoComplete.js"></script>
<script>
if (window.jQuery) {
alert('jQuery is loaded');
} else {
alert('jQuery is not loaded');
}
</script>
<!-- css -->
<link href="/app/resources/css/base.css" rel="stylesheet">
<!-- favicon -->
<!-- ... -->
<!-- ie -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="login-username">Bars</label>
<input id="bar-search" name="bars" class="form-control" type="text" value=""/>
</div>
</div>
</div>
<script src="/crazy/resources/js/base.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/webfont.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/jquery.autocomplete.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
</body>
</html>
every thing is ok when app starts but when I write some text down in input I get error
can any one solve this error for me or tell me where am I wrong.
sorry if my English is incorrect.
Ok... the first thing is that your service is configured wrongly.
Your service wants a #RequestParam, but in your ajax you are sending a json object which means you should be accepting a #RequestBody.
Also, if you are looking for a #RequestParam, you need to pass the value as part of the url like...
$.ajax({
url: "/app/getBars?bar=" + request.term,
type: "GET"
( ... )
});
#RequestMapping(value = "/getBars", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestParam(value = "bar", defaultValue = "abc", required = false) String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
or
$.ajax({
url: "/app/getBars/" + request.term,
type: "GET"
( ... )
});
#RequestMapping(value = "/getBars/{bar}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Bar> getBars(#PathVariable String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
For a post.
First create a bean.
public class MyRequestBean implements Serializable{
private static final long serialVersionUID = 1L;
private String bar;
public void setBar(String bar){
this.bar = bar;
}
public void getBar(){
return this.bar;
}
}
and then write your service like this...
#RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestBody MyRequestBean bean, HttpServletResponse response) {
return barService.findBarByName(bean.getBar());
}
$.ajax({
url: "/app/getBars/,
type: "POST",
data: JSON.stringify({bar : request.term})
( ... )
});
NOTE: never have the verbs defining your service.
For example, /getBars can be changed to just /bars and let the HTTP protocol (GET, POST, PUT or DELETE etc..) descide which operation you are trying to perform.

Categories