upload and process user selected file in html, javascript and php - php

I want to have a user select a file and then have php put the contents in db. Now the last part (processing the file in php) is easy. But is there a way I can process a user selected file whithout a new page load?
If I use the following:
<FORM ACTION="upload.php" METHOD="post" ENCTYPE="multipart/form-data">
<INPUT TYPE="file" NAME="somefile"><BR />
<INPUT TYPE="submit" NAME="submit" VALUE="Upload">
</FORM>
Page upload.php automaticaly loads after which I can insert the uploaded file in a database.
I would like to use a combination of javascript, php and xajax to process the file. I don't think something like this is possible:
<FORM ACTION="javascript:xajax_proces_file()" METHOD="post" ENCTYPE="multipart/form-data">
<INPUT TYPE="file" NAME="somefile"><BR />
<INPUT TYPE="submit" NAME="submit" VALUE="Upload">
</FORM>
Because the file is not uploaded when function xajax_process_file() is called. Or is it? I think I do not fully grasp the principle of uploads with javascript, html and php.
Any help and or clarification is much appreciated.

It may help to think of this as a two step process.
First, the user fills in the form and submits it - step one.
Second ( which is the default action ) the specified target file takes the input from the form and uses it to do whatever. You can almost think of a form "action" as a link - the default action of a link click is to display the result of the link. The same goes for a form action - display the result of a form action.
Now, it's possible via JavaScript to disable the default action of an element for a particular event. It is also possible via JavaScript to access a browsers HTTP mechanism to send/receive HTTP request (which is what every page request is - whether from your URL bar or a page link or a Google search result).
And that is what AJAX in simple terms is - using JavaScript to use a browsers HTTP mechanism to send requests to a web server and possible receive a response back without the use of a traditional click event. You then combine this with the use of JavaScript to "turn off" default actions and instead follow the action specified by you to get information from a server and add it to the page without ever having to refresh the page.
Many times to prevent the defualt action from taking place for a certain element, you return false in your code. The same goes for your form. Using javascript:
form.onSubmit = function() {
blah blah blah.....Use ajax to send the information to the form handler
return false; //Prevents the defualt action of the submit event
}
If you are really new to AJAX, I suggest you check out this tutorial and then this one. Lastly, I would recommend using a Javascript framework like jQuery to help you - it is awesome and does alot of great stuff, but also has easy and built in functionality for AJAX.
Here is another tutorial to do a form submit with no page refresh (uses jquery).

an alternative is to make the form directs the action to an iframe, after processing the query in the iframe, proceed by JS to clear the form of the father

Related

Input directly to the same page

I'm trying to find a way to input an image directly onto the same page, but I can't figure it out.
The image doesn't need to be saved when navigating away from the page.
I've tried:
<form action="#" method="post">
but I still can't figure out how to actually put it where I want it.
This might be really simple and I'm just overthinking it, but I've been googling for hours with no result.
You need to leave empty form action and specify enctype
Example:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file">
<input type="submit">
</form>
This will push image into $_FILES array in php. For uploading images you need to view http://www.w3schools.com/php/php_file_upload.asp
If I understand you correctly, basically what you are trying to do is impossible. (without ajax)
The basic way a web-site works is:
browser asks for a page
server sends back page.
If you're trying to change the page after it has been sent to the browser (i.e. add an image), then you need to do some work behind the scenes.
browser asks for a page
server sends back page with some javascript in it that allows fetching additional data from the server.
javascript asks for additional data from the server.
additional data gets added to the page.
Since javascript has no access to the local machine outside the browser sandbox you'll have to get the user/javascript to send the image to the server, and the server then has to send it back to your javascript (which can then embed it in your page)
jquery or similar is probably the way to go.
You'll need a page/script on your server to handle the upload and serving of the image file.
Alternative
A simpler method might be to have a file input field on a form in your initial page with no image, when the page is submitted, check the $_FILES variable (see move_uploaded_file) and now serve the same page this time with the uploaded file displayed. You could then delete the image file from your server if you need it only once.

Form Submit with Different Redirect Location than Action

