I have an ajax call that is falling into error block before even running the controller.
The strange thing is that sometimes(after multiple requests) it does run succesfully but it does not save the cookies in the controller.
I think it could be the ajax call or some permission error.
AJAX CALL:
$('#loginAWGPE').on('click', function () {
var cpfLogin = $('#cpfValidacao').val().replace(/[^\d]+/g, '');
console.log(cpfLogin);
console.log(urlOrigem + appPath + "Login/validaCPF");
$.ajax({
type: 'POST',
url: urlOrigem + appPath + "Login/validaCPF",
datatype: String,
data: {
cpf: cpfLogin
},
success: function (teste) {
console.log('dataS: ' + teste);
if (teste = true) {
window.location = urlOrigem + appPath + "ProjetoEletrico/Index";
} else {
alert('CPF não cadastrado na Agência Virtual!');
}
},
error: function (teste2) {
console.log('dataE: ' + teste2);
alert('Erro na execusão');
}
});
});
-------CONTROLLER:
public JsonResult validaCPF(String cpf)
{
if (String.IsNullOrEmpty(cpf))
{
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json(false);
}
WebAPIPArameter id = new WebAPIPArameter();
id.ParameterName = "id";
id.ParameterValue = cpf;
List<WebAPIPArameter> list = new List<WebAPIPArameter>();
list.Add(id);
Usuario userInfo = (Usuario)apiClientSistema.GetItem<Usuario>(serviceNameUserInfo, list);
if (userInfo == null)
{
return Json(false);
}
else
{
CultureInfo cult = new CultureInfo("pt-BR");
String dataStr = userInfo.DTH_ULTIMO_ACESSO.ToString("dd/MM/yyyy HH:mm:ss", cult);
HttpCookie cook = new HttpCookie("UserInfo");
cook["cpfCnpj"] = userInfo.NUM_CPF_CNPJ_CLIENTE.ToString();
cook["nomeCompleto"] = userInfo.NOM_CLIENTE;
cook["dataAcesso"] = dataStr;
cook["email"] = userInfo.END_EMAIL;
cook.Expires = DateTime.Now.AddHours(4);
Response.Cookies.Add(cook);
//cookie de autenticacao
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
cpf, // Id do usuário é muito importante
DateTime.Now,
DateTime.Now.AddHours(4),
true, // Se você deixar true, o cookie ficará no PC do usuário
"");
HttpCookie cookieAuth = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookieAuth);
}
Response.Redirect("~/ProjetoEletrico/Index");
return Json(true);
}
I figure it out. It was a stupid mistake....
I forgot the "submit" in my form button and I also the ajax call.
Related
I had a file download with ajax call and window.location. Ajax call is only needed to show a gif and then I use window.location to get the output and download the file.
Now this file was splitted in two and I need with the same button, donwload both files.
I thought that writting both files through the outputStream will do the task, but no.
Function in my controller:
#RequestMapping(value = "descargaSupervisors")
#ResponseBody
public final String descargaSupervisors(HttpServletResponse response) throws IOException, ParseException {
// Crida query BDD per generar supervisors
String missatgeBDD = blueSupervisorsService.carregarBlueSupervisorsBlue();
if (missatgeBDD.toLowerCase().equals("ok")) {
OutputStream out = response.getOutputStream();
byte[] processedFile = getSupervisorsEstudi();
downloadFile(response,out, processedFile, Constants.BLUE_SUPERVISORS_ESTUDIS + ".csv");
processedFile = getSupervisorsDepartament();
downloadFile(response,out, processedFile, Constants.BLUE_SUPERVISORS_DEPART + ".csv");
} else {
mailService.enviaCorreuFailedGenerarBlue(missatgeBDD);
}
return Constants.RESPOSTA_OK;
}
private void downloadFile(HttpServletResponse response,OutputStream out, byte[] processedFile, String filename) {
JSONObject output;
try {
output = new JSONObject(new String(processedFile, StandardCharsets.UTF_8));
JSONArray docs = output.getJSONArray("data");
// Generem dos arxius per passar les dades no formatades al format correcte
File file = new File("temp/" + "temp_csv.csv");
File file2 = new File("temp/" + "temp.csv");
jsonToCsv(docs, file, file2);
if (file.delete()) {
log.info("Arxiu eliminat correctament");
}
// Configurem el tipus de resposta que volem al fer la descarrega
response.setHeader("Content-Encoding", "UTF-8");
response.setContentType("text/csv; charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
// response.setHeader("Cache-Control", "no-cache");
// response.setHeader("Expires", "0");
// response.setHeader("Pragma", "no-cache");
response.setContentLength((int) file2.length());
// Descarrega del fitxer
InputStream input = new BufferedInputStream(new FileInputStream(file2.getAbsolutePath()));
FileCopyUtils.copy(input, out); // IOUtils from Apache Commons-IO
response.flushBuffer();
input.close();
if (file2.delete()) {
log.info("Arxiu eliminat correctament");
}
} catch (Exception e) {
e.printStackTrace();
}
}
JAVASCRIPT
function descargaSupervisors() {
var url = "/9avaldoval/administracio/descargaSupervisors";
$.ajax({
url: url,
success: function() { //return the download link
window.location.href = url;
},
beforeSend: function() {
$("#modal").show();
},
complete: function() {
$("#modal").hide();
},
});
}
I'm using the following code to upload multiple documents to the server.
var docFileUploader = new sap.ui.unified.FileUploader({
name : fileUploaderName,
uploadOnChange: false,
uploadUrl: uploadUrlStr,
multiple:true,
additionaldata : nodeObjId ,
fileSizeExceed: function (oEvent) {
var sName = oEvent.getParameter("fileName");
var fSize = oEvent.getParameter("fileSize");
var fLimit = oFileUploader.getMaximumFileSize();
Messenger().post({
message: "File: " + sName + " is of size " + fSize + " MB which exceeds the file size limit of " + fLimit + " MB.",
type: 'error',
showCloseButton: true
});
},
uploadComplete: function (oEvent) {
var sResponse = oEvent.getParameter("response");
console.log(sResponse);
var thisDlg = this.getParent().getParent().getParent().getParent();
console.log(thisDlg);
if (sResponse) {
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
uploadSuccess = true;
thisDlg.setBusy(false);
console.log("The document has been uploaded successfully");
setTimeout(function() { Messenger().post("The document has been uploaded successfully");}, 100);
}
else {
thisDlg.setBusy(false);
setTimeout(function() { Messenger().post({
message: 'Oops! Error in document upload. <br>Please try again or contact your administrator.',
type: 'error',
showCloseButton: true
});},100);
}
}
thisDlg.setBusy(false);
console.log("The document has been uploaded successfully");
setTimeout(function() { Messenger().post("The document has been uploaded successfully");}, 100);
thisDlg.close();
thisDlg.destroy();
setTimeout(function() { reloadPage(attrGrpName); }, 100);
}
});
The controller part is as below:
#RequestMapping(value = "doc/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public #ResponseBody String uploadDoc(#RequestParam("uploadDoc-data") ObjectId nodeId,
#RequestParam(value = "uploadDoc", required = true) MultipartFile[] files, #RequestParam String userId, #RequestParam String passwd) {
if (files != null) {
return service.uploadDoc(nodeId, files[0], userId, passwd);
} else
return "No files found to upload";
}
Even if I use files[0] gives me an ArrayIndexOutofBound 0 Exception. It means the MultipartFile[] is returning an empty array only. I was able to upload one file without multiple attributes. The problem arises if I set the multiple attributes to 'true'. What am I missing? Please help me.
I'm using jquery-bitly-plugin for shorten some URLs and I'm doing in this way:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
shorten = bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine
// I got something like http://bit.ly/1DfLzsF
return shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
Then I tried this:
console.log(shorten);
But got Undefined, why? How do I assign the var in order to use in other places?
EDIT: adding extra information around the problem
This info will clarify a bit what I'm trying to do with my question so I have this code which allow to share some content in social networks on click event:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0];
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + url;
}
else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + url;
}
else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
return false;
}
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
});
As you may notice url is common to share-facebook and share-twitter. I need to shorten that URL and pass back to the href on each possible choice. For shorten the URL I'm using jquery-bitly-plugin as follow:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine I got
// something like http://bit.ly/1DfLzsF
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
How I can use shortUrl in href parameter? Do I need to repeat the code on each condition in order to use execute the action at onSuccess event from shorten() method? How do you deal with this?
To assign to a variable:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
shorten = shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
The method shorten doesn't have a return on source code of plugin.
IMPROVED ANSWER
Based on your edite post, this is the correct answer on how to use it the shortUrl:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0],
opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + shortUrl;
} else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + shortUrl;
} else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
}
if ($(this).data('category') != 'share-mail')
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
return false;
});
As I said in a comment, you need to figure out a future for the shortened URL. This future here is "open a window with this URL". Here is a quick pseudocode:
function openWindow(shortUrl) {
window.open(shortUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}
$('.share-item').click(function () {
if ($(this).data('category') == 'share-mail') {
...
return;
}
if (....twitter...) {
href = ...
} else if (....facebook....) {
href = ...
}
bitly.shorten(url, {
onSuccess: openWindow,
onError: function(err) {
...
}
});
}
(I made the openWindow future into a separate function to make it obvious, but it could just as well have been left inline.)
I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);
so for pagination I have this url that when a user press the link it goes to the next page (the link parts are in a partial view), for that to work i get the dropdowbox value with javascript and pass to the url
#Html.ActionLink("|Siguiente >", "Index", new { pagina = Model.PageNumber + 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro , empresa = "param-empresa" }, new { id = "mylinkSig" })
<script type="text/javascript">
$(function () {
$('#mylinkSig').click(function () {
var empresa = $("#empresa").val();
this.href = this.href.replace("param-empresa", encodeURIComponent(empresa));
});
});
</script>
as I use the script in almost all my page i want to put this script in a js file so i dont have to write it in all my view (pages) y try to copy/paste and put in a js file and it dont work (yes i have the .js file refence in my page)
so iam new to javascript so i dont know if i have to change the function for it could work in the .js file an use it in all my page
edit:
my Helper.js
$(function () {
$('#mylinkSig').click(function () {
var empresa = $("#empresa").val();
this.href = this.href.replace("param-empresa", encodeURIComponent(empresa));
});
});
function deleteConfirmation(response, status, data) {
// remove the row from the table
var rowId = "#widget-id-" + response.id;
$('.widgets').find(rowId).remove();
// display a status message with highlight
$('#actionMessage').text(response.message);
$('#actionMessage').effect("highlight", {}, 3000);
if (response.message == null) {
alert('No se pudo eliminar el registro');
}
else {
alert(response.message);
}
}
my view
<script src="#Url.Content("~/Scripts/Helper.js")" type="text/javascript"></script>
#*navigation << < >>>*#
<div>
Pagina #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
de #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<|", "Index", new { pagina = 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro, empresa = "param-empresa" }, new { id = "mylinkFirst" })
#Html.Raw(" ");
#Html.ActionLink("< Anterior|", "Index", new { pagina = Model.PageNumber - 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro, empresa = "param-empresa" }, new { id = "mylinkAnt" })
}
#if (Model.HasNextPage)
{
#Html.ActionLink("|Siguiente >", "Index", new { pagina = Model.PageNumber + 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro , empresa = "param-empresa" }, new { id = "mylinkSig" })
#Html.Raw(" ");
#Html.ActionLink("|>>", "Index", new { pagina = Model.PageCount, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro , empresa = "param-empresa"}, new { id = "mylinkLast" })
}
</div>
If you have a reference to the file, then my best guess is that you are copying the script-tag into the JS-file as well, which you shouldn't.
Try just copying this part:
$(function () {
$('#mylinkSig').click(function () {
var empresa = $("#empresa").val();
this.href = this.href.replace("param-empresa", encodeURIComponent(empresa));
});
});
If you do that, there shouldn't be a difference between having the code within the page, compared to having it in a separate file.