ajax form data serialization failed - php

I have a HTML with a form in it like this:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
and the .php script like this:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
The problem:
in the submitform() function, in the script tag at the line:
data = $('*').serialize();
why I get empty result?
What is wrong with the code?
Thank you

change this
data = $('*').serialize();
to
data = $('theform').serialize();
and change this
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
to
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">

Give thsi a try as mentioned here: http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});

You can also use
echo json_encode($data);
http://php.net/manual/en/function.json-encode.php

You cannot upload files using Ajax, if you MUST upload files in an AJAX-like way you can use hidden iframes, set the target attribute equal to the iframe and grab the iframe's content to know whether the request has failed or not
This is what i usually do for this purpose, create a hidden iframe that will be the target to the form, something like this:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
and in processResult you can fetch the iframe's content by:
$(results).html();
This way when the iframe is loaded it will automatically trigger the function to inform the request is complete

Related

How to create a php upload file with progress bar [duplicate]

This question already has answers here:
Upload Progress Bar in PHP
(10 answers)
Closed 9 years ago.
I would like to know how can I add a progress bar in my php upload file.
This is my code:
form.html
http://pastebin.com/embed_iframe.php?i=mukfyVSz
<form id="myForm" action="action.php" method="post">
<input type="file" name="upfile">
<input type="hidden" name="MAX_FILE_SIZE" value="10000">
<input type="submit" value="Upload">
</form>
<div style="margin-top:15px;" id="htmlExampleTarget"></div>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#myForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
// success: function(data) {
// $('.data').html(data);
//}
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
action.php
http://pastebin.com/vhcH7rTT
<?php
$upload_dir = "./uploads"; // upload folder
$file_name = $_FILES["upfile"]["name"];
// MIME TYPES LIST: http://reference.sitepoint.com/html/mime-types-full
$allowed_types = array("image/gif","image/jpeg","text/html","image/png");
if(!in_array($_FILES["upfile"]["type"],$allowed_types)) {
die("Upload non consentito per questo tipo di file. ");
}
if(trim($_FILES["upfile"]["name"]) == "") {
die("Error1");
}
if(#is_uploaded_file($_FILES["upfile"]["tmp_name"])) {
#move_uploaded_file($_FILES["upfile"]["tmp_name"], "$upload_dir/$file_name")
or die("Error2");
} else {
die("Problems with " . $_FILES["upfile"]["name"]);
}
echo "<div [class='alert alert-success'>Upload with success " . $_FILES["upfile"]"name"] . "</div>";
?>
jquery file upload is better for your need,
just go through the plugin page:
http://blueimp.github.io/jQuery-File-Upload/

Search Text Files with PHP from User Input

Looking for a solution to search through a list of Zip Codes. I have a text file with a bunch of zip codes that we service. Would like to have a form on the website asking for the user to input their zip code to see if we service that area. If it does, display a message saying that we do, if not, saying that we don't. Thought PHP would be the best solution for my problem, but I'm a total noob when it comes to that.
I have my form set up, I'm just not sure how to search the text file and display the answer in another div?
<form action="zipcode.php" method="post">
<input type="text" name="search" />
<input type="submit" />
</form>
UPDATE: Preferably an AJAX solution!
AJAX method (tested)
PHP handler
(find_in_file_ajax.php)
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found";
}else{
echo "ZIP code does not exist";
}
?>
HTML form
<!DOCTYPE html>
<html>
<head>
<style>
.update {
font-family:Georgia;
color:#0000FF;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "find_in_file_ajax.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="container">
<div>
<form method="post" action="">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results: <span id="results" class="update"></span>
</div>
</div>
</div>
</body>
</html>
Original answer
Tested
First the file needs to be accessed via file_get_contents, then explode each entry and extract the zip code search in question.
Assuming the zipcodes.txt file is in the following format:
43505
43517
43518
43526
43543
NOTE: If 43505 is queried, it will be found. Unlike 4350 or 3505 will not be found, so it's a unique query.
Consider the following:
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found.";
}else{
echo "ZIP code does not exist";
}
?>
Saw your edit...the below is PHP.
I would do something like
$lines = file("/path/to/file.txt", FILE_IGNORE_NEW_LINES); //reads all values into array
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "found zip code";
}else{
echo "zip code does not exist";
}
As long as there isn't a VERY LARGE amount of zip codes...this should be fine. Also, what is the format of your file? This may not work.

Uploading file via PHP in form

