Onclick page should not reload - javascript

Hi how can i make my page don't reload every time i click another link?
function myFunctionD(id) {
var x=document.getElementById(id);
var myURL = "http:www.sample.php";
document.location = myURL + "?t_id=" + x.id ;
return false
}
HTML:
<a href="docview.php?id=26" id="3" onclick="myFunctionD('3')" target="iframe_a" >July 17, 2013</a>
<a href="docview.php?id=26" id="4" onclick="myFunctionD('4')" target="iframe_a" >July 18, 2013</a>

You can change the target to open the link in new tab or window . Use window.open() instead of window.location

You can use ajax something like this
<script type="text/javascript">
$(function(){ myFunctionD('3'){
var form = $(this).parent("form");
$.ajax({
type: "POST",
url: form.attr("yourform"),
data: form.serialize()
})
return false;
});
});
</script>

Actually you don't even need to use Ajax. You can simply load content of another page in your current page with Jquery's $.get function
//Inserting a div for holding another page content. On click of button, this div will update content
<div id="contentdiv"></div>
<input type="button" value="Page 1 Load Content" onclick="loadContent('page1.html')"/>
<input type="button" value="Page 2 Load Content" onclick="loadContent('page2.html')"/>
<input type="button" value="Page 3 Load Content" onclick="loadContent('page3.html')"/>
<script type="text/javascript">
function loadContent(page)
{
//Empty contentdiv for new content and add new page content with jquery's $.get
$('#contentdiv').empty();
$.get('http://www.example.com/'+page, function(data) { $("#contentdiv").append(data); });
//This will load page content in your contentdiv
//for more info about $.get visit this http://api.jquery.com/jQuery.get/
}
</script>
In your other pages, just put that content which you want to load into contentdiv. Do not make complete html page with html and body tags etc. Just content you want to appear in you contentdiv.

Related

Get weird syntax when opening automatically created pdf php javascript

I'm trying to make a website where users can make a pdf. I want to show the pdf directly next to the button when I press "create worksheet". I tried to do it with javascript and php, but I get a weird syntax in my iframe instead of the actual pdf. Does anybody know the correct way of doing this?
<?php
$titel = "TITLE";
require_once('tcpdf/tcpdf.php');
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$obj_pdf->SetTitle("educationworksheet.com");
$obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, '5', PDF_MARGIN_RIGHT);
$obj_pdf->setPrintHeader(false);
$obj_pdf->setPrintFooter(false);
$obj_pdf->SetAutoPageBreak(TRUE, 10);
$obj_pdf->SetFont('helvetica', '', 12);
$obj_pdf->AddPage();
$content .= '
<h3 align="center">TITLE</h3><br /><br />
<h4 align="left">This is what we are gonne do '.$titel.'</h4><br /><br /><h4 align = "left">Name:____________________________</h4>
';
$obj_pdf->writeHTML($content);
$obj_pdf->Output('sample.pdf', 'I');
?>
<!DOCTYPE html>
<html>
<head>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pdf_viewer").srcdoc = this.responseText;
}
};
xhttp.open("GET", "/test2.php", true);
xhttp.send();
}
</script>
</head>
<body>
<button height="10px" width="30px" onclick="loadDoc()" name="create_pdf" value="create worksheet">create worksheet</button>
<iframe id="pdf_viewer"></iframe>
</body>
</html>
Firstly, the issue is the browser will not interpret the PDF data as a PDF in that way. srcdoc is treated as raw HTML.
There are a couple of different ways to accomplish your "generate on click" functionality:
1) You could just drop the AJAX entirely and just use HTML form markup to accomplish this. Using the target attribute on the form element to target your PDF viewer iframe.
<body>
<!-- Set up our form to target the PDF viewer iframe.-->
<!-- Note: This will work with both GET and POST methods -->
<form action="/test2.php" method="get" target="pdf_viewer">
<input type="text" name="titel">
<button height="10px" width="30px" type="submit" name="create_pdf_btn" value="create worksheet">create worksheet</button>
</form>
<!-- Initially, frame is blank, will update to PDF generation URL on form submit.
I created a special empty HTML file for this purpose. -->
<iframe name="pdf_viewer" id="pdf_viewer" src="blank.html"></iframe>
</body>
and then in test2.php you simply generate your PDF inline as you already are.
2) Generate the file on your server and use the AJAX response to pass where the saved PDF is. This answer below opens a new window with window.open but you can simply replace that window.open line with one that updates document.getElementById('pdf_viewer').src with the new URL.
https://stackoverflow.com/a/46529459/395384
3) Return Base64 and use a lengthy data URL. For an example of that, see here:
https://stackoverflow.com/a/35197585/395384

