How to render content on dompdf after ajax call using codeigniter? - javascript

<script>
$(document).on("click",".pdf_sheet", function(){
var subjectID = $("#subjectID").val();
var session = $("#SessionFrom").val()+"-"+$("#SessionTo").val();
var courseID = $("#classesID").val();
var yearsOrSemester = $("#yearSemesterID").val();
$.ajax({
type: 'POST',
url: "<?=base_url('student/sheetPDF')?>",
data: {"subjectID":subjectID,"session":session,"courseID":courseID,"yearsOrSemester":yearsOrSemester},
cache: false,
success: function(data) {
}
});
});
</script>
Controller:
function sheetPDF()
{
$subjectID = $this->input->post('subjectID');
$session = $this->input->post('session');
$courseID = $this->input->post('courseID');
$yearsOrSemester = $this->input->post('yearsOrSemester');
$data['subjectID'] = $subjectID;
$data['session'] = $session;
$data['courseID'] = $courseID;
$data['yearsOrSemester'] = $yearsOrSemester;
$data['award'] = $this->classes->award($subjectID,$session,$courseID,$yearsOrSemester);
$this->load->view('sheet',$data);
$html = $this->output->get_output();
$this->load->library('pdf');
$this->dompdf->loadHtml($html);
$this->dompdf->render();
$this->dompdf->stream("Awardsheet.pdf", array("Attachment"=>1));
}
I am using DOMPdf to convert html to pdf file. Now, What is happening when I click on pdf_sheet class then content are showing but not rendering on html. So, How can I show view file on pdf file? So, How can I do this? Please help me.
Thank You

Ajax call doesn't render application/pdf.
Instead of ajax use web form to render PDF.
$(document).on("click",".pdf_sheet", function(){
var subjectID = $("#subjectID").val();
var session = $("#SessionFrom").val()+"-"+$("#SessionTo").val();
var courseID = $("#classesID").val();
var yearsOrSemester = $("#yearSemesterID").val();
var form = '<form id="static_form" action="<?=base_url('student/sheetPDF')?>" method="post">';
form += '<input type="hidden" name="subjectID" value="' + subjectID + '">';
form += '<input type="hidden" name="session" value="' + session + '">';
form += '<input type="hidden" name="courseID" value="' + courseID + '">';
form += '<input type="hidden" name="yearsOrSemester" value="' + yearsOrSemester+ '">';
form += '</form>';
$('body').append(form);
$('#static_form').submit();
});

Related

How to use form data in codepen