Problem:I have an RSS feed. As some of you may know, RSS feeds do not always update promptly (I'm using FeedBurner) so I'd like to provide the option on my webpage to update the RSS feed. This is a simple process, and I just need to ping an address. The catch is this: I'd like to stay on the initial page, and ideally refresh it.
I've seen some "solutions" around with using hidden iframes, and javascript, Ajax, etc.. What I am wondering is if there is an elegant way to do this using php/html.
Below is a flowchart illustrating exactly how I would like the system to function.
EDIT:
Here is the simple form code which I currently have:
<form action="http://url.to.ping" method="post">
<input type="submit" value="Refresh" />
</form>
This is a standard form, performing an action on submit. I require now that the browsers destination (as seen from the user) is a different url than that in the action. It is worth noting that the action page is not in my domain, and is not part of a domain which I own or have access to.
Thanks!
What i meant was,
/contactme.php
once they've submitted and come back to the page is there any additional variables like
/contactme.php?thanks=1
basically is there anything to declare they have just submitted and come back to the original page, if so..
You could do;
<?php
if(isset($_GET['thanks']))
{
$pingServer = file_get_contents('http://www.the.server.to.ping.com/pingit.php');
unset($pingServer);
}
?>
at the bottom of the page and it'll just hit that page.
This way you are not relying on JavaScript being enabled and the user is not hopped around multiple URLs.
What I have done when I needed the landing page to be different from the processing page is add a JavaScript redirection where one would put their "thanks for filling out my form" material.
So, the code process would be:
user fills out form, clicks submit
server-side validation and processing.
if success then location.href(URL, 0); else do error case
user is redirected to new URL (your refresh page)

How can I pass data from one page to another using PHP and Javascript?

I have 3 buttons (image links, eventually will evolve to javascript or something better though)
Each of these buttons should send a value to a handler script, which does choice 1 if button 1 is pressed, choice 2, so on and so forth.
I'm wondering what the best way to do this is. I DON'T WANT TO USE GET. I'd like to use POST if that's possible but I don't think it is. I thought about cookies too but the problem is even though you can call a JS function to create a cookie via a link, you can't go to the PHP page for processing, within the same click can you?
It would work like the user clicks the button img, then it takes them to the handler script, but the handler redirects them back before they even know they were there.
Again this isn't a form, I need to do this with a hyperlink. I suppose I could just have a different page for each choice, but I don't think that's efficient.
Thanks!
If you want the variables to be passed using POST, you could create a form on the page, and have your links execute some javascript code at onClick. They'd set the variable to the desired value, then submit the form. The key lines would be something like:
document.getElementById("user_choice").value = 2; // or whatever the value for this link is
document.getElementById("my_form").submit();
You could turn your image links into:
<form method="post" action="blah">
<input type="hidden" name="function" value="function1" />
<input type="image" scr="whatever" />
</form>
This way they still look like images, but are actually post forms with whatever you want inside of them. That's the easy way anyways. The harder way would be to use AJAX.
In case you want to use JavaScript, have a look at jQuery. Using jQuery's click-method, you can easily handle clicks on elements:
Suppose you have this HTML:
<div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div>
Using jQuery, you can easily track click on the element labeled target:
$("#target").click(function() {
alert("Handler for .click() called.");
});
In case you don't want to POST or GET clicks directly, I'd propose to register jQuery click-handlers, which set JavaScript variable based on the clicked element.
Note, that jQuery's click-handler can be registered with any element, not only forms. Furthermore note, that e.g. the above click-handler does not POST or GET the page to the server.
Additionally, have a look here, on how to prevent the browser from submitting forms: What's the effect of adding 'return false' to a click event listener?
Even better than JavaScript is CoffeScript, which compile to JavaScript but makes live much easier. Give it a try!
what about AJAX? it's the best choice for your problem and the bonus part is you can use post too.

Submit information to url, but also open PDF

EDIT: This privately published page is what I need to work with. Password: stackOF
My client desires is to have her Wordpress blog show a MailChimp form on her home page as a gateway to a .pdf. I need the following behavior to occur when the user clicks "Submit":
execute the included MailChimp's javascript file; this ensures the form was properly filled, and then performs the sign-up to the newsletter list (don't need help with this part)
then show the user an informational PDF for download or viewing
EDIT: The logical order was flipped from when I originally posted this. The script should execute, and only if the script gets executed properly should the PDF show to the user
Note:
My experience level with HTML and PHP is 3/4, and with JS I am 2/4 EDIT: (seems more like 1/4 at this point lol). If my research is correct, PHP (server-side language) would be used to do that which the client wants.
Additional validation is not necessary beyond what MailChimp's script provides (it ensures that user has submitted a completed form) in this case (the client says it's ok if the e-mail isn't valid at all).
The .pdf URL and content is static, and simply needs to be shown, not generated.
----RESEARCH----
I know that the Mailchimp form uses the following line to actually submit the information, but I want to do the action mentioned below, as well as open the aforementioned .pdf:
<form action="http://*BLAH*.us2.list-manage.com/subscribe/post?u=*BLAHBLAH*&id=*BLAHBLAHBLAH*" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">
I am reading on other sites that I can conceivably point "action" to a .php file, but if there is a way to do this with javascript - since its using the .js file that I created for that already anyways, then I would be most happy. Barring that, I'll take what I can get..
You can try the following:
add an onsubmit handler on the mailchimp form like below:
<form onsubmit="runMyStuff(this)" action="http://*BLAH*.us2.list-manage.com/subscribe/post?u=*BLAHBLAH*&id=*BLAHBLAHBLAH*" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">
Your javascript function:
function runMyStuff( o ) {
// open the pdf file in a separate window
window.open( PATH_TO_YOUR_PDF_URL );
// now, submit the form
o.submit();
}
Hope this helps.
You might possibly create a page that includes your script and have an iframe that points to the URL of the PDF.