How to call one javascript variable to another javascript file

I have an HTMLForm which on click forward me to new HTML page i have Two JS files for each HTML
What i am doing and trying to achieve is :-
On 1st HTML when i click search button i am storing the values of input field and select field in different variables
What I am trying to achieve is when on search new page loaded I want to use that new variable into my new JavaScript
I have Two HTML files also
here is the code of my file1.html
<form id="formId" action="file2.html">
<div class="container">
<h4>Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>Outlets:</h4>
<select name="outlet" id="myselect">
<option>ALL</option>
</select>
<div>
<br>
<button id="btn-search" class="btn btn-default" type="submit">
<i class="fa fa-search"></i> Search
</button>
</div>
</div>
</form>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
In This HTML i have a form having one date field and one select field
On clicking submit Button I am Storing the values of date and Outlet into a variable in my JavaScript file which is JavaScript1
**Here is my JavaScript1 file **
$(document).ready(function() {
$("#btn-search").click(function(){
var currentlyClickedOutletform = $("#myselect").find(":selected")[0].textContent;
var currentlyClickedStartdateform= $("#startdate").val();
$.ajax({
url : "LinkReportMain",
method : "POST",
data : {
Outletlink : currentlyClickedOutletform,
Fromdatelink : currentlyClickedStartdateform,
},
});
});
});
var currentlyClickedOutletform and var currentlyClickedStartdateform are the two values i want to use in my new JavaScript file which is JavaScript2
my file2.html is
in this file i am just populating an HTML table so i only have an div tag inside
<div id="tbl"></div>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
<script type="text/javascript" src="JS/JavaScript2.js"></script>
And finally my JavaScript2 is
in this file I want to use the values of first Javascript file
$(document).ready(function() {
alert(currentlyClickedOutletform)
$('.loader').show();
$('.overlay').show();
$.ajax({
url: "LinkReportMain",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
fromdate: $("#startdate").val(),
todate: $("#enddate").val(),
outlet: $("#all").val()
},
success: function(data) {
let formatedData = formatData(data);
renderTable(formatedData);
$('.loader').hide();
$('.overlay').hide();
}
});
});
NOTE to see the code of JavaScript2 file please see the snippet its not working but my code was not getting formatted so I have put that into snippet
So what I am trying to achieve is to use the Variable of JavaScript1 into JavaScript2
i am doing it right but its not working any one out here who can guide em please, it would be very helpfull
Without localStorage
First set type="button" of you search button or prevent form submit by e.preventDefault(); on click event.
$("#btn-search").click(function(){
e.preventDefault();
// your other code
//code to redirect to another html page
var queryString = "?para1=" + currentlyClickedOutletform + "&para2=" + currentlyClickedStartdateform;
window.location.href = "page2.html" + queryString;
})
for other page script:
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var oldParam = queryString.split("&");
var param1 = oldParam[0];
var param2 = oldParam[1];
Now you can use param1 and param2.
**localStorage ** :
in first page store object :
localStorage.setItem("outletFrom",currentlyClickedOutletform);
localStorage.setItem("startDate",currentlyClickedStartdateform);
in seond page get data:
var currentlyClickedOutletform = localStorage.getItem("outletFrom");
var currentlyClickedStartdateform= localStorage.getItem("startDate");

Javascript of selected php file won't load when using JQuery's load(file.php) method

