prevent AJAX success result to download file or open - json

I have this jquery to make a post request:
$('#btnAdd').click(function (e) {
$('#modal_processing').modal('show');
$('#modal_body_process').html("Please wait while we are processing your request. This message will automatically close when request successfully completed.");
$('#modal_title_process').html("Processing...");
$.ajax({
url: '#Url.Action("AddNew", "Home")',
type: 'POST',
data: {
Name: $('#txtEmail').val(),
Project: $('#cbProject').val(),
Gender: $('#cbGender').val(),
Level: $('#cbLevel').val(),
ShiftStart: $('#txtShiftStart').val(),
ShiftEnd: $('#txtShiftEnd').val(),
GeoId: $('#cbGeo').val(),
TowerId: $('#cbTower').val(),
ProcessId: $('#cbProcess').val(),
PrimaryTeamId: $('#cbPrimaryTeam').val(),
RegionId: $('#cbRegion').val(),
WBSId: $('#cbWBS').val(),
},
dataType: "json",
success: function (response) {
$('#modal_body_process').html("New user has been successfuly added.");
$('#modal_title_process').html("Successful!");
setTimeout(function () {
$('#modal_processing').modal('hide');
}, 3000);
},
error: function (resp) {
$('#modal_body_process').html("Please fill out all required fields.");
$('#modal_title_process').html("Error");
setTimeout(function () {
$('#modal_processing').modal('hide');
}, 3000);
alert("Error");
}
});
});
in my controller, i have this:
if (result.IsSuccessStatusCode)
{
ModelState.Clear();
return Json(result.StatusCode, JsonRequestBehavior.AllowGet);
}
return View(model);
my problem is, everytime the result is success, it always prompting me to download the json file (IE 11) and for mozilla, it opens the json file.
how can i prevent this?

Related

AJAX success function not being called even though HTTP 200 is returned

When a user clicks 'buy now', I want the transaction to happen and the div to eventually be faded out and removed once being processed by the controller. Everything in the controller works as it should, but when I put the function in the success, it isn't called. However it works when the function is placed outside the success. Additionally, a window.alert() somehow works when there's a success.
Here is my script, everything works in regards to the controller etc
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
$(this).closest('.product').fadeOut("normal", function() {
$(this).closest('.product').remove();
});
}
});
}));
});
Everything above in the controller works fine as well, here is what it returns:
return response()->json(['ok' => 'ok']);
You cannot use this under success function because this is out scope . Just change your code like below :
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
var element=this;//getting current element click in variable
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
//passing variable
$(element).closest('.product').fadeOut("normal", function() {
$(element).closest('.product').remove();
});
}
});
}));

History.go(-1) does not work in chrome extension

I am creating a chrome extension that goes back to a certain site. But history.go(-1);The syntax is not working Why?
chrome.tabs.executeScript({
code: 'document.URL;'
}, function (domain) {
var google = 'https://www.google.co.kr/';
if (domain == google) {
history.go(-1);
}
else
alert('not google')
$.ajax({
type: 'GET',
url: 'http://www.mhwdb.kr/main/apis/monsters',
// data: {
// url: domain
// },
// dataType: 'json',
success: function(success){
document.getElementById('url').innerHTML = success;
},
error: function(error) {
console.log(error);
}
})
})

Get variable from Sencha Touch Ext.data.JSONP.request response