Change Form Elements Depending On Selected Option

I have seen several sites where there is a form, starting with a dropdown box, and depending on the box chosen there is different form elements, for example, let's say I wanted to make an uploader script, the dropdown box might hold:
Upload
Delete
And is Upload is selected I would want a browse file element, while with Delete selcted maybe only the name should be imputted into a text field. How can I make it do so? I plan on using php for it and using the echo syntax to create the html for the forms, but is ther a way to have, for example an if statment, that changes the other form elements that show based on the option selected.
I have seen people use jQuery for it, but I can ONLY use PHP ad HTML for my project.
This isn't a direct solution but if you intend on carrying out this task exclusively with php/html then you should consider setting up a system such as this in the php file which serves the page.
<?php
/*Check to see if the user has submitted the form*/
if(isset($_POST['action']))
$action = $_POST['action'];
/*If no action has been sent from the client side, generate form*/
if(!isset($action)){ ?>
<form name="test" action="example.php" method="POST">
<select name="action">
<option value="update">Update</option>
<option value="delete">delete</option>
</select>
</form>
<?}
/* if update action, load file dialog*/
elseif($action == "update"){?>
<!-- relevant HTML or action for file load -->
<?}
/*Default to delete*/
else{?>
<!-- some action to place the input field -->
<input name="fileName" value="<? echo $FILE_NAME; ?>" />
<?}
?>
Essentially you're going to have to handle both page serving and form processing within the one page, using the value from the form select element to determine which blocks of HTML need to be loaded. Note that you will still have to provide a submit button for the form in order to trigger the action since there's no javascript events.
I want to distance myself from this solution as I know of it only through experiencing the Dunning Kruger effect and I'm sure the lack of client side involvement will be frowned upon by most.
You can't do what you want in purely server-side code without some sort of submission from the browser to trigger the check. PHP code runs on the server and returns the page to the browser. Once the page has left the server there's nothing PHP can do to it.
Sites I've seen that do this kind of thing on the server-side reload usually have an initial page where you choose the action you want, and then load the form for the chosen action. That's really all you can do without some kind of javascript on the client side.
If you can use javascript then you have many more options:
Trigger a reload of the form when the drop-down box is changed.
Send an ajax request when the drop-down box is changed and dynamically add the HTML returned by the server to the form.
Send fields for all options in the original page, and use the change event on the drop-down to show/hide the relevant fields.
Based on your comments to other answers there seems to be some confusion as to the role of javascript in the application. The server doesn't need to know about Javascript, or even JQuery. The server runs your PHP code to build the HTML for your page. The HTML can reference CSS stylesheets, images, Javascript files, etc, which, as far as the server is concerned, are just static files requested by the browser. Once the client browser gets the javascript file from the server it can execute it and enable whatever dynmiac page behaviour is intended. There is no Javascript code in your server-side application. The application is just a bunch of PHP files, with a collection of other static files to support the generated HTML.
Im no expert, but i guess since PHP is a Server-Side Scripting Language, there is no way to do this purely in php, other than to reload the page evertime you switch the dropdown option. Maybe you could accomplish it with frames (but who wants to use those?).
jQuery is just a pre-written javascript subset, are you not allowed to use javascript? if you can not use it, then your ability for dynamic pages diminishes greatly.
AJAX uses javascript as well and is the solution I use to load dynamic content. do you need examples or a way to do this without javascript.

Categories