How to properly post JSON data using Ajax to Flask [duplicate] - javascript

update: I would like to pass the var value to the server
hello,
same old, same old ... :)
I have a form called <form id="testForm" action="javascript:test()"> and a code area called <code id="testArea"></code>
I am using this code to stringify and display the data in the code area:
var formData = form2object('testForm');
document.getElementById('testArea').innerHTML = JSON.stringify(formData, null, '\t');
var value = JSON.stringify(formData, null, '\t');
What I want is to send this data to a JSON file.
I've been working on this project : http://ridegrab.com/profile_old/ and if you press Submit Query button you will see the head of the page populate.
Also I want use this piece of script to send data:
function authenticate(userName, password) {
$.ajax
({
type: "POST",
//the url where you want to sent the userName and password to
url: 'username:password#link to the server/update',
dataType: 'json',
async: false,
//json object to sent to the authentication url
data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
success: function () {
alert("Thanks!");
}
})
}
Again, all I want is to be able to send that JSON data to the server. My server is set up to update or POST the data in the right place.

You post JSON like this
$.ajax(url, {
data : JSON.stringify(myJSObject),
contentType : 'application/json',
type : 'POST',
...
if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

'data' should be a stringified JavaScript object:
data: JSON.stringify({ "userName": userName, "password" : password })
To send your formData, pass it to stringify:
data: JSON.stringify(formData)
Some servers also require the application/json content type header:
contentType: 'application/json'
There's also a more detailed answer to a similar question here: Jquery Ajax Posting JSON to webservice

In case you are sending this post request to a cross domain, you should check out this link.
https://stackoverflow.com/a/1320708/969984
Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

Related

How to send file?

I want to send an image to my telegram bot via javascript (not Node.js). For this I need the token of the bot and my Telegram user ID.
Sending text messages works fine, I also succeeded in sending photos, which I gave as LINK. Now I want to take my own photos and send them directly to my bot.
This is a part of the telegram documentation:
So as I understood it, I can also send images as a file and not as a link using a post request. Unfortunately I had no great success with the implementation:
let token = "xy",
chat_id = "123"
let url = `https://api.telegram.org/bot${token}/sendPhoto?chat_id=${chat_id}`;
$("form").submit(function(e) {
let formData = new FormData(this);
e.preventDefault();
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function(r) {
console.log(r);
},
error: (e) => {
console.log("Error", e)
}
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input id="fileInput" type="file" />
<input type="submit" value="submit" />
</form>
How can I implement this in pure javascript and working?
Note that https://api.telegram.org/bot${token}/sendPhoto?chat_id=${chat_id}&photo=${link_to_photo} is working.
Though it's not obvious from the jQuery documentation, you need to set two more ajax options:
processData: false
processData (default: true)
Type: Boolean By default, data passed in to the data option as an object (technically, anything other than a string) will be processed
and transformed into a query string, fitting to the default
content-type "application/x-www-form-urlencoded". If you want to send
a DOMDocument, or other non-processed data, set this option to false.
FormData should be sent unprocessed
contentType: false
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded;
charset=UTF-8", which is fine for most cases. If you explicitly pass
in a content-type to $.ajax(), then it is always sent to the server
(even if no data is sent). As of jQuery 1.6 you can pass false to tell
jQuery to not set any content type header. Note: The W3C
XMLHttpRequest specification dictates that the charset is always
UTF-8; specifying another charset will not force the browser to change
the encoding. Note: For cross-domain requests, setting the content
type to anything other than application/x-www-form-urlencoded,
multipart/form-data, or text/plain will trigger the browser to send a
preflight OPTIONS request to the server.
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false, // TO SEND DATA UNPROCESSED
contentType: false, // TO OVERRIDE THE DEFAULT
success: function(r) {console.log(r);},
error: (e) => {console.log("Error", e)}
// return false; <-- REMOVE THIS FROM HERE
});

Javascript API POST Request from URL

Forgive me if I have titled this tread wrong, I don't know the correct terminology.
I have a link with values included, they are: id and environment therefore the url it formatted such ad https://foo.com?id=1234&e=s
With this url I need to take the id and the environment (Stage or production) and create a post body to set a flag as true.
So if e=s (environment = stage) I need post to
https://services-stage.foo.com/api/account//flag
Or if e = p (production)
https://services.foo.com/api/account//flag
Where = the id in the url
With POST body:
{
"type": OptionFlag,
"flag": true //Flag should be set to true
}
My problem is I don't know where to start with my limited javascript knowledge. I have created GET requests form api's in the past but never POST and never with parameters in the URL.
I now understand how to handle the post, however I am still at a loss on how I would get the Id and the environment data from the url to then pass them to the ajax url in the function.
function CustomerId(){
//Function for getting id number from URL
}
function apiEnvironment(){
//Function for getting environment from URL
}
function OptOut(CustomerId, apiEnvironment) {
jQuery.ajax({
type: 'POST',
url: apiEnvironment + '/api/v1/account/' + CustomerId + '/optOut',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data : data,
success: {
}
});
}
This Is what I have so far...

Why does node.js attach a string value in my array to another object in the array as true?

I'm not sure why this is happening, but could use some input.
I have an object attached to the body of a POST request through jquery ajax. The object is similar to this example:
var dogData = {breeds: [{Dog: "Golden Retriever"}, "Rottweiler"]}
The AJAX request is this:
$.ajax({
type: "POST",
url: "api/dog",
data: dogData,
})
On my server using Express + bodyparser:
app.post('/dogs', function(req, res){console.log(req.body)})
When I console.log the object:
{breeds: [{Dog: "Golden Retriever", Rottweiler: true}]}
I want the same object that I initially started out with to be returned from the server. Can someone explain why the string is attached to the previous object along with a boolean value?
use jsonparser on your server and make your post with json content
$.ajax({
type: "POST",
url: "api/dog",
data: JSON.stringify(dogData),
contentType: 'application/json; charset=utf-8'
})
Body parser parses urlencoded form data.
When you send your data it will be converted to:
breeds[0][Dog]=Golden+Retriever&breeds[Rottweiler];
When bodyparser parse it, because of there is no value on Rottweiler and it exists, it will be converted to "true"

Ajax POST data in Request Param

I am making a POST request as below :
$.ajax({
url :"/clientCredentials.json",
type: "POST",
data: {
"clientEmail": email,
"clientName":clientName,
"orgName":orgName,
"logoURL":logoURL,
"redirectURI":redirectUri
},
success: function(response){
alert("sucess");
},
error:function(response){
alert("something went wrong");
}
});
On the server, I am using #RequestParams to get this data.
#RequestParam String clientEmail, #RequestParam String clientName, #RequestParam String orgName, #RequestParam String logoURL, #RequestParam String redirectURI
I am getting below from from server:
{"code":"400","errorMessage":"Required String parameter 'clientEmail' is not present"}
If I use #RequestBody instead of #RequestParam to accept this data its working fine.
My question is How can I get this data in Request Parameters? What am I doing wrong?
I have tried Jquery($.get(), $.post()) also. nothing working.
Thanks for any help.
I just did small project with latest version of spring boot and jquery and it is working well, and based on investigation I did I found there are 2 factor can make this issue, one from jquery and other one from Spring MVC converters:
1- jquery ajax have contentType parameter
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
if this one changed to application/json or application/xml will change the way it is sending request to server then will make issue to server parsing, but it is default value will send form as key=value coma separated and this is OK with FormHttpMessageConverter "which is drive us to next point"
2- spring MVC is using FormHttpMessageConverter for "application/x-www-form-urlencoded" parsing or converting then you can use #RequestParam if this converter changed to other converter like:
MappingJackson2HttpMessageConverter for 'application/json'
or
Jaxb2CollectionHttpMessageConverter for 'application/xml'
so it will expect another request and you can get it using #RequestBody
So, you have to check request going from jquery is it form, json, or xml using development tools in your browser, then check you spring code/configuration to be sure that this request is converted by the FormHttpMessageConverter, this converter could be changed by the parameters of your #RequestMapping.
you cant use $.get with payload(data) but you can use $.post. please add attribute contentType in your request parameter.
$.ajax({
url :"/clientCredentials.json",
type: "POST",
contentType: "application/json",
data: {
"clientEmail": email,
"clientName":clientName,
"orgName":orgName,
"logoURL":logoURL,
"redirectURI":redirectUri
},
success: function(response){
alert("sucess");
},
error:function(response){
alert("something went wrong");
}
});

Ajax post request string data instead of object

Similar to this question I need to send a string as data in a post request.
Unlike that one, I can't use an object because I have repeated items. As you can see in my sample data sn1, sn2 and sn3 are repeated several times on different datetimes.
Sample data:
&sn3=2013-2-4T12:43:52&sn3=2013-2-4T12:43:55&sn1=2013-2-4T12:43:59&sn1=2013-2-4T12:44:0&sn2=2013-2-4T12:44:0&sn3=2013-2-4T12:44:2&sn2=2013-2-4T12:44:3&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn2=2013-2-4T12:44:19&sn3=2013-2-4T12:44:21&sn2=2013-2-4T12:44:22&sn2=2013-2-4T12:46:39&sn3=2013-2-4T12:46:42&sn2=2013-2-4T12:46:44&sn2=2013-2-4T12:46:45&sn2=2013-2-4T12:46:46&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:49:44&sn2=2013-2-4T12:50:21&sn2=2013-2-4T12:52:21&sn2=2013-2-4T12:52:24&sn2=2013-2-4T12:57:35&sn3=2013-2-4T12:57:38&sn3=2013-2-4T12:57:39&sn2=2013-2-4T12:57:39&sn2=2013-2-4T12:57:40&sn3=2013-2-4T12:57:46&sn3=2013-2-4T13:21:30
I tried using the following
console.log(screens); //logs my sample data posted above.
$.ajax({
url : url,
type: "POST",
dataType : 'text',
data : screens,
success : function(data) {
console.log("sucessfull sending:")
console.log(data);
},
error : function() {
console.log('failed');
}
});
But it always triggers failed.
Can I send it as a string? If not, how can I send multiple items with the same key?
console.log(screens); //logs my sample data posted above.
$.ajax({
url : url,
type: "POST",
dataType : 'text',
data : {screens:screens},
success : function(data) {
console.log("sucessfull sending:")
console.log(data);
},
error : function() {
console.log('failed');
}
});
See data : {screens:screens},, if you do something like that, on server you will be able to get it like: screensString = Request["screens"]. After that, screensString will contain a single string with all screens.
When you don't specify contentType in the ajax options, your request will default to 'application/x-www-form-urlencoded; charset=UTF-8'.
However, when your post data is just text, you should make the server aware of that fact by specifying a contentType 'text'.
As opposed to the contentType, the dataType specifies the type of response data that you expect back from the server.
I think what you need is to use [] in your parameters.
instead of sending &sn3= multiple times (which is rewriting itself) send it as an array like this &sn3[]=
if you are getting this data from an form input use name="sn3[]" and if this is the case, I would recommend you use $('#yourform').serialize() as data sent

Categories

Resources