Display json in a new browser tab page - javascript

I have been trying for 4 days to solve this problem. But I cannot return json data into a new tab page.
My code:
<script type="text/javascript">
function CustomerId() {
var url = "Home/PanelGoster"; // My URL
var veri = {
Id: Id.GetValue(),
};
$.ajax({
url: "/Home/PanelGoster",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) {
}
else { // Success
var something = window.open(url, '_blank'); // Problem Here , it does not work
something.focus(); // Problem Here
("#MusterilerGetir").html(mydata); // Problem Here, should be displayed in a new tab
}
},
error: function () {
}
});
return false;
}
</script>
Controller:
public ActionResult PanelGoster(MyModel model)
{
var stringView = RenderRazorViewToString("PartialView", MyModel());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
}

try
something = window.open("data:text/json," + encodeURIComponent(mysdata),
"_blank");
something.focus();
from Open a new tab/window and write something to it?

Related

Javascript on change not working (Ajax to load filtered items)

I am in shopify and trying to Ajax a filter. I have a dropdown and the dropdown onchange should use Ajax to replace the contents of a bunch of products in the #collection div.
My onchange can't find my update products function. What is wrong with my syntax?
<script>
$(function() {
var popped = ('state' in window.history && window.history.state !== null),
initialURL = location.href;
//function to handle the scenarios where back and forward buttons used in browser
$(window).bind("popstate", function(e) {
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) {
return;
}
ajaxLoadPage(location.href);
});
//the ajax function that does the AJAX calls to get the products and load them into the grid
var ajaxLoadPage = function(url) {
$.ajax({
type: 'GET',
url: url,
data: {},
complete: function(data) {
$('#collection').html($("#collection", data.responseText).html());
history.pushState({
page: url
}, url, url);
}
});
}
}
function update_flavors(ajax_page) {
$.ajax({
type: "GET",
url: ajax_page + "?view=flavors-field",
success: function(html) {
$("#collection").html(html);
}
});
}
function update_products(ajax_page) {
$.ajax({
type: "GET",
url: ajax_page + "?view=products",
data: {},
success: function(html) {
$("#collection").html(html);
history.pushState({
page: ajax_page
}, "", ajax_page);
}
});
}
</script>

chrome.storage.local.get not working

Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.

Get pdf of current page MVC 5

I am trying to get a pdf of a div in my view.
I am doing the following:
I get the element, uri encode its html, then pass it to a method via ajax:
AJAX:
function getPDF(html) {
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) }
}).done(function (result) {
window.open("data:application/pdf; " + result);
$("#printArea").html(result);
}).fail(function (data) {
alert("Failed");
});
}
Method:
[HttpPost]
public void printPage(string html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
//var base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
Response.BinaryWrite(mem.ToArray());
//return File(mem, System.Net.Mime.MediaTypeNames.Application.Octet);
}
In the end I get a popup to open a pdf but it won't open, according to adobe acrobat it is corrupt.
I tried sending the html as a perameter to the method, but the perameter is too long
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
What would be a good way of doing this.
public JsonResult printPage(String html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
mem.Flush();
mem.Position = 0;
String b64Converted = Convert.ToBase64String(mem.ToArray());
return Json(b64Converted, JsonRequestBehavior.AllowGet );
System.Net.Mime.MediaTypeNames.Application.Octet);
}
Then in the view:
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) },
}).done(function (result) {
$("#printArea").append('PDF');
}).fail(function (data) {
alert("Failed");
});
Apparently its very easy
Just base64 the pdf and send it over at the json response.

Javascript firing, without me asking it to

I have an MVC4 application, and on the layout (master page for the oldies), I have some javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
This simply logs in a user.
This is working fine.
However, on another screen I now have some new javascript, which does similar function, by taking data from a form, and passing it to a controller to handle.
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewCard').on('click', function () {
var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };
$.ajax({
url: '#Url.Action("SaveBankCard", "BankAccount")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
// window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no");
}
});
});
});
</script>
When I click the save button that this code is linked to, the code fires, the controller method goes well, the data is stored, but then, when I refresh the screen, I get an 'Undefinied' error coming from the LOGIN script above. It seems to fire when the page is reloaded. I am unsure why it's firing. It should just load, ready to fire, but it seems to be called, and fails.
The controller that it calls is this:
public ActionResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
var card = new AccountCardDto
{
Id = 0,
AccountId = accountId,
Active = active == "on",
CardHolderName = cardHolder,
CardNumber = cardNumber,
ExpiryDate = new DateTime(expiryYear, expiryMonth, 1)
};
int id = new BankAccountService().SaveCard(card);
return RedirectToAction("EditBankAccount", new { bankAccountId = accountId });
}
The problem happens on the RedirectToAction... when that view reloads, which includes the Layout, the Layout javascript fires.
EDIT: I now see that it's the btnSubmitNewCard javascript that is fired twice. Once when the click event happens (expected), and then again when the postback happens. Why is the second event happening?
Check with this: -
$('.btnSubmitNewCard').click(function () {...});
You are getting Undefined in the line that checks status:
if (result.Success == 'true') {
Because result contains string with html response of the view for the EditBankAccount action and does not have "Success" property.
You can put breakepoint in debugger and see. You can use debugger; statement as breakpoint

Ajax call not succeeding after function call

I am attempting to load dynamic data based on the specific URI segment thats on the page.
Heres my Javascript:
$(document).ready(function() {
$(function() {
load_custom_topics();
});
$('#topics_form').submit(function() {
var topic = document.getElementById('topics_filter').value
$.ajax({
type: "POST",
url: 'ajax/update_session_topic',
dataType: 'json',
data: { topic: topic },
success: function(){
load_custom_topics()
}
});
return false;
});
function load_custom_topics(){
$.ajax({
type: "POST",
url: 'ajax/load_custom_topics',
dataType: 'json',
data: {},
success: function (html) {
$('div.topics_filter').html(html['content']);
get_threads();
}
});
}
function get_threads(){
var page = document.getElementById('page').value
$.ajax({
type: "POST",
url: 'ajax/get_threads',
dataType: 'json',
data: {page: page},
success: function (html) {
$('div#thread_list').html(html['content']);
}
});
}
});
So, as you can see, on page load, it kicks off load_custom_topics which runs just fine. Its then supposed to call get_threads(). This is where the thing stops, and I get no data.
Get_threads()
public function get_threads()
{
$session = $this->session->userdata('active_topic');
if ($this->input->post('page') == '1')
{
$data['list'] = $this->right_model->thread_list_all();
$data['test'] = "all";
} else {
$data['list'] = $this->right_model->thread_list_other($session);
$data['test'] = "not all";
}
if ($data['list'] == FALSE)
{
$content = "no hits";
} else {
$content = $this->load->view('right/thread_list', $data, TRUE);
}
$data['content'] = $content;
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
While I create the 'page' dynamically, the HTML outputs to this:
<div name="page" value="1"></div>
Any reason why get_threads() is not running?
This does not have an ID. It has a name.
<div name="page" value="1"></div>
This means that your request for getElementById is failing. So this line of code should be showing a TypeError in your console.
var page = document.getElementById('page').value

Categories