I need help with my ajax function. I have a form that submits data with the same input name
When I run my code without javascript, I can insert multiple input data with the same name,
Submitted structure
{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}
When I implement javascript, a concatenated string is sent to the controller and this makes the service_name inaccessible.
formdata:"_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"
My javascript function
jQuery("form.ajax").on("submit", function (e) {
e.preventDefault();
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: $(".ajax#servicesForm").serialize()
},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function (jqXHR, exception) {
var msg = "";
if (jqXHR.status === 0) {
msg = "Not connect.\n Verify Network.";
} else if (jqXHR.status === 404) {
msg = "Requested page not found. [404]";
} else if (jqXHR.status === 500) {
msg = "Internal Server Error [500].";
} else if (exception === "parsererror") {
msg = "function Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error.";
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Uncaught Error.\n" + jqXHR.responseText;
}
}
});
});
My PHP Controller Function
public function insert(Request $request)
{
return response()->json($request);
}
use FormData Object, to send fromdata
fd = new FormData();
fd.append("input-name", value1);
fd.append("input-name2", value2 OR arry of value);
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: fd
}
I found a workaround:
First, I created an array, and pushed all instances of input[name='service_name[]'] into the array.
Then I passed the data with ajax and was able to insert the data.
var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
serviceArray.push($(obj).val());
});
My ajax script then:
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: 'post',
data: {
'service_name': serviceArray,
'id': id
},
dataType: 'JSON',
success: function(response) {
console.log(response);
}
});
Related
Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}
I am learning C# and jQuery AJAX. I'm currently having a problem where I cannot get Ajax to run correctly and I am not sure why.
Here is the error log:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is my code:
HTML
<button class="btn btn-primary btn-edit" id="{{SubjectId}}" id1="
{{StudentId}}" >Edit</button>
JavaScript AJAX code:
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!")
}
},
Error: function (err) {
console.log(err);
}
});
},
And ExamsController
[HttpGet]
public JsonResult LoadDetail(int id, int id1)
{
bool status = false;
Exam exam = new Exam();
exam = db.Exams.Find(id, id1);
status = true;
return Json(new
{
data = exam,
status = status
}, JsonRequestBehavior.AllowGet);
}
Internal server error means you have error in C# script, please double check error logs.
And also your code isnt cleanest, missing semi-colons.
Try add semi-colons, add name to function , and check error log, it can be useful, we can make better answer.
Maybe try this code with semi colon :) :
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!");
}
},
Error: function (err) {
console.log(err);
}
});
},
Thanks!
I am developing a code to check whether a data already exist on the server or not. If there is a conflict, then the program must return status code 409. I can get the data returned by the webmethod via ajax.success. However, I cannot get the data via ajax.statusCode. It always returns error:
TypeError: data is undefined
I have tried this but I got an error
Non-invocable member "Content" cannot be used like a method
How do I get my object via ajax.statusCode?
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Case CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
HttpContext.Current.Response.StatusCode = 409;
return caseResponse;
}
else
{
HttpContext.Current.Response.StatusCode = 200;
return caseResponse;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.StatusCode = 500;
return null;
}
}
JS:
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
statusCode: {
409: function (data, response) {
//how do I get the "data" from WebMethod here?
loadCase(ID, data);
//TypeError: data is undefined
}
},
success: function (data, status) {
loadCase(ID, data);
},
error: function (data) {
}
});
}
You can do like this. Use Web API instead of Web method and return HttpResponseMessage instead of case
public HttpResponseMessage CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
return Request.CreateResponse( HttpStatusCode.Conflict, caseResponse );
}
else
{
return Request.CreateResponse( HttpStatusCode.OK, caseResponse );
}
}
catch (Exception ex)
{
return Request.CreateResponse( HttpStatusCode.InternalServerError, null);
}
}
If you want to use the web method approach then change the ajax and try to parse the error in errro function as given below
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
loadCase(ID, data);
},
error: function (jqXHR, textStatus, thrownError) {
if(jqXHR.status =="409" ){
var data= jqXHR.responseJSON;
loadCase(ID, data);
}
else
{
console.log(textStatus);
}
}
});
}
enter code hereI have read several answers about this question, but no one works.
I have the following code but my HttpPostedFileBase[] array is always null.
The Other parameters has the right value, but the HttpPostedFileBase[] is always null.
What am i missing??
$('#myFile').on('change', function (e) {
var fileName = e.target.files[0].name;
archivosProcesar = new FormData();
for (var i = 0; i <= e.target.files.length -1; i++) {
archivosProcesar.append(i, e.target.files[i]);
}
});
function aplicarFragmentacion() {
var ids = obtenerAfiliadosSeleccionados();
var data = {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
archivos: archivosProcesar
}
if (!validarProcentajes() & !validarSeleccionados(ids)) {
$.ajax({
data: data,
url: urlAplicarFrag,
type: 'POST',
processData: false,
beforeSend: function () {
//$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
}
}
Controller.cs
public async Task<ActionResult> AplicarFragmentacion(decimal fragmento1, decimal fragmento2, string[] segment\
os, HttpPostedFileBase[] archivos)
{
List<Credito> lstSegmentos = new List<Credito>();
try
{
ProgressHub.SendMessage("Iniciando proceso de fragmentación...", 10);
lstSegmentos = await FragmentacionNegocio.AplicarFragmentacion(fragmento1, fragmento2, segmentos)\
;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return Json(lstSegmentos, JsonRequestBehavior.AllowGet);
}
Try submitting a FormData object, not an anonymous object with a FormData field. Also it is my understanding that the contentType should be set to false.
var formData = new FormData();
formData.append('fragmento1', parseInt($('#fragmento1').val());
formData.append('fragmento2', parseInt($('#fragmento2').val());
formData.append('segmentos', obtenerAfiliadosSeleccionados());
formData.append('archivos', $('#fileupload')[0].files[0]);
$.ajax({
type: 'POST',
data: formData,
url: urlAplicarFrag,
type: 'POST',
processData: false,
contentType: false,
[...]
});
The fix was to use this plug in
https://jquery-form.github.io/form/
In this way
$(this).ajaxSubmit({
url: urlAplicarFrag,
data: {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
fechaReenvio: $('#fecha-reenvio').val()
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
check the plugin website
here is my web method
[HttpGet]
public ActionResult EditEmp(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee Emp = db.Employees.Find(id);
if (Emp == null)
{
return HttpNotFound();
}
ViewBag.dept_id = new SelectList(db.Departments, "dept_id", "dept_name", Emp.dept_id);
return PartialView("_EditEmp", Emp);
}
and here is the ajax call
$.ajax({
type: "GET",
url: '/Employee/EditEmp',
data: { id: idp },
dataType: "json",
success: function (result) {
alert(result);
$('#editid').html(result);
},
error: function (result) {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
});
it gives me result.status =200 and result.statusText = OK but it fire Error Event
Please check that you are returning valid json or not, because you are setting
dataType: "json"
it evaluates the response as JSON and returns a JavaScript object. (...) The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
You may want to see this