This question is more of how to logically approach this obstacle instead of correcting code.
I have a very large application which is based on a 'Wizard'. Users input their data, continue on, data is saved, etc.
In the end, the user needs to be able to print a PDF of all this collected data from the Wizard process. I don't want to use the data from the database, but capture the data 'currently' in the Wizard.
I've been able to make a hidden form on the page, jquery creates new hidden inputs with small strings of data. Then when the user clicks 'print' the data is sent via post and is used in the pdf... but I need a way to send large amounts of data.
So, to make my life easier, is it possible to send an entire specified div or table to TCPDF to use as an htmlcell ?
P.S. jQuery, HTML, PHP are at my disposal.
I don't know this methode is correct or not.But it works..Send data through ajax as an array to server
Create pdf . Save pdf server side folder and open the pdf in another window
**// Post data to server
$.ajax({
type:"POST",
url:"//path",
data:"&arrDataArray="+arrDataArray,
success:function(Results){
//if preview then open the pdf in a new tab
if(Results=='PREVIEW'){
highLightPrintSettingsTab(strCurrentTab);
$(".busyLoading").hide();
window.open("../pdffiles/example.pdf","_blank");
}
}
});
Here is what I ended up doing. Works like charm.
function submitData(url, method, data) {
var $form = $('<form></form>')
.attr('action', url)
.attr('method', method)
.attr('target', '_blank')
.appendTo('body');
for (var i in data) {
if (!data.hasOwnProperty(i)) continue;
$('<input type="hidden"/>')
.attr('name', i)
.val(JSON.stringify(data[i]))
.appendTo($form);
}
$form.submit();
}
});
Where 'data' will be the array(s) you wish to send to wherever, in my case the controller for tcpdf. {multi, data} for plural.
Related
all my problem is that I wanna send data from my website to this website's page :
http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw
how I can do this ? and is it possible ? cuz as I have seen this website forms validation's all in javascript and dunno how to handle it ?
thanks.
This is how you can do that, just make a testPosting.html file,
Create your form using all the inputs that are required to send.
See the screenshot for the posted fields.
This data is posted when i submitted the form after filling it.
Now as you can see 14 fields are posted, so you need to make 13 inputs and 1 textarea.
use click function for the button of submit e.g
$('#buttonID').click(function(e){
e.PreventDefault();
//store values of inputs in a variable
var data = {
FirstName = $('#FirstName').val(); // you can more better then that if you know how
//Add the rest of the data
};
});
then you can use jQuery Ajax to send data.
$.ajax({
url: "http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw",
data:data, //this data will be the variable that you create in which all the forms inputs datas are stored.
type: "POST"
}).done(function(result) {
//do stuff if some result has returned
});
i just gave the rough idea.
Oh you must use this line in script on top of you JS scrips
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
My code is not perfect but you get the idea what i am trying to say, you might can start from here, and do stuff of your own..
I want to transfer the varible "content" to php and then a mysql database, but everything I have tryied fails. The data is comming from a iframe and the code looks like this
function getContentFromIframe(Textfield)
{
var myIFrame = document.getElementById("Textfield");
var content = myIFrame.contentWindow.document.body.innerHTML;
if (content != "")
{
alert('bla, bla, bla ' + content);
content = 'The inside of my frame has now been saved';
myIFrame.contentWindow.document.body.innerHTML = content;
}
else{
alert('bla bla bla ');
}
}
Sending data from the browser to the web server is not such a simple task. I would suggest you read up on AJAX. Basically AJAX will allow you to send asynchronous request to the server from you JS code. The data you want sent is added as POST body or as query parameters in the URL you request, depending on the size of the data.
Also using AJAX without some extra library (Prototype/JQuery/etc) is not very easy, due to cross-browser issues. Check those out too.
Save javascript data in hidden field and get hidden field in php code
You will need to perform a request that interfaces with your server in some way. You can use a form submission, or put the variable in the query string of a URL and navigate to it (using window.location). Or an AJAX request.
I needed recently to set some $_SESSION vars from onSelect on a select menu. So basically, transferring Javascript value to PHP.
It's totally doable through AJAX, and I use the simple object inited in Javascript (no JQuery or other new fancy tools for cool programmers :))
You can actually do an AJAX request, via POST or GET (read docs on AJAX), and then in the .php file on which you do the request, init a $_SESSION var (with start_session() on) which you can then access in your PHP current page.
Basically, to shed some more light, when you trigger a Javascript event, that event triggers a POST / GET request on an external .php file which can save into a database or assign a $_SESSION var, but this is all done asynchronously, and quick, so the current PHP variables are still in effect :)
cheers
you can pass javascript variable like this
if (content != "")
{
var url = "your phpfile ?content="+content;
$.ajax({
url : url,
type: "post",
success:function(response)
{
document.getElementById("your field").innerHTML = response;
}
});
}
You can use Jquery to invoke a post request to a php page using AJAX and process it.
I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';
Full code can also be found here: https://gist.github.com/1973726 (partially version on jsfiddle http://jsfiddle.net/VaEAJ/ obviously couldn't have php running with jsfiddle)
I initially wrote some code which took a canvas element and saved it as an image (see working code here: https://gist.github.com/1973283) and afterwards I updated it so it could process multiple canvas elements but the main difference now is that the image data is passed through to my PHP script via jQuery ajax method rather than via a hidden form field.
Problem is the images appear to be blank. They are about 200kb each when generated so they obviously have some content but when you preview the image nothing shows and when I try and open the image in Adobe Fireworks or another photo application I can't open the file.
The image data appears to be coming through to the server fine, but I'm really not sure why now when I write the image using base64_decode it would mean the images that are generated would no longer be viewable? The only thing I can think of is that maybe the posting of data via ajax isn't sending all the data through and so it's generating an image but it's not the full content and so the image is incomplete (hence why a photo application can't open it).
When checking the post data in Firebug it suggests that the limit has been reached? Not sure if that's what the problem is?
The problem was actually with sending data via XHR. I was using jQuery ajax method initially and then I swapped it out for my own ajax abstraction but the problem was still occuring until someone on twitter suggested I use FormData to pass the data to the server-side PHP. Sample is as follows... (full code can be seen here: https://gist.github.com/1973726)
// Can't use standard library AJAX methods (such as…)
// data: "imgdata=" + newCanvas.toDataURL()
// Not sure why it doesn't work as we're only abstracting an API over the top of the native XHR object?
// To make this work we need to use a proper FormData object (no data on browser support)
var formData = new FormData();
formData.append("imgdata", newCanvas.toDataURL());
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveimage.php");
xhr.send(formData);
// Watch for when the state of the document gets updated
xhr.onreadystatechange = function(){
// Wait until the data is fully loaded, and make sure that the request hasn't already timed out
if (xhr.readyState == 4) {
// Check to see if the request was successful
if (checkHTTPSuccess(xhr)) {
// Execute the success callback
onSuccessfulImageProcessing(card, newCanvas, ctx, getHTTPData(xhr));
}
else {
throw new Error("checkHTTPSuccess failed = " + e);
}
xhr.onreadystatechange = null;
xhr = null;
}
};
```
If you are not having Cross Origin SECURITY_ERR's (which your Fiddle suffers from, but as long as your images are on the same server they will be fine), and you are getting some data so you are probably having problems with your PHP. From the PHP user notes, you have to replace the spaces with +'s to decode base64 that has been encoded with Javascript.
$data = str_replace(" ", "+", $_POST['imgdata']);
file_put_contents("generated.png", base64_decode($data));
I have no problem with submitting form data through AJAX, and display all that data in a separate div.
But how do I update the form itself with some new info based on server response?
In my case I have:
a form with many inputs, including a group of checkboxes
data from form is collected (with JQuery serialize) and sent to php script through Ajax.
I need to set a specific color for text near a selected checkbox.
I need to set that color not on client side, but based on server side script.
Please explain the correct logical process when need to update a form based on initial form data.
Server side, you can send back a json encoded variable like so.
echo json_encode( array('text_color', 'green') );
Then, on the client side, you can access this variable in the callback function.
$.ajax({
url: 'ajax/test.html',
dataType: 'json',
data: $('yourform').serialize(),
success: function(data) {
var color = data.text_color;
$('yourElement').css('color', color);
}
});
Alternatively you could send back a class and add that class to the element.
If you are using jQuery, you would send the data via AJAX (post/get) and then you would get the response from server script in plain text / json / xml format (your choice). In this case, if you need to return only color code, you can use plain text format. When you get the response, you can manipulate the data.
$.post("test.php", $('#form').serialize(),
function(returned_data_from_server_script) {
$('some dom for color').css('color', returned_data_from_server_script);
});