Send byte[] in ajax - javascript

I need to send data with id,name , and file (PdfBytes) byte[] with ajax to my service.
How can i add my PDF file to var pdf and add it to my ajax.
My code
var PdfBytes;
//Tried to fill PdfBytes with get,didnt work
$.get('http://testservices.xxx/PdfService/MYTest.pdf', function(data)
{
PdfBytes=data;
});
var ConvertHtmlToPdfAndSendEmail = {
"PdfBytes":PdfBytes,
id": id,
"Name": name
};
$.ajax({
type: "POST",
data: JSON.stringify(ConvertHtmlToPdfAndSendEmail),
dataType: 'json',
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload",
contentType: 'application/json; charset=utf-8',
async: true,
cache: false,
success: function (result) {
//my code
},
error: function (req, err) {
//my code
}
})
In the server i get PdfBytes is null
function expect to get byte[] PdfBytes
Sow how i can upload my pdf from my pc to var PdfBytes ,and send it in ajax to my service.

There two way to send byte[] in Ajax
You convert byte[] to string for GET or to json for POST
=> The main thing you should convert to byte array to text
and recover the data format when call the server script
$.ajax({
type: "GET",
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload?data="+encodeURI(byte_array.join())
});
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(byte_array),
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload"
});
Hope it help!

I think you should use option call 'async' so do that:
var PdfBytes = $.ajax({
url: 'http://testservices.xxx/PdfService/MYTest.pdf',
type: 'GET',
async: false
});
var ConvertHtmlToPdfAndSendEmail = {
PdfBytes: PdfBytes,
id: id,
Name: name
};
$.ajax({
type: "POST",
data: JSON.stringify(ConvertHtmlToPdfAndSendEmail),
dataType: 'json',
url: "http://testservices.xxx/ConvertHtmlToPdfAndDownload",
contentType: 'application/json; charset=utf-8',
async: true,
cache: false,
success: function (result) {
//my code
},
error: function (req, err) {
//my code
}
});
Hope it help.

Related

How to send #RequestParam in AJAX POST request

I have my API which accepts Request Param:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(value = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I want to send AJAX POST request.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/ ,
async: false,
data: { "managedObjects": ["Audit","Logs"]},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
//File Handling
}
});
I tried to send managedObjects in URL. In data also I am sending the same.But my API is not working. How to send the #RequestParam from AJAX POST request exactly?
pass a list in Query Param
$.ajax({
...
url: "/export?managedObjects=Audit,Logs" ,
...
});
pass a list in Request Body
$.ajax({
type: "POST",
url: "/export/",
...
data: {managedObjects[0]: "Audit",
managedObjects[1]: "Logs"}
...
});
Try stringifying your data:
var data = {
managedObjects: ["Audit", "Logs"]
}
$.ajax({
type: "POST",
url: "/export/",
async: false,
data: JSON.Stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});
Additionally you should use "name" instead "value" in #RequestParam:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(name = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I think the problem is just with list that you want to send in your request.
var dataToSend = {
list: [{ fieldname: 'ABC' }, { fieldname: 'DEF' }]; // your list should something like this.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/?managedObjects=" + Mos ,
async: false,
data: JSON.stringify(dataToSend),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});

i am trying to pass parameter to data through ajax

I am trying to pass value through an ajax json array but value of catergory variable is not getting in controller action
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
data: {
'category': category
},
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(response) {}
});
You need to use the parameter namespace matching your extension/plugin:
$.ajax({
// ...
data: {
'tx_myext_foo[category]': category,
},
// ...
});
But you'll also need to configure the cHash evaluation since this will lead to a HTTP request like /?tx_myext_foo[category]=X which will fail without a matching cHash.
This can be done with the excludedParameters configuration option.
Please check the Controller action if category (parameter name) passed from the ajax is exactly same in the controller action too
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
async: false,
url: url,
data: JSON.stringify {
category: category
},
dataType: 'json',
success: function(response) {}
});
You need to make ajaxurl with action and controller. and then pass the data in full format.
var ajaxUrl = '<f:uri.action action="youraction" controller="Yourcontroller" />';
var category = $('#category').val();
$.ajax({
type: 'POST',
url: ajaxUrl,
data: '&tx_yourext_yourplugin[category]='+category,
success: function(response) {
},
});
Just make the following changes :
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
url:url,
data: {'category': category},
dataType: "json",
success: function(response) {}
});

How can i solve Ajax Ckeditor value post problem

I am trying to send a CKeditor value post with ajax but i cant response anyway! I cant find anything
function send_days(tourId){
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: dataString,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});
}
but when i chance ajax method like this. It is succesfull
$.post(url, {data:value}, function (response) {
$('.tour_popup_container').html(response);
})
here is my codeigniter php file (it is not important actually)
public function save_days($tourId)
{
$value=$this->input->post("data");
print_r($value);
}
It looks like you used dataString instead of value.
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: value /*dataString*/,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

Is it possible to send entire form including the files to server using jquery/ajax?

Is it possible to submit entire form (all the fields including fileupload) to server (webmethod or handler etc) using Jquery/Ajax? If yes, how?
ASPX:
$.ajax({
type: "POST",
url: "SupplierBidding.aspx/SubmitBid",
data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
span.fadeIn("slow", function () {
span.text(data.d).fadeOut('slow');
});
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
setTimeout(function () {
btn.prop('disabled', false);
}, 3000);
}
});
}
WebMethod:
[WebMethod]
public static string SubmitBid(string id, string bidamt)
{
//code
return "";
}
I would like to replace data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }) with entire form including files also.
You can use Formdata.
FormData Docs
Code example.
var fdata = new FormData();
fdata.append( 'file', input.files[0] );
$.ajax({
url: 'http://yourserver.com/upload.php',
data: fdata,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log('siceess')
}
});
Did you try jQuery Form plugin?
It handles file uploads.
Worked for me before.

Categories

Resources