I'm trying to get a boolean (success) and a HTML string (result) from the response to an Ext.data.JsonP.request, but I can't fgure out how. Here's the code I have so far:
Ext.data.JsonP.request({
url: 'http://wereani.ml/shorten-app.php',
callbackKey: 'callback',
params: {
data: Ext.encode(values)
},
success: function(response) {
console.log(response);
console.log(JSON.stringify(values));
console.log('Link Shortened');
if(response.responseText['success'] == true) {
Ext.Msg.alert('Link Shortened', response.responseText, Ext.emptyFn);
} else {
Ext.Msg.alert('Error', response.responseText, Ext.emptyFn);
}
form.reset();
},
failure: function(response) {
console.log(response);
console.log(JSON.stringify(values));
console.log('Error');
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});
Some sample JSON-P:
callback({"success":false,"result":"<div class=\"error\">Please enter a valid link to shorten!<\/div>"})
The error I'm currently getting is Uncaught TypeError: Cannot read property 'success' of undefined.
Thanks in advance for the help!
EDIT: It seems that while response is Object {success: false, result: "<div class="error">Please enter a valid link to shorten!</div>"}, response.responseText is undefined. Am I using the wrong variable? I couldn't find any documentation on response.
EDIT 2: It seems that the reason Console.log(response.responseText) was returning undefined is because it.... was. The JsonP-encoded variables (success and result) that I passed were parsed automatically into the object, and response.responseText was never created (though I think it was supposed to be). The solution was to just read response.success and response.result directly!
ANSWER: Here's the code that worked. Thanks to Viswa for the help!
Ext.data.JsonP.request({
url: 'http://wereani.ml/shorten-app.php',
callbackKey: 'callback',
params: {
data: Ext.encode(values)
},
success: function(response) {
if(response.success === true) {
Ext.Msg.alert('Link Shortened', response.result, Ext.emptyFn);
} else {
Ext.Msg.alert('Error', response.result, Ext.emptyFn);
}
form.reset();
},
failure: function(response) {
console.log('Error');
Ext.Msg.alert('Error', '<div class="error">Please try again.</div>', Ext.emptyFn);
}
});
Try like this
Ext.data.JsonP.request({
url: 'http://example.com/script.php',
callbackKey: 'callback',
params: {
data: Ext.encode(values)
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});

in action, return json("Partial view name") doesn't go to success of ajax

I have 2 function in my js file for 2 button.
when i try to:
return Json("_ThanksForLogin");
it doesn't go to js file, doesn't go to success of ajax.
when click the button it just shows the string "_ThanksForLogin" in dialog box.
what should i do?
my function:
$(function () {
$("#loginBtn").click(function () {
var user = getUser();
// poor man's validation
if (user.Username == null) {
alert("please enter username.");
return;
}
if (user.Password == null) {
alert("please enter password.");
return;
}
var json = $.toJSON(user);
$.ajax({
url: '/Members/MemberLoginPartial/LoginUser',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success:
function (address) {
$("#resultMessage").load(address);
setTimeout(function () { $("#resultMessage").dialog("close") }, 1000);
location.href = "/Members/Members/Index";
},
close: function (event, ui) {
location.href = "/Members/Members/Index"
}
});
});
});
I want to send address of "_ThanksForLogin" partial view by return json() in action to this part:
success:
function (address) {
$("#resultMessage").load(address);
setTimeout(function () { $("#resultMessage").dialog("close") }, 1000);
location.href = "/Members/Members/Index";
},
and after it, the dialog close automatically and redirect to user profile.
thanks for helping...
Json() is supposed return a JSON, not html. What you need is
return PartialView(_ThanksForLogin)
which will return the PartialView named "_ThanksForLogin".

How do get jquery fullcalendar to pass additional parameters to my json feed script

My code is as follows
jQuery('#calendar').fullCalendar({
weekMode: 'liquid',
events: themeforce.events,
eventRender: function (event, element) {
element.find('span.fc-event-title').html(element.find('span.fc-event-title').text());
}
});
where themeforce.events is a variable containing an encoded url of the json feed a php file - all works well.
I tried replacing events: themeforce.events, with
events: {
url: themeforce.events,
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
However now the calendar fails to load.
What can I do?
I wanted the start and end times for a post ajax request and it took me a bit of time to work it out.
This might help you:
events: function(start, end, timezone, callback) {
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format(),
custom_param1: 'value 1',
custom_param2: 'value 2',
},
error: function () {
alert('there was an error while fetching events!');
},
success: function(doc) {
var events = [];
$.each(doc,function (index, e) {
events.push(e);
});
callback(events);
}
});
}
You should use extraParams as explained in doc : https://fullcalendar.io/docs/events-json-feed
var calendar = new Calendar(calendarEl, {
eventSources: [
// your event source
{
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
Also be sure your feed's url return raw json data array !
Just put "data" instead of "extraParams" in "events"
events: {
url: 'service.php',
method: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
}