Javascript, Ajax : Bad Request 400 - javascript

I'm working on ASP Net Core Project and I'm trying to send to my controller with JQuery Ajax function from a partial view modal, parameters.
The recovered URL is correct for example : http://localhost:44321/Validations/ValidationRefuse?ficheId=24&commentaire=Commentaire%20de%20test
But it's always :
Failed to load resource: the server responded with a status of 400 (Bad Request)
My Javascript :
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse?ficheId=" + ficheId + "&commentaire" + commentaire,
type: 'POST',
contentType: 'application/html',
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
My C# method :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ValidationRefuse(int ficheId, string commentaire)
{ ... }
My Partial View :
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Validez-vous cette fiche ?</h5>
<button type="button" class="btn btn-outline-dark btn-circle" data-dismiss="modal" aria-label="Close">
<i class="fa fa-close"></i>
</button>
</div>
<form asp-controller="Validations" asp-action="ValidationParResponsable" asp-route-id="#Model.FicheId" asp-route-eId="#Model.EnseignantId">
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="ficheId" asp-for="FicheId" />
<input type="hidden" asp-for="EnseignantId" />
<input type="hidden" asp-for="EtatId" />
<label class="control-label font-weight-bold">Commentaire :</label>
<textarea class="form-control" id="inputCommentaire" asp-for="Commentaire" placeholder="Votre commentaire"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="buttonRefusFiche">Refuser</button>
<button type="submit" class="btn btn-success">Valider</button>
</div>
</form>
I hope it's understandable, thanks for your responses. :)

When you use a POST request you have to send the parameters in the body of the request, not in the URL like that :
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse",
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType : "html",
data : {
ficheId : ficheId,
commentaire : commentaire
},
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
I also changed the contentType and added dataType.
For more information about ajax Post see documentation

Related

Why my ajax post is not working codeigniter? The page is refreshing

// save new employee record
$('#saveEmpForm').submit('click',function(){
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
});
<form id="saveEmpForm" method="post">
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-2 col-form-label">Jenis</label>
<div class="col-md-10">
<input type="text" name="jenis" id="jenis" class="form-control" required>
<input type="hidden" id="input_id" name="input_id" class="form-control " value="{$input_id}">
</div>
</div>
<div class="form-group row">
<label class="col-md-2 col-form-label">Jarak</label>
<div class="col-md-10">
<input type="text" name="jarak" id="jarak" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
Save function in controller file
public function save(){
$data=$this->inputs_model->saveEmp();
echo json_encode($data);
}
Save function in Model
public function saveEmp(){
$data = array(
'input_id' => $this->input->post('input_id'),
'jenis' => $this->input->post('jenis'),
'jarak' => $this->input->post('jarak'),
'created_at' => date("Y-m-d h:i:sa"),
'updated_at' => date("Y-m-d h:i:sa")
);
$result=$this->db->insert('input_jenis_industri',$data);
return $result;
}
The code are as stated above, my ajax function to save the data is not working. It is not saving the data in the db. What can cause the problem?
My ajax function calls the InputPembangunan/save to save the data, then the controller try to the save data using the save() function. It is saved using the model saveEmp()
The following is incorrect, there is no click involved in a submit event
$('#saveEmpForm').submit('click',function(){
Change to
$('#saveEmpForm').submit(function(event){
event.preventDefault()// prevent normal form submit
without refreshing the page you have to call event.preventDefault() method after submit event.
replace this
$('#saveEmpForm').submit('click',function(){
with
$('#saveEmpForm').on('submit',function(){
event.preventDefault()
Change this
<button type="submit" class="btn btn-primary">Save</button>
to
<button type="button" class="btn btn-primary">Save</button>
You can onlick() method. Actually I used like this;
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="save()" class="btn btn-primary">Save</button>
</div>
than add jquery
function save() {
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
URL: "<?php echo site_url('InputPembangunan/save')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data) {
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else {
//do something
}
},
error: function(jqXHR, textStatus, errorThrown) {
//do error form
}
});}
Use the following way,
$( "#saveEmpForm" ).submit(function( event ) {
event.preventDefault();
/** Your Existing Code ***/
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
/** Your Existing Code ***/
});
Also, you can check the jQuery reference from this link:
https://api.jquery.com/submit/#submit
Replace
$('#saveEmpForm').submit('click',function(){
with
$(document).off('submit','#saveEmpForm').on('submit','#saveEmpForm',function(event) {
event.preventDefault(); //to prevent default submit action
...rest of the code
})
also check for any errors on the browser dev tool

Sending data using ajax to the controller in rails

I am new to JS and rails so recently facing lots of difficulties about using ajax in rails environment. I will very appreciate if you contribute to developing my project. What I am trying to do is that Once a user selects data from the modal, I want to send the selected data to an action in the controller so that I can handle the data. I am not really sure where I can start with that. Please help guys :( Thanks a lot
view:
<form id= "selected_form" action="" method="">
<div id= "selected_form">
<p id="checkids"></p>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Select Task</h4>
</div>
<div class="modal-body">
<fieldset>
<% #tasks.each do |task|%>
<div>
<label><input type="checkbox" value="<%=task.id%>" name="selected"><%=task.title%></label>
</div>
<% end %>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" id="save" class="btn btn-default" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
JS
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/users/<%= current_user.id %>/test", // route of your rails action
data: {checked_items: checkedItem.join(", ")}, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){}
})
});
});
});
</script>
Please check script below
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/things", // route of your rails action
data: {checked_items: checkedItem }, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){...}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){...}
})
});
});
});
</script>
For simplicity you can inject rails path to that controller as dataset attribute.
for e.g
<form method="post" data-url="<%= tasks_path %>">
and in js part
$('#save').on('click', function (e) {
e.preventDefault();
$.ajax({
type: $(this).method || "GET",
url: this.dataset.url,
data: $(this).serialize(),
success: function (response) {
console.log(response)
},
error: function (error) {
console.log(error);
}
});
});

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Insert data using bootstrap modal in datatables library

