Display View in New Window - javascript

I have developed an ASP.NET MVC application that will run several prescreen functions based on user input.
The plan is to call this new mvc app from an existing HTML/JavaScript application. I would like to display the controllers's view in a new browser window outside of the calling application.
My AJAX call will look something like this
$.support.cors = true;
$.ajax( {
url: "http://mvc_url/prescreen",
data: jsonObject,
type: "POST",
processData: false,
dataType: 'html',
contentType: "application/json; charset=utf-8",
timeout: 60000,
//dataType: "json",
success: function ( msg )
{
...on success msg = html rendered from view...
},
error: function ( XMLHttpRequest, textStatus, errorThrown )
{
...error handling...
}
} );
I've tested this and on success msg does contain the fully rendered HTML from the view. My question is how do I open a new window using the rendered HTML?.
I've tried the following:
var newWindow = window.open( "", "", "" );
newWindow.document.write( msg );
and that seems to work. sort of. The new window opens and the html is displayed, but then my style sheets and included javascript files, for the view, are missing. So if using the above window.open code is correct, then how do I bring down the necessary stylesheets and javascript files?
EDIT
Utilizing the suggestion provided by AndyJ, I've modified my view to include relative paths based on my base application. Here is the returned mark up from my MVC
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offer</title>
<link href="../css/site.css", type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container body-content">
... Page Content ...
<script src="/baseapp/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="/baseapp/js/someInclude.js" type="text/javascript"></script>
<script type="text/javascript">
InitializeForm();
</script>
the InitializeForm method is defined within the someInclude.js.
Based on the above and assuming the files are locates in the paths, everything should link up, correct? So what else might I be doing wrong?

In addition to the help provided by Andy J (Thank you), I also found that when the response was rendered in the new window, the JQuery library was loading AFTER my initialization script. To circumvent this, I simply added my event handlers to the inline attributes of the controls.
This may be a work around, but for now it seems to be working for me.

If you are returning raw HTML in the AJAX request you will probably need to add the CSS and JS references there. You are not really returning a view that would normally have a layout that includes the references.

Related

PHP/HTML, AJAX is not calling/executing PHP file

