I have the following code snippet here. I am trying to refresh the page with /Events/Index page when the Ajax request is successful. However, inside the success method, I see that the response variable is available in else if case, but it is not available in the if case. Inside if case, I get an error: The name response does not exist in the current context.
The Ajax call from the View is as follows:
$.ajax({ url: "/Events/DeleteEvent", data:data, async: true }).success(function (response) {
if (response != "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
window.location.href = '#Url.Action("Index", "Events", new { EventId = response })';
}
else if (response == "Event not found")
swal("Cancelled!!!", "Error : " + response, "error");
});
This is how I am sending the response to the success part of the Ajax call from the Controller:
if (eventid > 0)
{
...
return Json(id);
}
else
return Json("Event not found");
// id is an integer value that I want to send to success in Ajax.
Am I going wrong anywhere?
The response is a client-side variable which contains AJAX response, hence you cannot use it as routeValues parameter value inside #Url.Action() helper which contains server-side code because the script doesn't executed yet while action URL is generated, and response variable doesn't declared yet in server-side code.
To fix the issue, try using plain query string to insert EventId parameter:
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
// use query string because Url.Action helper runs server-side
window.location.href = '#Url.Action("Index", "Events")' + '?EventId=' + response;
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
Or use a placeholder from server-side and then change parameter value to response with replace():
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
// the URL generated server-side with placeholder
var targetUrl = '#Url.Action("Index", "Events", new { EventId = "xxx" })';
// replace placeholder with event ID
window.location.href = targetUrl.replace("xxx", response);
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
Additional note:
Better to use client-side property in the response to differentiate between success and error conditions, as provided in example below:
if (eventid > 0)
{
...
return Json(new { id = id });
}
else
return Json(new { message = "Event not found" });
AJAX call
$.ajax({
url: '#Url.Action("DeleteEvent", "Events")',
data: data,
async: true,
success: function (response) {
if (typeof response.id !== 'undefined' && response.id != null) {
swal("Deleted!", "The event has been deleted.", "success");
// use query string because Url.Action helper runs server-side
window.location.href = '#Url.Action("Index", "Events")' + '?EventId=' + response.id;
} else if (typeof response.message !== 'undefined' && response.message != null) {
swal("Cancelled!!!", "Error : " + response.message, "error");
}
}
});
Try this:
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
window.location.href = '#Url.Action("Index", "Events", new { EventId = "' + response + '" })';
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
You have some errors in your syntax. Look at the code and you'll see the difference in the syntax.
Let me know how this goes.
Pass response value instead of its name
'#Url.Action("Index", "Events", new { EventId = "' + response + '" })'
Related
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);
}
});
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
I am using AJAX with my CodeIgniter application.
I've manged to make a "Ajax checkbox", so when I click on my checkbox, in background specific function is called.
But how to make a callback, I mean I would like to know if the operation was done ok, or maybe it was any problem/error.
My HTML:
<input type="checkbox" onClick="change_parameter(<?=$dane_leada['lead_id']?>, 'my_parameter');" >
JS:
function change_parameter(lead_id, parametr)
{
$.ajax({
type : "POST",
url : '<?=base_url();?>leads/change_parametr/' + lead_id,
data : "lead_id=" + lead_id,
data : "parameter=" + parameter,
});
alert("Status changed"); //here should be message "ok" or "error"
}
PHP in Controller:
public function change_parameter($lead_id, $parametr=FALSE)
{
if ($lead_id != "" AND isset($_POST['parameter']))
{
$parameter = $_POST['parameter']; //odczytujemy zmienną wysłaną przez AJAXa
}
if ($data['dane_leada'][$parameter] == '0') $new_parameter = 1; else $new_parameter = 0;
$dane = array(
'lead_id' => $lead_id,
$parameter => $new_parameter,
);
$this->model_leady->mofify_lead($lead_id, $dane);
// return error or confirm
}
Update the script with this:
function change_parameter(lead_id, parametr)
{
$.ajax({
type : "POST",
url : '<?=base_url();?>leads/change_parametr/' + lead_id,
data : {lead_id : lead_id,parameter :parameter},
success: function(response){
if(response){
alert("Status changed"); //here should be message "ok" or "error"
}else{
alert("ERROR :Something Wrong");
}
},
error: function (err) {
alert("ERROR :Something Wrong");
});
});
}
Or You can add error handler.
error: function (err) {
alert("ERROR :" + err.status);
}
I need to execute an ajax function, the detail here is that i want to execute this function until another ajax function return success.
This is the function that will i have to wait to return success (try..catch block)
Ajaxfunction1
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
try {
var jsonObject = JSON.parse(msg);
console.debug(msg);
//SendToDMS(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
},
failure : function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
}
});
I want something like this:
while ( Ajaxfunction1 != success ) { // while the previous ajax function not return success execute this another ajax function
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
// something on success
},
failure : function(msg) {
// something when comes an error
}
});
}
How can I accomplish this? Thanks for your help
You can use the returned Deferred from $.ajax and check it's state() to see if it's resolved, rejected or pending, so something like this with a recursive function should do what you want.
var waitFor = $.ajax({
type : "GET",
url : url,
data : parameters
}).done(function(msg) {
try {
var jsonObject = JSON.parse(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
}).fail(function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
});
(function rec() {
$.ajax({
type : "GET",
url : url,
data : parameters
}).always(function() {
if (waitFor.state() != 'resolved') rec();
}).done(function(msg) {
// something on success
}).fail(function(msg) {
// something when comes an error
});
})();
I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};