(beginner)
I'm having trouble uploading my file. I see the filename being posted to the database, but the file is not being posted to the images folder. It seems as though nothing is happening. Here is my following code, please advise me what I need to change:
<?php
//the $art variable gets posted to a database eventually
$art = mysql_real_escape_string(stripslashes($_FILES["art"]["name"]));
$art_ext = pathinfo($art, PATHINFO_EXTENSION);
$art = md5($art).".".$art_ext;
if($art!=""){
move_uploaded_file($art, "images/".$art );
}
?>
<script type="text/javascript">
$(function(){
image_upload = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("#imageupload").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
</script>
<form action="new.php" method="post" enctype="multipart/form-data">
<input type='file' name='art' id="file" onchange='image_upload.UpdatePreview(this)' value="Upload" accept="image/gif,image/jpeg,image/png"/>
</p>
<p>upload a image! (.gif, .jpg, .png formats allowed. 5MB max)</p>
<img id="imageupload" src="1x1.png" alt="test" />
<input type="submit" class="smallbtn4" style="cursor:pointer;" value="post"/>
</form>
Here's the format for move_uploaded_file():
$path = 'images/';
move_uploaded_file($_FILES['art']['tmp_name'], $path.basename($_FILES['art']['name']));
when using move_uploaded_files() your destination path should also include the name of the file....right now your destination path is:
images/
it should be:
images/nameOfImg.ext
Hope this helps!
EDIT:
After seeing the comment by #enhzflep, you should also hash the name of the file and create your filename string before using it in move_uploaded_file();

PHP - Upload picture and display on page

The following code allows me to upload pictures (using a html form) to a directory on my server.
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
Is there any way to modify it so that it will add the pictures to a html page instead?
Thanks
Well after you upload it, you can use javascript to put it on the html page.
I'm not quite sure what your question is, though
EDIT:
So, html form on your page:
<form action="imageUpload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="jupload();" id="form1" >
<div style="visibility:'hidden';" class="imageholder"> <!-- a gif image to show that the process wasn't finished -->
</div>
<input type="file" name="imgfile" />
<input type="submit" name="uploadButton" class="upbtn" value="Submit" />
</form>
Javascript(JQUERY) code for the upload and image add:
function jupload()
{
$(".imageholder").append('<img src="./images/loading.gif">');
}
function juploadstop(result)
{
if(result==0)
{
$(".imageholder").html("");
}
// the result will be the path to the image
else if(result!=0)
{
$(".imageholder").html("");
// imageplace is the class of the div where you want to add the image
$(".imageplace").append("<img src='"+result+"'>");
}
}
php code:
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
$result=$target;
}
else
{
$result=0;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.juploadstop(<?php echo $result; ?>);
</script>
Suppose you have the form in HTML to submit the image.. make the submit button, not a submit button, but just a button.. e.g.
<input type='button' id='submit_form' value='upload' />
and in the javascript, use Ajax to submit the form and Jquery to display it in the web page
$('#submit_form')click(function(){
$.ajax({
type: 'POST',
url: path/phpfile.php,
data: image_input_name
});
//after submitting, get the url of the image form the server
$('#div_to_display_image').html("<img src='path/image_file.jpg' alt='this' />");
});
Hope this helps :-)

Php - upload file with ajax

my 2form.php :
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
function test()
{
url = '2form.php';
var ajax = new Ajax(url, {
method: 'post',
onComplete: function(response) {
document.getElementById('error_upload_logo').innerHTML = response;
}
});
ajax.request();
}
</script>
<?php
if($_FILES)
{
echo "<div>";
foreach($_FILES['name'] as $v)
{
echo $v."<br/>";
}
echo "</div>";
}
else
{ ?>
<form action='' id='form1' name="form1" method="post" enctype="multipart/form-data">
<input type="file" name="name"/>
<input type="submit" name="submit" onclick='test(); return false;'/>
</form>
<?php
}
?>
<div id="error_upload_logo"></div>
if run code with out javascript , it 2form.php like simple php page, and
we can see information of $_FILES that was printed to scrreen
But if i have run with javascript by test() function ,
i don't get information in $_FILES ?
How to get $_FILES ? when click button run with javascript ?
i want to upload with ajax
You can't do file uploads using AJAX because you won't have access to the local file.
The most common workaround is what the JQuery Form plugin does, creating a temporary iframe and doing a normal form submit into it.
The other alternative is using a Flash-based uploader like SWFUpload or Uploadify.

Categories