Ajax response comparison with string - ajax

In the below example my Ajax response is coming as 'success'[ type is string], and I am comparing the 'success' [type is string]. Then why does the control not enter into the if condition?
$.ajax({
url: "controller.php",
method: "POST",
data: { loginData : $("#loginForm").serialize()},
dataType: "text",
success: function (response) {
if(response=='success') // response coming as is 'success'
{
window.open('www.google.com');
}
},
error: function (request, status, error) {
/* error handling code*/
}
});

You are passing data as plain text. I recommend passing data as JSON because it's easier to catch the response from the server.
Also, you are using a variable that will contain more variables (the form inputs) in data: { loginData : $("#loginForm").serialize()}. I recommend you using .serializeArray() to send data as JSON variables that you can catch in the server script.
So:
$.ajax({
url: "controller.php",
method: "POST",
data: $("#loginForm").serializeArray(),
dataType: "json",
success: function (response) {
if(response["success"]) {
window.open('www.google.com');
}
},
error: function (request, status, error) {
// error handling code
}
});
And in controller.php:
<?php
if(isset($_POST['input'])) { // use your input's name instead
$response['success'] = true;
} else {
$response['success'] = false;
}
header('Content-Type: application/javascript');
echo json_encode($response);
?>
And also, with this last code snippet you can pass more than "success" (simply because you're using an array). Eg:
<?php
if(isset($_POST['input'])) { // use your input's name instead
$response['success'] = true;
$response['open'] = 'www.google.com';
} else {
$response['success'] = false;
}
header('Content-Type: application/javascript');
echo json_encode($response);
?>

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

Make an Ajax request in Yii 2.0?

Right, i only want a very simple ajax request to get this working. im new with yii 2.0 framework you see.
in my view index.php:
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { test: test },
success: function(data) {
alert(data);
}
});
}
Now when i call this i assume that it should go to my CasesController to an action called actionAjax.
public function actionAjax()
{
if(isset($_POST['test'])){
$test = "Ajax Worked!";
}else{
$test = "Ajax failed";
}
return $test;
}
EDIT::
Ok great, so this works up to here. I get back the alert that pops up with the new value for $test. However i want to be able to access this value in php as ultimately i will be accessing data from a database and ill be wanting to query and do various other things.
So how do i now use this variable in php instead of just the pop up alert()?
Here is how you can access the post data in controller:
public function actionAjax()
{
if(isset(Yii::$app->request->post('test'))){
$test = "Ajax Worked!";
// do your query stuff here
}else{
$test = "Ajax failed";
// do your query stuff here
}
// return Json
return \yii\helpers\Json::encode($test);
}
//Controller file code
public function actionAjax()
{
$data = Yii::$app->request->post('test');
if (isset($data)) {
$test = "Ajax Worked!";
} else {
$test = "Ajax failed";
}
return \yii\helpers\Json::encode($test);
}
//_form.php code
<script>
$(document).ready(function () {
$("#mausers-user_email").focusout(function () {
sendFirstCategory();
});
});
function sendFirstCategory() {
var test = "this is an ajax test";
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->getUrlManager()->createUrl('cases/ajax') ; ?>",
data: {test: test},
success: function (test) {
alert(test);
},
error: function (exception) {
alert(exception);
}
})
;
}
</script>
You can include js this way in your view file:
$script = <<< JS
$('#el').on('click', function(e) {
sendFirstCategory();
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: "<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>",
data: {test: test},
success: function(data) {
alert(data)
}
});
}

how to get the value from codeigniter to ajax?

i have an ajax which I don't know if it is correct. I want to get the value from the controller and pass it to ajax.
ajax:
$.ajax({
type: "GET",
url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),
success: function(response) {
if (response != "Error")
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
event.preventDefault();
and in the controller:
public function swoosh_delete_child()
{
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response = $this->emp->delete_children($id);
}
model
public function delete_chilren($id){
.......//codes here.. etc. etc.
if success //
return "success";
else
return "Error";
}
i just want to pass/get the value of $reponse and pass it to the ajax and check if the value is error or not..
Just echo in the controller:
$response = $this->emp->delete_children($id);
And alert the response:
alert(response); //output: success / Error
in your controller:
you should have something like this
public function swoosh_delete_child(){
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response['status'] = $this->emp->delete_children($id);
echo json_encode($response);
}
then in your ajax, to access the response
$.ajax({
type: 'POST',
url: url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),,
dataType: 'json',
success: function(response){
if (response.status)
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});

Can I return custom error from JsonResult to jQuery ajax error method?

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:
Still throw the error on the server (this is used for logging)
Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
Returning error info from catch block
This works, but the exception can't be thrown
Editing HTTP response in catch block
Then inspected xhr in the jQuery error handler
xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
I think this may be possible, but I just did it wrong?
You could write a custom error filter:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let's suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.
And on the client:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
and then:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.
The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message.
You have to use customError mode in web.config, or add
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
or
"You can also go into IIS manager --> Error Pages then click on the
right on "Edit feature settings..." And set the option to "Detailed
errors" then it will be your application that process the error and
not IIS."
you can return JsonResult with error and track the status at javascript side to show error message :
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
My MVC project wasn't returning any error message (custom or otherwise).
I found that this worked well for me:
$.ajax({
url: '/SomePath/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("start JSON");
if (result.Success == "1") {
window.location.href = "/SomePath/index";
}
else {
alert(result.ex);
}
alert("end JSON");
},
error: function (xhr) {
alert(xhr.responseText);
}
//error: AjaxFailed
});
Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.
If for some reason you can't send a server error. Here's an option that you can do.
server side
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object
if (!String.IsNullOrEmpty(items.OldName))
{
DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);
if(update.Rows.Count > 0)
{
List<errors> errors_ = new List<errors>();
errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));
return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
}
}
return items;
client side
$.ajax({
method: 'POST',
url: `legacy.aspx/${place}`,
contentType: 'application/json',
data: JSON.stringify({data_}),
headers: {
'Accept': 'application/json, text/plain, *',
'Content-type': 'application/json',
'dataType': 'json'
},
success: function (data) {
if (typeof data.d === 'object') { //If data returns an object then its a success
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
})
Toast.fire({
type: 'success',
title: 'Information Saved Successfully'
})
editChange(place, data.d, data_);
} else { // If data returns a stringify object or string then it failed and run error
var myData = JSON.parse(data.d);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
})
}
},
error: function (error) { console.log("FAIL....================="); }
});

Make a if loop according to what returns the ajax html(data)

I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}
Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});
The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}
You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}

Resources