Post JSON to PHP and then trigger a file download from PHP? - php

I'm thinking about a webpage that posts json object to a PHP page, and then the PHP page generates some data and exports the data to a local file. Because in the first step, the data will be too large to pass through URL, I need to use JSON. However, when I passed the JSON object to PHP in an AJAX way, no downloading is triggered. I'm wondering how this downloading can be triggered.
//the code will not trigger a download from PHP
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("POST", "export.php");
xmlhttp.setRequestHeader("Content-type", "application/json", true);
xmlhttp.send(JSON.stringify(obj));
I can receive the echoed data in JavaScript, but creating local files in JavaScript is more complex than in PHP.

Don't use xmlhttprequest, just submit the form with your json to PHP and in PHP specify the correct Content-Type.

I found the solution: create a form and use JavaScript to dynamically create hidden input fields. And use a submit button to post the form to the php file in a newly opened window.

Related

How to Convert jQuery ajax success data to a PHP variable

I'm sending data to a php page for processing through jQuery and ajax and as result I will get
success: function(data){
mydata = data;
}
my data is an url that looks like mydata = https://myurl.com. Now I want to set mydata to a php variable and use it again inside another function in the main page, means: to set $url = mydata;.
How can I do that?
Thanks,
You can do that using Post via a from, GET via a query string
or you can use cookie like in this solution
how to assign javascript variable value to php variable
You can send the mydata variable to PHP by calling an XMLHttpRequest() via AJAX.
For example
var ajax = new XMLHttpRequest(); // Create new request
ajax.open("POST", "mainpage.php"); // Open the file where you want to send it with POST
ajax.send("mydata="+mydata); // Send mydata variable to PHP
Then in PHP you can check for the variable mydata
if(isset($_POST['mydata'])){
// do something
}
PHP scripts execute when you open a file and before everything else.
Ajax calls exectue when the Javascript is completely loaded. (After php).
So you cant do it.
could you give me more detail about what do you want to do?

Do AJAX functions have to be in the same file calling them?

I am able to call javascript functions from a JS file without any issues. When I move AJAX functions into the same file then the functions cannot be called. Do AJAX functions require that they are in the same file that they're called from?
Home.html
<button onclick=scale(id)>scale</button>
<button onclick=save(id)>Save</button>
Javascript.js
function scale(id){
//scales the element with the given id
//works
}
function save(id){
//Does not work unless in Home.html file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "SaveValue.php?id="+id, true);
xmlhttp.send();
SaveValue.php
//Sends value to mysql db
-Update-
When I moved the AJAX function into a different JS file by itself, and linked it in the html file, everything worked.
JavaScript functions which perform Ajax options are no different from any other function as far as loading them is concerned.
There is no requirement to include the function inline in the HTML document.
You do, of course, still, need a <script> element to load them (or resort to things like fetching the script data with XMLHttpRequest and running it through eval — which is not recommended!).
If you have a problem, then it is most likely due to the <script> element failing to load the file. The most common reasons for this are revealed by the developer tools in your browser:
The URL is wrong (the Network tab will tell you that you aren't getting a 200 OK response)
The Content-Type is not application/javascript (or the legacy text/javascript). The Console will report an error and the Network tab will show the Content-Type.
The HTML for the <script> element is wrong or in the wrong place (this will often be picked up by the use of a Markup Validator).

Accessing ArrayBuffer from PHP $_POST after xmlHTTPrequest send()

I'm following the tuitions on XMLHttpRequest 2 from :
https://developer.mozilla.org/en/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data
and
http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-send-arraybuffer
They're great tutorials for the client side, and here is a working extract from my script:
var imagebuffer = new ArrayBuffer(size); // create the readonly memory buffer
var imagedata= new Uint8Array(imagebuffer); // create a view to manipulate data
// do some cool stuff with imagedata
var exchange=new XMLHttpRequest();
exchange.open("POST",url,true);
exchange.send(arraybuffer);
So far so good, and I can see from the both client and server control panels that plenty of data is being transferred.
Here's my problem: how do I access the ArrayBuffer with PHP at the server?
I'm used to the $_POST superglobal wanting parameters passing from a HTML form so it can be accessed as an array but I can't find any reference for how to access this binary array and stick it in my MySQL database.
Okay - I've figured it out. My server side PHP opens with:
$data = file_get_contents('php://input');
$mysql_blob = base64_encode($data);
which is now in a format ready for inserting (for example) into MySQL as a BLOB format.
Works like a charm!

Images generated by JavaScript Canvas API aren't viewable when saved?

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));

How to insert a PHP dropdown in a HTML / Javascript page

Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;

Categories