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
});
Related
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.
I'm trying to send array files using JS. My code:
var formData = new FormData();
formData.append("files", files);
$.ajax({
url: './upload.php',
method: 'post',
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('Files uploaded successfully. ');
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
In this image you can see the response(red) from php https://beta.ctrlv.cz/mUwx and also you can see the files array data. My php code is:
<?php
echo $_POST['files'][0]["name"];
?>
I want use php script for upload, but the ajax didn't sent the array of file, which is important for uploading.
Here's an answer that I found:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Here the source: https://stackoverflow.com/a/5976031/7282094
Hope that help.
Change contentType: false, to contentType: "multipart/form-data", possibly.
Taken from http://api.jquery.com/jquery.ajax/
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.
I'm trying to use this to get image URL's http://aminariana.github.io/data-uri-to-img-url/ for sharing on facebook.
I just can't work out how to make the post request using jquery:
# Make a POST request with param 'image[data_uri]' set to the above DataURI input.
# This could be from an HTML form with a textarea, or programmatically using an AJAX POST request.
I have setup a JS Fiddle that creates an image in canvas, converts the image to the datauri http://jsfiddle.net/7asutg7c/ it's just the last part of using jsonp in jquery to send the parameter and get the URL back that I am completely lost on.
var url = 'http://data-uri-to-img-url.herokuapp.com/images.json';.
$.ajax({
type: 'POST',
url: url,
async: false,
// data: dataURL,
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json.url);
},
error: function(e) {
console.log(e.message);
}
});
My initial thought was to set data to the dataURI but I get "Failed to load resource: the server responded with a status of 414 (Request-URI Too Large)" ... so I am a little stuck about how I should be sending that dataURI.
Any help would be greatly appreciated.
Create a JavaScript object like this,
var myData = {
image: {
data_uri: your_data_uri_here
}
};
and then pass that as value of the data parameter of the $.ajax call.
I have a form that I need to process before it's submitted. The form has several text and radio inputs, as well as a file one. I'm using jQuery to pass the form data:
$button.on('click', function(e) {
e.preventDefault();
var formData = new FormData($('.js-my-form')[0]);
$.ajax({
type: 'GET',
url: '/get-data',
data: formData,
contentType: false,
processData: false
}).done(function(response) {
// handle response
});
});
Then, in Laravel controller:
$input = Input::all() // <- EMPTY ARRAY
No idea why Input comes empty. Any help appreciated.
Your problem is that you are using a GET to send a request with enctype = multipart/form-data. When you use a native FormData object this is the format that you get by default. You can read how to send the form's data
using the POST method and setting the enctype attribute to application/x-www-form-urlencoded (default);
using the POST method and setting the enctype attribute to text/plain;
using the POST method and setting the enctype attribute to multipart/form-data;
using the GET method (in this case the enctype attribute will be ignored).
So if you set your requesto to a GET the content of your form present in the body of the request will be ignored. The enctype attribute is what tells the server how to process your request. This is why you should use POST.
Note that when you write
contentType: false,
processData: false
you are telling jQuery that do not mess with the data you are passing and leave your native Formdata object untouched. This will cause the enctype to be set automatically.
First i suggest use a type 'POST' to pass your data at your method and second, try serialize the form data
$.ajax({
type: 'POST',
url: '/get-data', /*Route laravel*/
data: formData.serialize(),
contentType: false,
processData: false
}).done(function(response) {
// handle response
});
So, I could not find any resource to confirm this, but it seems FormData won't work with GET type - at least when using jQuery's $.ajax() function.
Changed GET to POST - and the form input is getting to the Laravel controller with no problems.
Not sure I like it, thought, as I'm actually not POSTing anything, but GETting information I need. Anyways, it works.
I am looking to make HTTP POST Request with XML payload.
I have looked at this documentation:
http://api.jquery.com/jquery.post/
Here the parameter data is I believe I should be interested in.
However, it is not entirely very clear to me how do I specify the format of this data parameter. In most of my earlier experience this parameter is application/x-www-form-urlencoded
However, my request has an XML payload.
Any pointers ?
$.post is a shorthand function that covers some common usecases but has some unchangeable defaults. Use the $.ajax method instead. It allows you to set the content type for the request.
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: 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). The W3C
XMLHttpRequest specification dictates that the charset is always
UTF-8; specifying another charset will not force the browser to change
the encoding.
You can post XML data as
$.ajax({
url: ajaxurl,
data: "<test><node1></node1></test>",
type: 'POST',
contentType: "text/xml",
dataType: "text",
success : parse,
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
} });