I'm trying to call a method in Angular but it doesn't work and I don't know why
This is my HTML
<div class="panel-footer text-right">
<input type="button" ng-click="AceptarSolicitudPendiente()" class="btn btn-primary" value="Guardar" />
</div>
and this is my JS
s.AceptarSolicitudPenediente = function () {
var config = {
method: "POST",
url: "CatSolicitud.aspx/GuardarLOG",
data: {
Log: {
IdSolicitud: s.solicitudSeleccionada.Id_Sol,
FechaCompromiso: $("#FechaCompromiso").val(),
Comentario: s.Comentario,
Estatus: "Activo",
Motivo: null
}
}
};
h(config).success(function (data, status, head, conf) {
data = $.parseJSON(data.d);
if (data.success) {
s.closeAceptar();
s.message = data.message;
s.openModal();
s.loadSolicitud();
} else {
s.message = data.message;
s.openModal();
}
}).error(function (data, status, head, conf) {
console.log(data);
});
}
It should work because I have another method to do another action and it works, but not this. I'm tired of search any error or something but no, I can't find anything.
I just found my mistake, I was writting different name Function.
I was calling AceptarSolicitudPendiente() and It was AceptarSolicitudPenediente()
Thank you guys.
Related
So I have a .ASP MVC Web Application project. I want to run a void method from the controller class when I press a button using AJAX. No variable input or output data needed. I just want to create a pdf file and save it on my local machine.
Right now, nothing at all happens when I click the button. I don't think the ajax script works, 0 connection.
This is my Controller method:
[HttpPost]
public void Test()
{
string dok = System.IO.File.ReadAllText("C:\\Users\\axel\\Desktop\\Repo\\Cert\\employee_regular.html");
var Renderer = new IronPdf.HtmlToPdf();
var HtmlTemplate = dok;
var Pdf = Renderer.RenderHtmlAsPdf(HtmlTemplate);
Pdf.SaveAs("C:\\Users\\axel\\Desktop\\Repo\\Cert\\Arbetsgivarintyg_vanlig_heltid.pdf");
}
This is my Index.cshtml file
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12">
<h2>Request employement certificate</h2>
<input type="button" onclick="BtnClick()" value="Click me" />
</div>
</div>
<script>
function BtnClick() {
$ajax({
url: "/Home/Test",
method: "POST",
success: function () {
alert("ok");
},
error: function () {
alert("not ok")
}
})
}
</script>
Really happy for any help
Well there can be several reasons why your code is not working.
First Make sure you are actually able to make a call to a function, Just simply add simple alert message before calling the ajax and see if the alert triggers.
The second thing is to validate url replace the hardcoded url and add url using URL helper.
I would recommend you to make a function as JsonResult Instead of Void, because an exception can happen when creating pdf. [This change is optional but I do recommend it]
So after all the changes your code would look something like this
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12">
<h2>Request employement certificate</h2>
<input type="button" onclick="BtnClick()" value="Click me" />
</div>
</div>
<script>
function BtnClick() {
$ajax({
alert("Funciton is working"); // change confirm function is working
url: "#Url.Action("Test","Home")", // change using Url Helper to create valid URL
method: "POST",
success: function (data) {
if (data == true)
{
alert("pdf created sucessfully ok");
}
else
{
alert("exception happend when creating pdf not ok");
}
},
error: function () {
alert("not ok")
}
})
}
</script>
Your Back End would look something like this
[HttpPost]
public JsonResult Test()
{
try {
string dok = System.IO.File.ReadAllText("C:\\Users\\axel\\Desktop\\Repo\\Cert\\employee_regular.html");
var Renderer = new IronPdf.HtmlToPdf();
var HtmlTemplate = dok;
var Pdf = Renderer.RenderHtmlAsPdf(HtmlTemplate);
Pdf.SaveAs("C:\\Users\\axel\\Desktop\\Repo\\Cert\\Arbetsgivarintyg_vanlig_heltid.pdf");
return Json(true, JsonRequestBehavior.AllowGet);
}
catch(Exception ex) {
return Json(false, JsonRequestBehavior.AllowGet);
}
}
So I'm working on some demoware and I have two AJAX calls, the first is just a last modified date, to let me know whether to fetch data from the second. This works, but I feel like there's a smarter way to do this for real applications, and I'm just a UI monkey trying to come up in the world, any advice is much appreciated.
componentDidMount() {
this.getJson();
setInterval(this.getJson.bind(this), 1000);
}
getJson() {
const el = this;
const isModified = (date) => {
let mod = false;
if (this.state.lastModified == date) {
console.log('no change');
} else {
mod = true;
console.log({
'previously modified': this.state.lastModified,
'newly modified': date
});
el.setState({lastModified: date});
}
return mod;
}
this.serverRequest = $.ajax({
url: 'URL_LAST_MODIFIED',
success: function(result) {
const lastModified = $.parseJSON(result).LastModifiedDateTime;
if (isModified(lastModified)) {
$.ajax({
url: 'URL_DATA',
success: function(result2) {
const result2Obj = $.parseJSON(result2);
el.setState({data: result2Obj});
},
error: function(xhr, status, err) {
alert(err.toString());
}
})
}
},
error: function(xhr, status, err) {
}
});
}
I think it is realted to this:
https://github.com/reactjs/redux/issues/1676
The idea is create a action for the first ajax call... and on success dispatch another action to execute the second call.
I have this on my html page
<div class="form-group col-xs-7 col-lg-6">
<label>Background image</label>
<input type="file" name="background_image" id="background_image" ng-model="selectedLayout.background_image" class="form-control" />
<button class="btn btn-primary" ng-click="save(selectedLayout)">Change background image</button>
</div>
This is what I have in controller
$scope.save = function (selectedLayout) {
$http({
method: 'POST',
url: 'api/LayoutSettings/PostImage',
data: selectedLayout.background_image,
headers: {
'Content-Type':'image/jpeg'
}
});
};
And this is my method in the api controller named LayoutSettings
public async Task<HttpResponseMessage> PostImage()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
I don't know why when i actual press the change background image I send an empty object. Someone have some idea how i can actual pass the image there? Thanks.
ng-model is not supported by input[file] type, there is a note in the Angular docs about it:
Note: Not every feature offered is available for all input types.
Specifically, data binding and event handling via ng-model is
unsupported for input[file].
Try this instead.
I am newbie to angularjs. I succeeded in making the fileuploader work and displaying the files uploaded. Now I want to remove the files which I do not want.
Here is how my upload and display works.
html file
<div class="container-fluid">
<error-display error-display-api="errorDisplayApi"></error-display>
<div ng-controller="complianceItemDocumentcontroller">
<div class="form-inline">
<span class="btn btn-default">
Add Photo
<input ng-model="file"
onchange="angular.element(this).scope().file_changed(this)"
type="file" accept="image/*">
</span>
<button ng-click="removeFile()">Delete Photo</button>
</div>
<div ng-repeat="images in document">
<label name ="desscription" ng-bind ="images.Description"></label><br>
</div>
</div>
</div>
javascript file
app.controller('complianceItemDocumentcontroller', ['$scope', '$http', function ($scope, $http)
{
var url = "http://localhost:/....";
$http.get(url)
.success(function (data, status, headers, config)
{
$scope.document = data;
})
.error(function (data, status, headers, config)
{
$scope.document = undefined;
});
$scope.removeFile = function()
{
alert("delete");
};
$scope.file_changed = function(element)
{
$scope.$apply(function (scope)
{
var fd = new FormData();
fd.append('file', element.files[0]);
var urlpost = "http/.....";
var req = { method: 'POST', url: urlpost, headers: { 'Content- Type': undefined }, data: fd}
$http(req)
.success(function (data, status, headers, config)
{
alert("uploaded");
})
.error(function (data, status, headers, config)
{
alert("fail");
});
});
}
}]);
I should be able to select the images in the list and based on the selection of the file I should be able to call the related API to remove the document using the document ID.
I am unable to figure out how to select a file and upon selected get the document ID. Then I will call the method through httppost and that will be deleting the file in the database. Also I should be able to display the images available as thumbnails. Currently it is just a plain list of names of files.
Thank you for your time and suggestions.
I have a jqgrid with some data. When two of the rows are selected, I'd like to add a record in the database (in a different table than the one of the jqgrid). What I do is to create a new button in the navigation bar with the following code:
jQuery("#tabla").navButtonAdd('#navegacion',
{
caption: "Crear tramo", buttonicon: "ui-icon-extlink", cursor:"pointer", title: "Crear tramo",
onClickButton: $(function() {
var selectedrows = $("#tabla").jqGrid('getGridParam','selarrrow');
var er1=$("#tabla").jqGrid('getRowData',selectedrows[0]);
var er2=$("#tabla").jqGrid('getRowData',selectedrows[1]);
$.ajax({
dataType: 'json',
mtype: 'POST',
url: 'json/operaciones.jsp',
postData: { oper:'add', id1:er1, id2:er2},
success: function(data) {
alert(data);
}
})
})
});
And what I have in the file operaciones.jsp is:
<%
String salida="";
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("my", "Connection", "Parameters");
try {
System.out.println("ParĂ¡metros enviados:");
Enumeration e=request.getParameterNames();
while (e.hasMoreElements()){
String par=(String)e.nextElement();
System.out.println(par+":"+request.getParameter(par));
}
String operacion=request.getParameter("oper");
String id1=request.getParameter("id2");
String id2=request.getParameter("id2");
String comentarios="prueba";
if (operacion.equals("add")) {
PreparedStatement stmt=con.prepareStatement(
"INSERT INTO TRAMOS "+
"(COMENTARIOS,ELEMENTOS_REGISTROCODIGO,ELEMENTOS_REGISTROCODIGO2, ENTIDADESCIF) "+
"VALUES (?,?,?,?,?)");
stmt.setString(1,comentarios);
stmt.setString(2,id1);
stmt.setString(3,id2);
stmt.setString(4,"Q1818002F");
stmt.executeUpdate();
stmt.close();
salida="{\"correcto\":true,\"clave\":\""+id1+"|"+id2+"\",\"mensaje\":\"OK\"}";
}
}
catch (Exception e) {
String cadenaError=e.toString().substring(e.toString().indexOf(":")+2);
cadenaError=cadenaError.replace('\n',' ');
cadenaError=cadenaError.replace("\"","\\\"");
salida="{\"correcto\":false,\"clave\":\"\",\"mensaje\":\""+e.toString()+"\"}";
}
finally {
con.close();
}
System.out.println("salida:"+salida);
response.setContentType("application/json");
%>
<%=salida%>
But it's not working, what I get is "java.lang.NullPointerException". Where is the mistake? How can I send the data to the file operaciones.jsp?
Thanks in advanced,
Natalia
One clear error in the code which you use is the usage of postData instead of data and mtype instead of type as parameters of jQuery.ajax.
I recommend you additionally to write more safe code. For example you use selectedrows[0] and selectedrows[1] inside of the onClickButton before verifying that selectedrows is not null and that selectedrows.length > 1. If the user click for example on the button before at least two lines are selected one get exception in JavaScript code.
It was a stupid error... What finally worked:
jQuery("#tabla").navButtonAdd('#navegacion',
{
caption: "Crear tramo", buttonicon: "ui-icon-extlink", cursor:"pointer", title: "Crear tramo",
onClickButton: function() {
selectedrows = $("#tabla").jqGrid('getGridParam','selarrrow');
if(selectedrows.length==2){
er1=$("#tabla").jqGrid('getRowData',selectedrows[0]);
er2=$("#tabla").jqGrid('getRowData',selectedrows[1]);
$.ajax({
datatype:'json',
type:'GET',
url:'json/operacionesTramos.jsp',
data:{oper:'add',id1:er1.codigo,id2:er2.codigo},
success: function(data) {
alert("Tramo creado");
}
})
}
else{
alert("Seleccione dos arquetas, por favor");
}
}
});
Thanks Oleg!