I have a master container php file with a div container. Initially, the div container doesn't have any content or html children by default when page is loaded. I use JQuery to load php files to this div container when the user clicks a navigation item in the navbar.
landingpage.php
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<div class="div_dashboardLabel" id="dashboard_Label">
<h2 id="label_Dashboard">Admin Dashboard</h2>
</div>
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
<!-- end of wrapper-->
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
landingpage.js
/* GLOBAL VARIABLES WITHIN THIS DOCUMENT*/
var div_content_container = $("#content_container");
var navitem_dashboard = $("#admin_dashboard");
var navitem_admin_account_management = $("#admin_accountmanagement");
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
var logout = $('#logout');
/* END */
$(document).ready(function(){
loadDashboard(); // dashboard is loaded as default view.
navitem_admin_account_management.on("click",loadAccountManagement);
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php';
div_content_container.html('');
div_content_container.load(url);
}
Everything works as expected for landingpage.php which uses landingpage.js for the front end. No problem.
The problem is when admin_accountmanagement.php file is loaded in div_content_container. The JS of admin_account_management.php doesn't seem to bind to elements:
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php'; // has its JS file
div_content_container.html('');
div_content_container.load(url);
}
For example, let's take url which is 'view/admin_accountmanagement.php' This page gets loaded within div_content_container when user clicks a navbar item Account Management
as in
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<!-- view/admin_accountmanagement.php loaded here -->
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
There are no problems displaying the page or replacing the current element contained in the div_content_container. The problem is, the JS file attached to view/admin_accountmanagement.php doesn't seem to apply when view/admin_accountmanagement.php page is loaded in div_content_container
The view/admin_accountmanagement.php is loaded but the click events binded to the elements of view/admin_accountmanagement.php doesn't work. I know this because I tried to display an alert() message on $(document).ready()
admin_accountmanagement.php
<body>
<div>
<button class="button" id="btn_AddUser">
Add New User
</button>
</div>
<script src="js/admin_accountmanagement.js"></script> <!-- this JS doesn't seem to get binded when this page is loaded in the div_content_container -->
</body>
admin_accountmanagement.js
var btn_add_user = $('#btn_AddUser');
$(document).ready(function(){
alert("TEST"); //doesn't work no alert message.
btn_add_user.on("click",test); //doesn't work no alert message
});
function test(){
alert("testing"); //doesn't work. no alert message
}
I'm only able to display the page but when I click on the <button id="btn_AddUser"> nothing happens.
How can I solve this given the how I structured the loading of pages to div_content_container?
Thanks in advance.
Change your admin_accountmanagement.js to
var btn_add_user = $('#btn_AddUser');
alert('Account management js loaded'); // this should show alert
$(document).on("click",btn_add_user,test);
function test(){
alert("testing"); //doesn't work. no alert message
}
This method works because the binding is not dependent on "document ready" as document ready has already been fired when you loaded the parent page for the first time
#jordan i agree with #Magnus Eriksson as it is better to bind it on('event','selector','function') but make use of .off() before your .on() as you are playing with dynamic content which may cause multiple binding of the function. And if you are still not able to get the binding event to work you can try injecting the .js file in your page's head section after the load of your content like: $('head').append('<script src="admin_accountmanagement.js"></script>'). With your load() function in your js to bind the click event.
Or, your use the below code snippet:
function LoadContent()
{
var url = 'view/admin_accountmanagement.php';
var jssrc = 'js/admin_accountmanagement.js';
div_content_container.html('');
div_content_container.load(url);
if($('head').find('*[src="'+jssrc+'"]').length==0)
{
//the below approach have some consequences related to it as you will not be able to see the injected js in your developers tool's Sources(in chrome).
$('head').append('<script src="'+jssrc+'"></script>');
}
}
and then on your .js will look like this:
var btn_add_user = null;
$(window).load(function(){
alert("TEST");
btn_add_user = $('#btn_AddUser');
btn_add_user.off('click').on("click",test); //use .off('event') if load() is being called multiple times.
});
function test(){
alert("testing");
}

jQuery load page into <div> issues