I want to insert data with the help of bootstrap modal. But I've got an error on the action index. So the button I've added couldn't run. Did I make any wrong thing in coding?
Controller
function user_action(){
if ($_POST['action'] == "Tambah"){
$data=array(
'kodebayar' => $this->input->post('kodebayar'),
'nama' => $this->input->post('nama'),
'harga' => $this->input->post('harga')
);
$this->bpem_m->create($data);
}
}
View Of Modal
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" name="action" value="Tambah"/>
</div>
</div>
</form>
</div>
</div>
JS
$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method: "POST",
data: postData,
contentType: false,
processData: false,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
You can use serialize()
var datastring = $("#form_pem").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
return type is json
EDIT: I use event.preventDefault to prevent the browser getting submitted in such scenarios.

Pass IEnumerable<HttpPostedFileBase> to Webservice

I have found a few things that are similar but now quite showing how to do it.. and I'm having problems adopting what I've found to my situation. I'm trying to pass multiple images and text to a webservice to then save to db/amazon.
This is what I have so far...
The Form
<form class="create-status" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-12">
#Html.TextAreaFor(model => model.status, new { cols = "1", rows = "1", #class = "form-control no-max-width input-sm", id = "tbStatus", placeholder = "Beep Here", req = "tbStatus" })
</div>
</div>
<div class="row collapse" id="divStatusInputs">
<br />
<div class="col-sm-6">
<div class="row">
<div class="col-sm-3">
<a class="icon"><span id="spanImageInput" class="glyphicon glyphicon-camera glyphicon-camera-input icon"></span></a>
<input id="imageInput" multiple type="file" class="hidden" name="files" />
</div>
</div>
</div>
<div class="col-sm-6 text-right">
<div class="text-right">
<button id="btnCancel" class="btn btn-default" type="button">Cancel</button>
<a id="aSubmitStatus" class="btn btn-primary">Submit</a>
<input id="btnSubmitStatus" type="submit" class="btn hidden" />
</div>
</div>
</div>
</form>
And the jQuery/Javascript..
function CreateStatus() {
var status = $('#tbStatus').val();
var formData = new FormData();
var data = {
files: "", //this is where i'm having the issue? I'm not sure what to do here.
status: status
}
$.ajax({
type: 'POST',
url: '/Webservices/StatusWebService.asmx/CreateStatus',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
console.log(result.d);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
And the webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public async Task<string> CreateStatus(string status, IEnumerable<HttpPostedFileBase> files)
{
//everything here needed to save to db/amazon s3
}
If I remove the HttpPostedFileBase and associated code, I'm able to call the webservice just fine, just having issues passing the proper files/images to the webservice.
Any help is greatly appreciated!!

Categories

Resources