I'm working on the wikipedia viewer for free code camp and I'm trying to make the search bar work.
Ideally I would just like to have the user type in some text, then have that become a string in my code when the user hits submit. This is the html for the search bar so far
<form method="get">
<input type="text" placeholder="Search articles" class="srchbox" name="Search" id="searchbar">
<button type="submit" class="btn">Search</button>
</form>
and the api setup I have to make the search
var apiURL = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&generator=search&search=" + textInput;
$(document).ready(function() {
$.ajax({
url: apiURL,
dataType: "jsonp",
success: function(data) {
var wikiAPI = JSON.stringify(data, null, 3);
console.log(wikiAPI);
var wikiHTML = "";
for (i=0; i < data[1].length; i++)
{
wikiHTML += ("<a href =\"" + data[3][i] + "\" target=\"_blank\">")
wikiHTML += "<div class = \"wikicontent container-fluid\" style = \"color:black;\">";
wikiHTML += ("<h2>" + data[1][i] + "</h2>");
wikiHTML += ("<h3>" + data[2][i] + "</h3>");
wikiHTML += "</div></a>"
}
$("#articles").html(wikiHTML);
I'm a bit lost on how to pull this off so any help would be great. Thank you!
You can use submit event, set query to #searchbar .value
$("form").on("submit", function(e) {
e.preventDefault();
if (this.searchbar.value.length) {
var url = "https://en.wikipedia.org/w/api.php?format=json"
+ "&action=opensearch&generator=search&search="
+ this.searchbar.value;
$.ajax({url:url, /* settings */});
}
});

submitting arrays to php via ajax

I am having issues figuring out how to submit a form via ajax that has items with the same name(this form is dynamically created and has to use the same names for some fields).
This is the JS code that I have
<script>
var toggle123 = function() {
var chair = document.getElementsByName('chair[]');
var item1 = document.getElementsByName('item[]');
var price = document.getElementsByName('price[]');
var table = document.getElementById('table');
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'table='+table+'';
for(i=0;i<item1.length;i++)
{
dataString += + '& item1[]' + '=' + item1[i];
}
for(i=0;i<chair.length;i++)
{
dataString += + '& chair[]' + '=' + chair[i];
}
for(i=0;i<price.length;i++)
{
dataString += + '& price[]' + '=' + price[i];
}
if (chair == '' || item1 == '') {
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
var mydiv = document.getElementById('table1');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
I want it to submit to submit.php and also to hide the div that is open (table1).
I can get it to go to submit.php but I am not sure if the data is actually getting sent there or if it is just blank. It tells me there was an invalid argument for the foreach loop in submit.php.
Here is submit.php
<?php
include('dbconfig.php');
// Fetching Values From the post method
$table = $_POST['table_id'];
foreach($_POST["item1"] AS $key => $val) {
$chair = $val;
$price = $_POST['price'][$key];
$chair = $_POST['chair'][$key];
$query = mysqli_query($dbconfig,"insert into orders(table_id, price, item, chair) values ('$table', '$price', '$item', '$chair')"); //Insert Query
echo "Form Submitted succesfully";
}
?>
This is the javascript for the dynamic form....each time a button is clicked, this adds onto the form:
listholder.innerHTML += "Chair "+row.chair+"-<input type='hidden' id='chair' name='chair[]' value='"+row.chair+"' /><input type='hidden' id='table' name='table' value='"+row.table_id+"' /><input type='hidden' id='item' name='item[]' value='"+row.item1+"' /><input type='hidden' id='price' name='price[]' value='"+row.item1+"' />" + row.item1 + " - " + row.chair + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)<br>";
I think my main issue is probably forming the datastring that gets passed to submit.php. If anyone could help me figure this out, that would be great!
(P.S. toggle123 is activated via a button click (that works fine)

rails link_to delete without ujs, using only jQuery

I'm trying to do exactly what jquery_ujs is doing but, without ujs. I have one link app, just one, which posts to a destroy action. I want to avoid using ujs for performance purposes. I tried generating a form using jQuery when the link is clicked on submitting using ajax. The problem is, the action redirects the browser to logout. I am able to hit the controller just fine but nothing happens on the browser side. I'm aware button_to solves this as well, but i can't use a button.
I have hardcoded the form data for clarity
$(document).ready(function() {
var csrf_token = $('meta[name=csrf-token]').attr('content');
var form = $("<form action='/app/logout' class='logout-form' method='post' accept-charset='UTF-8'></form>")
var input1 = $("<input name=_method' type='hidden' value='delete'>")
var input2 = $("<input name=authenticity_token' type='hidden'>").val(csrf_token)
form.hide().append(input1)
form.submit(logout)
$("a[data-method]").click(function(event){
event.preventDefault()
form.submit()
})
function logout(event) {
$.ajax({
url: '/app/logout',
type: 'POST',
data: {_method:"delete", authenticity_token: csrf_token, action: "destroy", controller: "internal/logins" }
})
event.preventDefault()
}
});
The code above constructs a form, which is submitted on a click event
link_to("Logout", logout_path, :method => :delete)
An ajax post to a destroy action which redirects to another site causes CORS error. Solution is to construct a form, the same way button_to does and just use jquery submit.
var link = $("a[data-method]");
function submitForm(){
var csrfToken = $('meta[name=csrf-token]').attr('content');
var csrfParam = $('meta[name=csrf-param]').attr('content');
var form = $('<form method="post" action="' + link.attr('href') + '" type="hidden" class="logout-form"</form>');
var metadataInput = '<input name="_method" value="' + link.data('method') + '" type="hidden" />';
metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
form.append(metadataInput).appendTo('body');
form.submit()
}
link.click(function(event) {
event.preventDefault();
submitForm()
});
I realized I initially had my link_to function remote option set to true, which wasn't working. Just left it as is, add an on click listener and submit form when clicked, then preventDefault
link_to("Logout", logout_path, :method => :delete, class: 'logout')
I can't comment, but the first answer is correct, but has a bug: the link used in submitForm will only be the first link matched. Here's what my version looks like:
$('a[data-method]').click(function() {
var $link = $(this);
var csrfToken = $('meta[name=csrf-token]').attr('content');
var csrfParam = $('meta[name=csrf-param]').attr('content');
var $form = $('<form method="post" action="' + $link.attr('href') + '" class="u-hiddenVisually"></form>');
var metadataInput = '<input name="_method" value="' + $link.data('method') + '" type="hidden" />';
metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
$form.append(metadataInput).appendTo('body');
$form.submit();
return false;
});
Replace class: 'u-hiddenVisually' with whatever you use to hide the form.

Trouble with AJAX and Select

I m working with a project using an AJAX call and in my program I have a select list and I need to implement select2 but I can not do it. My code in my .js file is:
function selectAlumnos(){
$.ajax({
type : "GET",
url : lang + '../../../api/select_alumnos', //the list of data
dataType : "json",
data : {
cachehora : (new Date()).getTime()
}
}).done(function(response){
var html = '';
if(response.state == 'ok'){ //add html to the file view
html = '<select class="select_1" name="select-allalumnos" id="select-allalumnos" onchange="getIconLocation()" >'; //class to include in select2
html = html + '<option value="-1">...</option>';
for(var i in response.alumnos){
html = html + '<option value="' + response.alumnos[i].id + '" >' + response.alumnos[i].nombre + '</option>';
} //get the list of the data
html = html + '</select>'; // put the data in the list
}
$('#select-alumnos').html(html); //publish the info in the html file
});
}
In my html page for the view I have the select-alumnos part like this:
<label for="select-alumnos" class="select">Alumno:</label>
<span id="select-alumnos"></span> //here is the call in the AJAX
In this file (html for view) I have also put all the select2 paths to the required files, and I checked all the files are ok, also I have included the class (same class in my js file):
$(document).ready(function() {
$(".select_1").select2();
});
</script>
What am I doing wrong because I can not get the select2 format in my list...?
you're calling select2() on .select_1 before its created. Do it after you've created the element (put it in the done function)
.done(function(response){
var html = '';
if(response.state == 'ok'){ //add html to the file view
html = '<select class="select_1" name="select-allalumnos" id="select-allalumnos" onchange="getIconLocation()" >'; //class to include in select2
html = html + '<option value="-1">...</option>';
for(var i in response.alumnos){
html = html + '<option value="' + response.alumnos[i].id + '" >' + response.alumnos[i].nombre + '</option>';
} //get the list of the data
html = html + '</select>'; // put the data in the list
}
$('#select-alumnos').html(html); //publish the info in the html file
$(".select_1").select2();
});

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources