Opening the PDF file onclick of a button with AJAX - javascript

I want to open PDF File onclick of a button. I tried doing this with AJAX but it doesn't open the PDF file.
I keep receiving this alert everything I clicked the View PDF button.
Here is the my code for AJAX:
function viewPDF(id){
$.ajax({ url: "viewCrf.php",
data: {'idd' : id},
type: "POST",
success: function (data) {
}
});
}
The AJAX code above will be trigger after the clicked of this button:
<td><input id='$idd'
type='button'
value='View PDF'class='btn btn-primary' onclick='viewPDF(this.id)'
target='_blank' ></td>
The viewCrf.php contains the code for generating the PDF. Uses POST method to get the value passed by the AJAX then get the data from the database
$id = $_POST['idd'];
$q = $db->query("SELECT * FROM crf where col_ID = ".$id);
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$last = $r['col_ln'];
$first = $r['col_fn'];
$middle = $r['col_mi'];
$civilstatus = $r['col_civilstat'];
$sex = $r['col_gender'];
$dob = $r['col_bday'];
}
My problem here is that, the PDF file isn't opening at all. Though the success part on the AJAX seems to alert something when I add alert(data).
This code supposedly should open a PDF file on the click of the button.

Since using FPDF, you certainly have some PHP code looking like this.
If you didn't specifed any aguments to output(), it produces inline HTML.
Reference about the output method here.
So, this should work:
<td>
<input id='$idd' type='button' value='View PDF'class='btn btn-primary' onclick='viewPDF(this.id)' target='_blank' >
</td>
<div id="pdfResult"></div>
<script>
function viewPDF(id){
$.ajax({ url: "viewCrf.php",
data: {'idd' : id},
type: "POST",
success: function (data) {
$("#pdfResult").html(data);
}
});
}
</script>

I change the button to an href instead and use GET METHOD.
<td>".$result['col_ID']."</td>
<td>".$result['col_fn']." ".$result['col_ln']."</td>
<td><a href='viewCrf.php?idd=".$idd."' type='button'
value='View PDF'class='btn btn-primary'
target='_blank' >
</td>

In your viewCrf.php file, you must edit headers for say that's a PDf file ( and not show the pdf code.)
<?php header('Content-Type: application/pdf');

Related

Can't pass the value in php function using ajax

I created the function for my site the users will click the images according to the clicked image I showing the clicked image details so I created the onclick function and I passing that image ID using the ajax function I passing the image ID in PHP file and get that ID into post method and same time passing that variable into PHP class function. My issue is inside the script ID is coming but php file I can't get that variable I don't understand what is the issue. Please help me to find out this issue.
This is the clickable image with onclick function
<div class=\"col-md-3\">
<div class=\"single-new-trend\">
<a href=\"#\" id='BandChangeImg$BraproId' onclick='ImageChange($BraproId);'>
<img src=\"$BraProImg\" alt=\"$BraProName\"></a>
</div>
</div>
This is my ajax script
function ImageChange(x) {
var BrandName = x;
alert(BrandName);
$.ajax({
url: 'validate/brandImage.php',
method: 'POST',
dataType: 'json',
data: {BrandId:BrandName},
success:function(data){
//alert(data);
if($.trim(data))
{
alert("Success!");
}else{
alert("Failed!")
}
}
});
}
Last My PHP file
<?php
include("../db/mySqlDBi.class.php");
$DBConn = new mySqlDB;
$BrandId = $_POST['BrandId'];
include("../classes/personlized.class.php");
$personlized = new personlizedClass;
$result=$personlized->DisplayBrandProductDetails($BrandId);
echo "<script>alert('12334');</script>";
?>
You have
dataType: "json",
in the $.ajax call. jQuery will try to parse the response as JSON, and will get an error if this fails.
The script is sending
echo "<script>alert('12334');</script>";
That's HTML, not JSON, so the above error happens.
Either change it to dataType: "html" or change the PHP to something like
echo json_encode("Brand is $BrandId");

Not able to POST Variable to Another Page (PHP, Javascript, AJAX)

