How to add new browser tab - html

It won't go to a new browser tab, is my code wrong?
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
$(location).attr('href', a)
a.preventDefault();
},
error: function (err) {
}
});
}

What you're looking for might be:
window.open('http://stackoverflow.com/', '_blank');
And in your code:
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
var win = window.open('http://stackoverflow.com/', '_blank')
if(win) {
win.focus(); /if tab is open, change focus there.
}
},
error: function (err) {
// do stuff here
}
});
}

Related

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);
}
})
})

prevent AJAX success result to download file or open

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?

In Ajax Image Upload, ev.preventDefault(); not working

It uploads the image but it redirects to UploadImage.cshtml. So apparently ev.preventDefault isn't working. Is there a solution to this without having me to go through blueimp or xhtml stuffs coz I am not ready to touch those stuffs.
HTML
<form method="post" action="UploadImage.cshtml" id="imgUploadForm" class="imgUpload" enctype="multipart/form-data">
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag: false,
uploadText:"Upload")
<input type="submit" name="buttonUpload2" value="Upload" />
</form>
Jquery
$(function () {
$('.imgUpload').submit(function (ev) {
var frm = $(this);
Upload(frm);
ev.preventDefault();
});
});
function Upload(frm) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: new FormData(frm),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
}
Solved with following Jquery code. Thanks
$(document).ready(function (e) {
$('.imgUpload').on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert('success');
},
error: function (data) {
alert('error');
}
});
}));
})

Ajax read large json file slowly

I am using AJAX to read a large JSON file (about 15 MB minified), in order to display autocomplete suggestions on a text field.
The problem is that after user types 4 characters in order the suggestions to begin, i have to wait around 20 to 60 seconds which makes actually impossible to use it.
I don't know any techniques how i could make it read the JSON file faster.
I would like to read your suggestions...
My AJAX request is :
$(document).ready(function () {
$("#card").autocomplete({
source: function (request, response) {
$.ajax({
dataType: "json",
data: {
term: request.term,
},
type: 'GET',
contentType: 'application/json; charset=utf-8',
xhrFields: {
withCredentials: true
},
cache: true,
url: base_url+'/test123/wp-content/plugins/trading-collectible-cards/public/js/AllSets.json',
success: function (data) {
var keys = Object.getOwnPropertyNames (data)
var outputArray;
$.each(keys,function(ele, val){
var array = $.map(data[val].cards, function (set) {
return {
label: set.name + " (" +data[val].name + ")",
value: set.name,
text: set.text,
multi: set.multiverseid,
rarity: set.rarity,
setname:keys[ele],
setfull:data[val].name
}
});
if (ele == 0)
outputArray = $.merge([], array);
else {
outputArray = $.merge(outputArray, array);
}
});
response($.ui.autocomplete.filter(outputArray, request.term));
},
error: function (data) {
}
});
},
minLength: 3,
open: function () {
},
close: function () {
},
focus: function (event, ui) {
},
select: function (event, ui) {
$( "#card" ).val( ui.item.label );
$( "#description" ).html( ui.item.text );
}
});

HTTP GET not getting

Trying this but getting nothig
function getWeather() {
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
On clicking button it should return the JSON
<body>
<button onclick="getWeather();">Get Weather</button>
</body>
Expected example JSON:
{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5168,"message":0.0287,"country":"GB","sunrise":1415603442,"sunset":1415636293},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":284.99,"pressure":1003,"humidity":76,"temp_min":283.75,"temp_max":286.15},"wind":{"speed":5.1,"deg":210},"clouds":{"all":75},"dt":1415624678,"id":2643743,"name":"London","cod":200}
I am not getting the mistake I have done.
EDIT
Tried with this from snippets given here:
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script language="javascript" type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
//alert(JSON.stringify(data));
data_Json = data;
//alert("Weather Report: "+data_Json);
},
error: function(e) {
alert(e.message);
}
});
return data_Json;
}
function temp() {
//getWeather();
var obj = JSON.stringify(getWeather());
//alert("Got"+JSON.stringify(obj));
//alert(JSON.stringify(getWeather()));
//document.getElementById("temp").innerHTML = obj.main.temp;
alert("Temp : "+obj);
}
</script>
</body>
<body>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
</html>
It returned {}
Not returned the JSON (the return defined in getWeather)
Not the temperature (in get element by id part)
Remove contentType from your request and it will work fine.
Since this is a cross origin request, you cannot set contentType.
Following is the error you will see in your console -
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/weather?q=London. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
Also the statement return data; will fail as variable data is not available in that context.
You can use the below code for your purpose -
function getWeather() {
weatherJson = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
weatherJson = data;
},
error: function(e) {
alert(e.message);
}
});
return weatherJson;
}
You can try this solution
function getWeather() {
data_Json = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
dataType: 'JSONP',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
data_Json = data;
},
error: function(e) {
alert(e.message);
}
});
return data_Json; }
For Edit Part:-
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function (data) {
data_Json = JSON.stringify(data);
},
error: function (e) {
alert(e.message);
}
});
alert(data_Json);
return data_Json;
}
function temp() {
var obj = getWeather();
alert("Temp : " +obj);
}
</script>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
Hi See this,
function getWeather() {
var returnData="";
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
returnData=data;
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
Do you actually have an element with id="jsonp-results" in your html?
Some hints to simplify:
You don't need to specify a jsonp callback if you are not using jsonp
Synchronous calls are not nice because they block, you should avoid that and they aren't even supported for cross-domain calls (which your case is)
Simplified example:
function getWeather() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e) {
alert(e.message);
}
});
}
<body>
<button onclick="getWeather();">Get Weather</button>
<div id="jsonp-results"></div>
</body>
After your comment: It certainly works:
http://codepen.io/anon/pen/MYgXzd
You must have something wrong in your setup.