I'm using the following code to load a page into a <div>. It works fine except it's not supposed to load all links into the <div>.
<script type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("a").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#output").html(response);
}
});
return false;
});
});
</script>
<div>[ <a href="execute.php?cmd=test1">link 1</a] [ <a
href="execute.php?cmd=test2">link 2</a] [ <a href="mypage.com">link
3</a>]</div>
<div id="output"></div>
When I click link 3, used to go to the homepage, it opens the homepage in <div id="output"></div>.
Any idea why this happens?
You are assigning the click event to the a element, so all links will load the url inside the output div. You need to specify which elements to assign the click event, maybe by specifying a class.
$j("a.loadindiv").click
<a class="loadindiv" href
Hope this helps...
Link 3 is making a request to "mypage.com" and taking the html that it returns and outputting it into the 'output' div. You are making an AJAX call to the homepage and it is serving up the page to you.
Rather than having all the elements use the AJAX function you might want to consider doing:
<script type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j(".ajaxLink").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#output").html(response);
}
});
return false;
});
});
</script>
<div>[ <a href="execute.php?cmd=test1" class="ajaxLink">link 1</a] [ <a
href="execute.php?cmd=test2" class="ajaxLink">link 2</a] [ <a href="mypage.com">link
3</a>]</div>
<div id="output"></div>

How do I get past the jQuery error "$ not found error"?

MAIN WINDOW
// some javascript
//some html
//here ajax-call to load all divs
//all divs hidden by default
//based on user choice(from select option), show selected group of divs
//click any shown div to call corresponding popup
POPUP WINDOW
//edit contents of that div.
//on close i need
1. refresh main window to load all divs
2. select the previously selected user option(from select option)
3. show corresponding divs only
4. most important is i have to give the user the main page,
where they clicked the div before(not the page starting always!)
I tried and i am left with " $ not found error ". any ideas..? suggestions?
this is the main window
<script type="text/javascript" src="jquerymin.js"></script>
<script type="text/javascript">
var visible_status=0;
function selectFn(sno){
if(sno==1){
$('#id2').hide();
$('#id1').show();
visible_status=1;
}else if(sno==2){
$('#id2').show();
$('#id1').show();
visible_status=2;
}
}
function popitup(url) {
newwindow=window.open(url+'?parent_status='+visible_status,'name');
if (window.focus) {newwindow.focus();}
return false;
}
</script>
<select name='optionw'
onchange="selectFn(this.options[this.selectedIndex].value);">
<option value="">Select</option>
<option value="1">Div1</option>
<option value="2">All</option>
</select>
<div id='id1' style="display:none;">DIV1</div><!--by ajax i am loading-->
<div id='id2' style="display:none;">DIV2</div><!--these divs-->
<button onclick="popitup('popup.php');">popUp</button><br><!--and these-->
popupwindow
<script type="text/javascript" src="jquerymin.js"></script>
<script type="text/javascript">
var parent_status='<? echo $_GET[parent_status];?>';
function closePopup() {
window.opener.history.go(0);
//alert('going to call parent selectFn('+parent_status+')');
window.opener.selectFn(parent_status);
self.close();
}
</script>
...Here editing a part of the main page content...
<input type=button value=close_popup onclick="closePopup();">
If i remove the comments in the closePopup function , it works as expected. Any help to make it work without commnted line.
I would suggest that perhaps you're not linking to the jQuery library properly or have it linked in the wrong order. Could you provide more details as to what you're asking? Do you want the code to do this, or are you just asking about the jQuery object not being found?
get firebug plugin for firefox. load your page .. go to firebug console .. type $ and if it doesnt say 'function()' you haven't included the jQuery library properly
I'm trying to understand your question; it's very unclear what you're describing. Is the code you're showing coming from your web browser once you've loaded it (by viewing the source) or is it prior to being evaluated on the server?
What happens if you change this line in the popup:
var parent_status='<? echo $_GET[parent_status];?>';
to this:
var parent_status=1;
According to what I have understood here is the code below and check it if this works for you:
Paste this code inside main window:
<?php if(isset($_GET['parent_status'])): ?>
$(document).ready(function(){
selectFn(<?php echo $_GET['parent_status'] ?>);
})
<?php endif ?>
Below this code:
function popitup(url) {
newwindow=window.open(url+'?parent_status='+visible_status,'name');
if (window.focus) {newwindow.focus();}
return false;
}
And, replace the closePopup function inside popup window with this code:
function closePopup() {
var href = window.opener.location.href;
if((pos = href.lastIndexOf('parent_status=')) >= 0)
{
var patt = new RegExp('parent_status=' + parent_status);
href = href.replace(patt, 'parent_status='+parent_status);
} else {
href = window.opener.location.href + '?parent_status=' + parent_status
}
window.opener.location.href = href;
self.close();
}
Hope this helps.

Categories