I have a while loop (inside the "searchvessel.php") that display the content of a query and have a button "upgrade" for each record of that query.
`while($fetch = $read->fetch_array()) {
?>
<tr>
<td id="1" style="display:none;"><?php echo $fetch['VesselID']?></td>
<td id="2"><?php echo $fetch['VesselName']?></td>
<td><input type="submit" class="button" name=<?php echo $fetch['VesselID']; ?> value="Upgrade"/></td>
</tr>`
This "Upgrade" button when click will call to a Javascript code that use the value inside the tag name to pass to another page using AJAX.
<script type = "text/javascript">
$('.button').click(function(){
alert($(this).attr('name'));
$.ajax({
type: "POST",
data: {
name: $(this).attr('name')
},
url: "vesselrecord.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
complete: function(){
window.location.href = "vesselrecord.php";
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
});
</script>
I were able to prompt/alert the value of vessel identification using the "alert($(this).attr('name'));" then
Move/Transfer to the "vesselrecord.php
But inside the "vesselrecord.php" there is no value in the $_POST['name']. Looks like there is an issue on my ajax code. Can you guide me on this? TIA.
Below is my code inside the "vesselrecord.php"
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vessel_id = strip_tags($_POST['name']);
}
When you change the location of the window, you make a $get request not $post, that is why you are not getting any value $_POST['name'].
You can change the location from-
window.location.href = "vesselrecord.php"
to-
window.location.href = "vesselrecord.php?myquerystringdata=" + $(this).attr("name");
and then on you php file you can write code to get value from query string.
'name' is nested within 'data'. Maybe you need to access data.name? I'm more used to JS than PHP so I'm not sure how to express this. Hope this helps.
data:{
name:'Al'
}

ajax - save javascript value to php

After hours of trying to get this to work, i want to ask you :)
So i have a php Page that can display files from a server. Now I can edit
the files with a editor plugin.
Textarea is the tag where the editor gets rendered.
To save the changed text from the editor, I have a button that gets the innerHTML from the surrounding pre tag of the text with javascript.
I now want to pass that variable via ajax to a php variable on the site get.php,
so I can save it locally and send it to the server.
The problem is, that there is no reaction at all, if i click the "Save" button. I tested a lot of answers from similar ajax functions here, but none of them gave me a single reaction :/
php main
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
...
echo "<textarea><pre id='textbox'> ";
echo $ssh->exec($display);
echo "</textarea></pre>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
var show = document.getElementById('textbox').innerHTML;
$(document).ready(function() {
$('#butt').click(function() {
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
}
});
});
});
</script>";
...
get.php
if (isset($_POST["variable"])){
$show =$_POST["variable"];
echo $show;
}
Edit:
This is the actual working state:
echo "<textarea id='textbox'><pre> ";
echo $ssh->exec($display);
echo "</pre></textarea>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
$(document).ready(function() {
$('#butt').click(function() {
var show = document.getElementById('textbox').value;
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
},
});
});
});
</script>";
You have an error in the data: {'variable': show)} part. It should be: data: {variable: show}. Also you should use Firebug or Firefox developer tools for these kind of problems. A lot easier to see whats wrong.
I would suggest small changes to see if everything is running as it should.
I can see that pre tag is behind textarea closing tag - try to change it
Try putting var show = document.getElementById('textbox').innerHTML; inside of the ,,butt" function
Then I can see your problem here data: {'variable': 'show')}, - you are sending 'show' as a string - remove quotes to send it as a variable which will appear as a POST value in PHP site.
with this should work:
$.ajax({
type: 'POST',
url: 'get.php',
data: {variable: show)},
success: function (data){
alert(data);

How do i send parameter in ajax function call in jquery

I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});

PHP Ajax button press conundrum

I have been trying to have a button execute a PHP script on a page and refresh just a div tag without any success. When I remove the $ajax part of the script my buttons change state but when I add the ajax part again nothing happens.
I need to load some content from a PHP file and then change the button's and div tags state. Some help will be very much appreciated as I can't seem to find the problem.
<div id="noah-content">
<script>
$(document).ready(function() {
$("#ON'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = true;
document.getElementById("OFF'.$id.'").disabled = false;
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src");
}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
$("#OFF'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = false;
document.getElementById("OFF'.$id.'").disabled = true;
});
});
</script>
<img src="images/about.png" alt="image" id="myimg" />
<input type="submit" class="ON" id = "ON'.$id.'" value=" ON " name="submit"/>
<input type="submit" class="OFF" id = "OFF'.$id.'" value=" OFF " name="submit" disabled="disable"/>
</div>
Lets start with evaluating your php:
In order to run your php you have to open php tags:
$("#ON<?php echo $id ?>")...
Replace it everywhere you want your id to appear. For debugging, open your page source in the browser and see what is being generated:
Example:
<input type="submit" class="ON" id="ON<?php echo $id ?>" value="ON" name="submit"/>
Firstly, your ids for your html tags, and the way you reference them in js, seem odd (though still perhaps valid when dropped into js or html as strings). Looks like your trying to reference a php value in an improper way in html and js.
Second, are you getting any errors on your javascript console? Does the ajax query complete (i.e. do you get the alert message)? Check your JS console because that will tell you something more than 'nothing happens'
Also
I usually use the success option for ajax rather than the done method. Personal choice.
You also have a syntax error after $(this).attr("src");. The semicolon indicates the end of a line of code usually, and you put it after an element in your array/object declaration for your data.
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src") //Removed the semicolon that was here
},
success: function(data){alert(msg)}
});

Categories