Before I opened this question, I searched the entire internet on a solution. Maybe it is me or my solution. Sorry for that.
The situation is, I have a web app which is build with PHP and interacting with the database through functions. Every page is a php in which html code is executed.
The problem is, when I want to implement Ajax to update data without refreshing a page, the PHP file is not being executed when the button is clicked.
The javascript has two functions:
Alert serialized data of the button (works)
Run php script with Ajax (doesn't work)
Html Header
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
Im using bootstrap-table, one of the column is a button which has the following content:
<form id="form" class="favourite-form" method="post"><input style="display:none" type="hidden" id=5 name="subject_id" value=5 ><input type="submit" name="submit" value="Button"></form><div id="response"></div>
When clicked on the button the following alert is popping up:
The script file is included in the php file:
include("favorite_ajax.html");
The script file has the following content:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var data = $(this).serialize(); //"this" represents the form element in this context
alert(data); // this alert works
$.ajax({
method: "POST",
url: "process.php", // calling this php file doens't work
data: data,
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Finally the php file has one single simple function which inserts (dummy) data. The php file is tested and does not contain any errors.
<?php
insertDummyData(1, 123);
?>
In another topic I also read checking the logs. When I press the button, there is also no record being added in the logs.
Im cursious, what am I doing wrong? Spend like days to fix this, until now no results :(
put an error log in "process.php" to make sure that it's actually being called, if it's not being called, as others suggest, you may have path, permissions or script errors.
what does insertDummyData/process.php actually do? It must echo something as if it were writing to the page for the AJAX call to get a non-empty result. For example, in process.php
<?php
$new_data = my_function_which_does_stuff_to_posted_data($_POST['data']);
echo json_encode($new_data);
exit();

how to Invoke api using simple html code?

I have a small requirement that needs to make REST API POST call using HTML code. I have copied the sample code below and some reason this is not working. I am unable to see any call using the below code. Please let me know If there is any change required in the code.
<html>
<head>
<title>My first API script</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<H1>Testing the API call</h1>
<form>
<label for="msg">Message</label>
<button id='submitButton'>Submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var API_URL = 'https://example.com/'; // this will be my API like https://example.com
$('#submitButton').on('click', function(){
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringfly({"message": $('#msg'.val())}),
contentType: "application/json",
success: function(data){
location.reload();
}
})
})
</script>
</body>
</html>
Rewrite $('#msg'.val()) to $('#msg').val(), and implement an error(xhr, textStatus, errorThrown) function in .ajax too so you'd catch the error next time.
Several things need to be fixed in your code. Not sure if that's the one you're actually using but:
Change stringfly to stringify.
label doesn't have an id="msg" but you're trying to access it with #msg.
Add a e.preventDefault() on your click callback function. Make sure to receive e as parameter.
label-s don't have a val() function. If you're trying to get the "Message" inside the label, use $('msg').text().
Try using API placeholders like JSONPlaceholder instead of example.com so you don't get CORS errors.
Finally, add an error callback to your AJAX so you can catch and handle errors.

Url with parameters does not work in ajax but works alone

I've this simple HTML / Javascript sample code ....
<html>
<head>
<meta charset='utf-8' />
<title>Open Pronto Soccorsi</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<!-- *** References for JQuery ... -->
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
var city= "Torino";
$.ajax({
url: "http://www.webglobes.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php",
method: "GET",
data: {municipality: city, distance:0}
})
.done(function(output) {
alert("OK!");
})
.fail(function() {
// handle error response
alert("KO!");
})
</script>
</body>
</html>
... that invoke this url ...
http://www.webglobes.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php
with parameters:
municipality=Torino
distance=0
When I try to execute the result is always "KO" alert but if I try, in a new browser tab, the complete url that I can see in the browser console when I try to use my code
http://www.webglobes.org/cesarefortelegram/Telegram/OpenProntoSoccorso/API/getProntoSoccorsoDetailsByMunicipality.php?&municipality=Torino&distance=0
all works fine .... ???
Any suggestion will be appreciated
You haven't set a dataType in the request so jQuery is trying to decide which format the data is. That's fine, but if jQuery is inferring that the data is JSON then it is trying to parse it as well. If the data is not formatted correctly, then then you'll get a 200, but the parsing will fail and throw an error. That may be a good place to start.

Change the displayed text on same page of a <td> or <input> element after some action

I have searched for this answer and it seems that it should be simple, based on DOM.
What I want to do is display a <td id="cte"> or <input id="cte"> on a page and after some action (i.e. button click OR onchange ) the getElementById('cte').value="somenewvalue" ACTUALLY changes the forementioned or element on the same page.
The technology (i.e. javascript, AJAX, DOM) says that this is doable, yet I have seen this question asked numerous ways where the answers supplied never seem to work or satisfy the question.
So my actual question is: How do I change the 'displayed' element.value on the same page without having to reload the same page?
Do you think of elements consist several values/texts? (like a table)
//emty the element really at first if the element consists several values
var forempty = document.getElementById("cte");
while( forempty.firstChild ){
forempty.removeChild(forempty.firstChild);
}
document.getElementById("cte").value = something;
//or
document.getElementById("cte").textContent = something;
You answered your own question at least in one way: "The technology (i.e. javascript, AJAX, DOM) says that this is doable. And sure enough, with AJAX, it is only a matter of replacing the DOM Node with the Data (Response) from AJAX Request...
Here is a very Basic Example. We will fetch an HTML String using AJAX from the Server and use this Contents to replace the former Contents of a DIV, which contains the HTML < strong>Hello< /strong>
The first part of this Demo is our HTML or PHP Document containing our initial Markup and this File, we'd call index.html or index.php
CONTENTS OF index.php | index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mini AJAX Demo</title>
</head>
<body>
<div class="swappable-content" id="swappable-content">
<strong>Hello!!!</strong>
</div>
<div class="other-dom-elements">
<Button id="action-trigger" data-ajax-url="/ajax.php">Click Me</Button>
</div>
<!-- ADD JQUERY LIBRARY & SETUP THE AJAX REQUEST CALLS -->
<!-- HERE WE ARE LOADING JQUERY FROM THE CDN.... CHANGE THE src ATTRIBUTE IF YOU HAVE A LOCAL COPY -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e){
var actionTrigger = $("#action-trigger");
actionTrigger.on("click", function(e){
$.ajax({
url : $(this).attr('data-ajax-url'),
type : "POST",
dataType : "JSON",
data : {
// HERE YOU CAN ADD KEY VALUE PAIRS
// WHICH WILL BE SENT TO AND PROCESSED BY THE SERVER
},
success : successHandler,
error : errorHandler,
complete : completeHandler
});
});
function successHandler(data, textStatus, jqXHR){
// IF THERE IS A RESPONSE PAYLOAD FROM THE SERVER
// WE JUST REPLACE THE CONTENTS OF THE #swappable-content DIV WITH THE DATA
if(data){
if(data.html){
$("#swappable-content").html(data.html);
}
}
}
function errorHandler(jqXHR, textStatus, errorThrown){
console.log('The following error occured: ' + textStatus, errorThrown);
}
function completeHandler(jqXHR, textStatus){
}
});
})(jQuery);
</script>
</body>
</html>
CONTENTS OF AJAX PROCESSING SCRIPT: ajax.php
<?php
// YOU CAN DO PRETTY MUCH ANYTHING WITHIN THIS FILE
// HOWEVER FOR THE PURPOSES OF THIS DEMO,
// WE WOULD JUST RETURN SOME HTML STRING BUNDLED IN AN ARRAY AND SENT AS JSON DATA
$response = array(
'html' => "<div style='font-weight:900;color:#F00;'>This is the Response Data from Server!</div>",
);
die(json_encode($response));

js .append html element do not have javascript lib

I'm trying to use $.ajax to get html string from php file and append to current html div. when i try to use php echo, everything works fine, but when i try to dynamically load using $.load or $.ajax, javascript library doesn't load or apply to the div.
included js libs in header:
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="MetroJs.lt.min.css">
<script src="MetroJs.lt.min.js" type="text/javascript"></script>
script file in header:
function getdatafromphp() {
$.ajax({
type: 'POST',
url: "autoload_process.php",
data: {group_no : track_load},
dataType: 'html',
async: true,
success: function(html) {
$("#results").append(html);
track_load++; //loaded group increment
loading = false;
}
})
}
html code in body:
<div id="results"></div><div class="animation_image" align="center"><img src="ajax-loader.gif"></div>
i put rest of css and js right after the div:
<link rel="stylesheet" type="text/css" href="index.css"/><script src="index.js" type="text/javascript"></script>
The html can be loaded into div, but it does not have any js effect to it (css is fine)
I suspect is because i use $(document).ready in both js scripts, but changing it does not help.
here is my test site: http://www.zsm.me/test/newindex/
Please help if you have any thoughts.
Thanks.
Try to bring in the data (html) into the specified div, then initialize the plugin for each of the elements inside the html.For ex:
success: function(html){
$("#mybutton").buttonset();
$("#dateofbirth").datepicker();
}
Today i find a new method by adding
<?php echo $script; ?>
in the header.
I have no idea why this works but it does...
well, hope this helps

Categories

Resources