Javascript open in new tab by using json - javascript

Javascript Code:
<script type="text/javascript">
function MusteriBilgileriKaydet2() {
var veri = {
AnaOzelDurumId: AnaOzelDurumId.GetValue(),
AnaİlgiliPersonelId: AnaİlgiliPersonelId.GetValue(),
};
if (veri.MusteriAdiTextBox1.trim() == "" || veri.MusteriAdiTextBox1 == undefined || veri.MusteriAdiTextBox1 == null) {
$("#showwarning222").html('<img src="/Image/warning.png" title="Müşteri Adı Giriniz!">').show();
}
else {
LoadingPanel.Show();
$.ajax({
url: "/Home/GenelMusterilerGridView2",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) { // Error
LoadingPanel.Hide();
alert("Müşteri Adı Mevcut");
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
else { // Success
$("#MusterilerGetir").html(mydata);
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
},
error: function () {
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
});
return false;
}
}
</script>
My Controller:
public ActionResult GenelMusterilerGridView2(MyModel model)
{
var stringView = RenderRazorViewToString("MerkezPartial", ModelleriGetir());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { error6 = true, JsonRequestBehavior.AllowGet });
}
}
return null;
}
My all codes works well .
I only want to open in new tab page .
So
How can i open in new tab in browser after i post data to my controller ?
Any help will be greatly appreciated.
Thanks.

you can add to your html <a href tag a target that looks like this.
Link name or text
OR you can in your javascript code add
function OpenNewTab(url){
var something = window.open(url, '_blank');
something.focus();
}
Now this should be working fine but just because some clients prevent pop-ups then you could add this to your html tag too.
<div onClick="OpenNewTab();">your link name</div>
Hope this will work for you
Cheers!

Related

ajax loading indicator stopped in between

I am saving data on a save button click that calls ajax and passing json data to a controller method but when we save it loading starts and suddenly stop though the data is not saved.
It is not working I have tried it in all way but not working please help me on this.
<button type="button" id="saveDeleg" class="btn_reg_back btnmainsize btnautowidth btngrad btnrds btnbdr btnsavesize " aria-hidden="true" data-icon="">#Resources.Resource.Save</button>
$('#saveDeleg').click(function() {
var response = Validation();
if (!response) {
return false;
}
$("#overlay").show();
$('.loading').show();
if ($('#organName').val() == '') {
$('#validorganisation').show();
return false;
} else {
$('#validorganisation').hide();
}
//Contact name
var SubDelegation = $('#subdelegation').is(':checked');
var CopyNotification = $('#copynotification').is(':checked');
var ArrangementId = $("#ArrangementId").val();
var paramList = {
ArrangementId: ArrangementId,
ArrangementName: $('#arrangName').val(),
OrganisationName: $('#organName').val(),
OrganisationId: $('#OrganisationId').val(),
ContactName: $('#contactName').val(),
ContactId: $('#ContactId').val(),
SubDelegation: $('#subdelegation').is(':checked'),
CopyNotification: $('#copynotification').is(':checked'),
ContactType: $('#ContactType').val(),
SelectedTypeName: $("input[name$=SelectedType]:checked").val()
};
setTimeout(function() {
$.ajax({
async: false,
type: "POST",
url: '#Url.Action("SaveDelegation", "Structures")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paramList),
processdata: true,
success: function(result) {
//stopAnimation()
paramList = null;
if (result == 0) {
window.location.href = '../Structures/MyDelegationArrangement';
} else if (result == 1) {
window.location.href = '../Structures/CreateDelegation';
} else if (result == 2) {
window.location.href = '../Home/Error';
} else if (result == 3) {
window.location.href = '../Account/Login';
} else {
//validation message
alert('Error');
}
},
error: function() {},
complete: function() {
$("#overlay").hide();
$('.loading').hide();
}
});
}, 500);
});
The problem with the loading indicator is because you used async: false which locks up the UI. Remove that setting.
Also note that if the data is not being saved I would assume that your AJAX call is returning an error. If so, check the console to see the response code. It may also be worth putting some logic in the error callback function to give you some information on whats happened, as well as inform your users about what to do next.

Rendering PartialView via AJAX takes too long time in MVC

There is a Layout page in my MVC app and with the help of a menü link on this Layout page, I render a PartialView having only 5-6 input with no css or js import. As it can bee seen on the image below, it takes approximately 4 second just loading this PartialView and I think there is a big mistake regarding to this logic. Could you please have a look at the page and clarify me about where I did mistake?
Note: As far as I see the time consuming part of the AJAx method is in the success part (until $("#div-page-content").html(''); line). Is it needed or how can I change that part with a faster code block?
LayoutPage:
<a href="#" id="register" class="nav-link" onclick="renderPartial(event, 'Account', 'Create')">
<div id="div-page-content" class="page-content">
#RenderBody()
</div>
<script>
function renderPartial(e, controller, action) {
e.preventDefault();
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
$("#div-page-content").html('');
$("#div-page-content").append(data);
},
error: function (data) { onError(data); }
});
};
</script>
_PartialView:
<div>
//... code omitted fr borevity (there is no js or css import in this view
</div>
Controller:
[HttpPost]
public ActionResult Create()
{
return PartialView("_Register");
}

Ctrl+Click on link that renders partial view

I got a link that renders partial view using AJAX.
Here is my link code:
<a href="#" onclick="LoadChildCategories(#i.CategoryId,
#i.IsTrading.ToString().ToLower())">#i.Name</a>
And here is LoadChildCategories function code:
function LoadChildCategories(id, isTrading) {
var link;
if (isTrading === false) {
link = '#Html.Raw(#Url.Action("NonTradingCategories", "Home",
new {categoryId = -1}))';
} else {
link = '#Html.Raw(#Url.Action("ModelList", "Home", new {categoryId = -1}))';
}
link = link.replace("-1", id);
$.ajax({
url: link,
method: 'GET',
success: function(data) {
$("#viewPartial").html(data);
}
});
}
When I click it without CTRL it's ok, partial view renders into my div. But when I click it with CTRL partial view renders into current tab and then another tab opens at Index page.
And when I rightclick on link and select to open it in another tab then nothing happens at current tab and new tab opens at Index page.
So, is there any ways to handle that?
I found pretty nice solution, so I modified project according to this solution: Make an MVC Application into a SPA with AJAX and History.js
1) Make controller methods return View, not PartialView and add one line of code than will check is it an AJAX request:
public ViewResult Category(int id)
{
ViewBag.IsAjaxRequest = Request.IsAjaxRequest();
var node = CategoriesHandler.Instance.First(x => x.CategoryId == id);
var childCategories = CategoriesHandler.Instance.Where(x => x.ParentId == node.Id).ToList();
ViewBag.Message = node.Name;
return View(childCategories);
}
2) Edit _ViewStart.cshtml like that:
#{
Layout = ViewContext.ViewBag.IsAjaxRequest == true ? null : "~/Views/Shared/_Layout.cshtml";
}
3) Prepare links to be managed via AJAX:
#i.Name
4) Create container for views at _Layout.cshtml
#/*Some layout stuff*/
<div id="bodyContent">
#RenderBody()
</div>
#/*Other layout stuff*/
5) Prepare helper javascript file like that:
$(function () {
var contentShell = $('#bodyContent');
var History = window.History, State = History.getState();
$(".ajaxLink").on('click', function (e) {
e.preventDefault();
var url = $(this).data('href');
var title = $(this).data('title');
History.pushState(null, title, url);
});
function navigateToURL(url) {
$('#bodyContent').html('<div class="loader"> </div>');
$.ajax({
type: "GET",
url: url,
dataType: "html",
cache: false,
success: function (data, status, xhr) {
$('#bodyContent').hide();
contentShell.html(data);
$('#bodyContent').fadeIn(500);
},
error: function (xhr, status, error) {
$('#bodyContent').hide();
alert("TEST_Error");
}
});
}
History.Adapter.bind(window, 'statechange', function () {
State = History.getState();
if (State.url === '') {
return;
}
navigateToURL(State.url);
});});
6) Do not forget to include your javascript files into the bundle!

Weird behavior under chrome and $.ajax after chrome update

I've an asp.net mvc5 application that on a loginpage does the following Ajax call
$(document).ready(function () {
var formObj = $(".login-form");
$("form input[name=username]").val("user");
$("form input[name=password]").val("password1!");
formObj.submit(function (event) {
event.preventDefault();
console.log("test");
validator = formObj.validate();
if (validator.checkForm()) {
var form = formObj.get();
var rememberMe = $("input:checkbox[name=remember]:checked").val() ? true : false;
$(form.rememberMe).val(rememberMe);
args = {
form: form,
userName: $(form.username).val(),
password: $(form.password).val(),
remember: rememberMe
}
var url = #Url.Content("~/api/auth");
func = $.ajax({
url: url,
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
#if(Request.Params.Get("redirect") != null) {
<text>
window.location = "#Request.Params.Get("redirect")";
</text>
}
else
{
<text>
window.location = "#Url.Content("~/Home")";
</text>
}
}
}
});
}
});
});
If I put this piece of code
var url = #Url.Content("~/api/auth");
it works, otherwise if I quote the url string (as it should be correct)
var url = "#Url.Content("~/api/auth")";
it hangs the browser.
This only happens under chrome as first iussue was reported with Chrome Version 43.0.2357.65 m
What is wrong?
Thanks
UPDATE #1
I've noticed that the problem is there
$.ajax({
url: "/someurl",
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
window.location = "/someotherurl/";
}
}
});
If I sue ajax it breaks...if I use $.post or $.get it works...

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources