PHP Variable from another file without include or session - php

I've tried using $_SESSION and include, none which have worked. What I'm doing is uploading an image to my server. Using Ajax to run a file called upload.php which has the upload script in it. When the file gets uploaded I want to pass the filename to my main.php page to use as a php variable. Include would just throw errors of undefined variables and session just wouldn't work.
Ajax
$(document).ready(function(){
$(document).on('change', '#file', function(){
var name = document.getElementById("file").files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize < 4000000)
{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
$('#image_upload_info').html(data);
}
});
}
});
Part of the upload script, $imagenameupload is the variable I want to pass back to my main.php page
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col-md-8">';
echo '<div class="alert alert-success">';
echo "Pilt: ". basename( $_FILES["file"]["name"]). " on lisatud!";
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
$imageNameUpload = basename( $_FILES["file"]["name"]);
}
EDIT
I explained it a little rought before. I want to be able to insert said variable into a database with other data. Heres a little more code.
SQL INSERT
if(isset($_POST['submit'])){
date_default_timezone_set('Europe/Tallinn');
$typeSelector = $_POST['typeSelector'];
if (isset($_POST['regionSelector']) ? $_POST['regionSelector'] : null) {
$checkBox = implode(',', $_POST['regionSelector']);
}
if(isset($_SESSION['imageNameUpload'])) {
$uploadedPic = $_SESSION['imageNameUpload'];
}
$now = new DateTime();
$timestring = $now->format('d.m.Y H:i');
$_POST = array_map('stripslashes', $_POST);
//$_POST = json_decode(stripslashes(json_encode($_POST)), true);
extract($_POST);
if($title ==''){
$error[] = 'Pealkiri on puudu.';
}
if($newstext ==''){
$error[] = 'Uudise sisu on puudu.';
}
if ($checkBox == '') {
$error[] = 'Regioon on puudu.';
}
if(!isset($error)){
try {
$stmt = $db->prepare('INSERT INTO news (title,shortdesc,newstext,tag,region,publish_date,imageName) VALUES (:title, :shortdesc, :newstext, :tag, :region, :publish_date, :imageName)') ;
$stmt->execute(array(
':title' => $title,
':shortdesc' => $shortdesc,
':newstext' => $newstext,
':tag' => $typeSelector,
':region' => $checkBox,
':imageName' => $imageName,
':publish_date' => $timestring
));
header('Location: index.php?news=addednews');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}

In upload.php
First you must start the seesion via session_start();
directly after the opening PHP 'tag' ()
Then you must save your variable to the session.
You can do this like,
$_SESSION['imageNameUpload'] = $imageNameUpload;
For main.php
And in the other file you must also use session_start(); at the very first after the
Then you could access the old variable via $imageNameUpload = $_SESSION['imageNameUpload'];.
You now can also use $imageNameUpload in the main.php file. But you only can use it if it's set (and you where at the first file before).
upload.php
<?php
session_start();
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col-md-8">';
echo '<div class="alert alert-success">';
echo "Pilt: ". basename( $_FILES["file"]["name"]). " on lisatud!";
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
$imageNameUpload = basename( $_FILES["file"]["name"]);
$_SESSION['imageNameUpload'] = $imageNameUpload;
}
main.php
<?php
session_start();
if(isset($_SESSION['imageNameUpload'])) {
$imageNameUpload = $_SESSION['imageNameUpload'];
}
// Other content of file
?>
If you don't want to refresh the page after image upload just want to show the uploaded image name without refreshing the page
Then,Change in your upload.php
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$imageNameUpload = basename( $_FILES["file"]["name"]);
$data = '<div class="container"><div class="row"><div class="col-md-8"><div class="alert alert-success">Pilt: '. $imageNameUpload. ' on lisatud!</div></div></div></div>';
echo $data;
exit();
}
And if you want to refresh the page then show image name on main.php. In that case you have to store data in session as i explain above. and add page refresh statement in ajax success block. And check in main.php if isset $imageNameUpload varible then first show it on html and then unset it. SO it will not seen in another page refresh request.
Hope this helps

Related

simple parse error with my form submit using ajax and file upload

I'm able to get the file uploaded and in to the directory I want so that part seems to work but I'm not sure why I'm getting a parse error in the js console in chrome. Because of this error my bottom javascript won't execute and I need it to do so.
Here's the ajax:
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
alert(data);
script = $(data).text();
$.globalEval(script);
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
Here's the html:
<?php
echo '<span class="new_profile_save_upload_image_span"><img src="'.$url_root.'/images/615721406-612x612.jpg"/ class="new_profile_save_upload_image_img"></span>';
?>
<form action="" method="post" enctype="multipart/form-data" name="new_profile_save_upload_image_input_form" id="new_profile_save_upload_image_input_form">
<input type="file" id="new_profile_save_upload_image_input" name="new_profile_save_upload_image_input" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
<input type="submit" value="Upload Image" name="submit">
</form>
And here is the php:
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
<script>
var scope1 = '<?php echo $url_root;?>';
var scope2 = '<?php echo $username;?>';
var scope3 = '<?php echo $file['name'];?>';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
$('.new_profile_save_upload_image_span').empty();
$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
alert(data) doesn't seem to be popping up, so there's something wrong previous to that execution.
I tried this code with simply 'submit.php' but it doesn't seem to work without the 'files' addition to it.
Also do I have the filename correct? Should the file's filename be $file['name'] in php? I'm trying to get the file name as a string and place it in when the default image is (as an image to be displayed), using an img html tag and inserting it via jquery, as you can see at the bottom under .
The ajax should execute this script at the bottom but it doesn't due to the error.
Also is there a nicer way of writing the bottom jquery scripts that I have written?
Error I'm getting:
ERRORS: Syntax Error: Unexpected Token < in JSON at position 103
Thanks in advance.
If you want to return JSON and HTML at the same time, you could put the HTML into an element of the $data array.
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
$data['html'] = <<<EOS
<script>
var scope1 = '$url_root';
var scope2 = '$username';
var scope3 = '{$file['name']}';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
\$('.new_profile_save_upload_image_span').empty();
\$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
EOS;
}
echo json_encode($data);
?>
Then in the JavaScript you do:
script = $(data.html).text();
It's better to use try-catch block in your PHP code, and send status with the response set to true or false. Also, send the $url_root and $username variables within the JSON object.
See this beginner's guide on Image Uploading with PHP and AJAX to learn everything about creating AJAX handler, validating, saving and sending a response back to the client side.

How can I upload the image with ajax and save image address in mysql with pdo [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 5 years ago.
How can I upload the image and save the image address in the mysql ?
1.I want to upload the image with AJAX
2.And the image address will be stored in the mysql with pdo
This is my code:
$(document).ready(function(){
$("#usredit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var file = $("#file").val();
var image = $("#image").val();
var id = $("#id").val();
var send = true;
$.post("set-ajax.php",{name:name,email:email,file:file,image:image,id:id,send:send},function(data){
$("#editres").html(data);
});
});
});
ajax.php
if(isset($_POST['send'])){
if(empty($_POST['name']) || empty($_POST['email'])){
echo '<div class="alert alert-warning">Fill empty fields</div>';
}else{
if(isset($_POST['file'])){
$file = $_POST['file'];
$tmp = $_FILES['file']["tmp_name"];
$name = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
if (is_uploaded_file($tmp)){
$ext = array("image/jpg","image/png","image/jpeg");
if (in_array($type,$ext)){
$filename = md5($name.microtime()).substr($name,-5,5);
if(move_uploaded_file($tmp,"user/img".$filename)){
echo '<div class="alert alert-success">Upload done</div>';
}else{
echo '<div class="alert alert-warning">Upload failed</div>';
}
}else{
echo '<div class="alert alert-warning">Unrelated file</div>';
}
}
}
$name = $_POST['name'];
$email = $_POST['email'];
$image = $_POST['image'];
$id = $_POST['id'];
$resualt = $User->UpdateUserProfile($name,$email,$image,$id);
if($resualt ){
echo '<div class="alert alert-success">Edit done</div>';
}else{
echo '<div class="alert alert-warning">Edit failed</div>';
}
}
Assuming, you were able to upload image to user/img folder. Then, create a method which will update/insert details of uploaded image. And call that method by passing image name (since, folder path will be common for all )
if(move_uploaded_file($tmp,"user/img".$filename)){
// update/insert table with folder location.
// call the method here
echo '<div class="alert alert-success">Upload done</div>';
}

Saving variable value in a text file using PHP

by clicking on a button I am setting a variable in php using Ajax.
submitInfo(var1);
function submitInfo(var1)
{
$.ajax({
type: "POST",
url: "js/info.php",
data: {Info:var1},
success: function (result)
{
alert(result);
}
});
}
in my php code, How can I save "var1" in a text file? I have used this to save variable in a text file but it is not saving anything there:
<?php
if (isset($_POST['var1']))
{
echo $_POST['var1'];
}
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
?>
The first issue is that in your JQuery you actually assigning the var1 variable to 'Info'
so the $_POST array will contain this rather than var1.
You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.
<?php
$var1 = "";
$filename = "js/test.txt";
// Get the correct $_POST object
if (isset($_POST['Info']) {
$var1 = $_POST['Info'];
}
// If the variable is not empty try to write your file
if (!empty($var1)) {
if(!$file = fopen($filename,"w")) {
$msg = "Cannot open file");
} else if (fwrite($file,$var1) === false) {
$msg = "Cannot write to file");
} else {
$msg => 'all was good'
}
fclose($file);
$result = array(
'error' => 'false',
'msg' => $msg
);
} else {
$result = array(
'error' => 'true',
'msg' => 'Info was empty'
);
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";
PS: Not tested this so fingers crossed there are no typos.
Try this:
<?php
if (isset($_REQUEST['Info'])){
$var1 = $_REQUEST['Info'];
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
}
?>

Alert when uploading file with php

I have a file upload page that works but I'm trying to do some error alerts to choose if you want to replace or not.
This is my php file that does the upload
<?php
require ("connect.php");
$filename = "docs/".$_FILES['datafile']['name']."";
$d=explode(".",$_FILES['datafile']['name']);
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
} else {
$target_path = "docs/";
$target_path = $target_path . basename( $_FILES['datafile']['name']);
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['datafile']['name'])." has been uploaded";
$error = 0;
}
else
{
echo "There was an error uploading the file, please try again!";
$error = 1;
}
}
if ($error != 1)
{
$r1 = mysql_query("insert into full_dump (file_name) values ('".$_FILES['datafile']['name']."')")or die(mysql_error());
$file1 = "docs/".$_FILES['datafile']['name']."";
$lines = file($file1);
$count = count($lines);
$fp = fopen("docs/".$_FILES['datafile']['name']."","r");
$data=fread($fp,filesize("docs/".$_FILES['datafile']['name'].""));
$tmp=explode ("\n", $data);
for ($i=0; $i<$count; $i++)
{
$a=$tmp[$i];
$b=$i+1;
$r2 = mysql_query("update full_dump set field_".$b."='".$a."' where file_name='".$_FILES['datafile']['name']."'")or die(mysql_error());
}
echo"</br>";
echo "Uploading Complete</br>";
echo "Uploaded File Info:</br>";
echo "Sent file: ".$_FILES['datafile']['name']."</br>";
echo "File size: ".$_FILES['datafile']['size']." bytes</br>";
echo "File type: ".$_FILES['datafile']['type']."</br>";
}
?>
What I want to have is instead of
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
}
to have an alert if I would like to replace the file or not. If it's yes it would replace the file, delete the old record in the db and insert the new record. I it's no don't do nothing...or show a message "canceled by user". Could I have $error to be assigned a value for YES or NO on user choosing or not to replace?
UPDATE
This is the form page for upload.
<html>
<head>
<script language="Javascript">
function fileUpload(form, action_url, div_id) {
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
}
else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
}
else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
// Submit the form...
form.submit();
document.getElementById(div_id).innerHTML = "Uploading...";}
</script>
</head>
<body>
<form enctype=\"multipart/form-data\" method=\"POST\">
<input type="file" name="datafile" />
<input type="button" value="upload" onClick="fileUpload(this.form,'file_upload.php','upload'); return false;" >
<div id="upload"></div>
</form>
<?php
require("connect.php");
$result = mysql_query("SELECT * FROM full_dump")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Job number: ".$row['file_name']."</br>";
}
?>
you should do this with ajax... when you will send ajax request you will check if file exist or not .. if yes return eg -1 and ask user for relapsing ...
Enjoy :)
instead of using upload code on same page. do one thing, upload file by using ajax request. then check on backend site file is aleady exist or not and according to that show message as you like

jQuery issues when using ajax and .attr('class', 'new_class')

I am using Zend Framework, and to illustrate what is working I added the saveAction() to this post and it works flawlessly. It will animate and change the class as I want. The function upload instead only change the text and ignore the javascript. I can do alerts that works, however jquery is not possible. I get error saying that $ is undefined. How could it be undefined in 1 case and not the other?
I am catching the upload form with ajax and just throw it into the #savecontainer.
Hope there's a solution, it seems to be a tiny issue somewhere, but I can't find it on my own. Thank you.
it looks like this:
$(document).ready(function() {
$('#newsForm').ajaxForm({
target: '#savecontainer'
});
$('#uploadForm').ajaxForm({
target: '#savecontainer'
});
$("#btn_save").click(function () {
$('#newsForm').submit();
});
$("#btn_upload").click(function () {
$('#uploadForm').submit();
});
});
public function saveAction()
{
$this->_helper->layout->disableLayout();
$db = new Admin_Model_DbAccess();
if(isset($_POST['active']))
$_POST['active'] = 1;
else
$_POST['active'] = 0;
if($_POST['id'] == 0){
// If it is a new post
$data = array(
'header' => $_POST['header'],
'message' => $_POST['message'],
'date' => time(),
'user' => Zend_Auth::getInstance()->getStorage()->read()->id,
'image' => $_POST['image'],
'active' => $_POST['active'],
'category' => $_POST['category']
);
if($db->addNews($data)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
$('#news_id').attr('value', '".$db->lastInsertId()."');
$('#upload_box').show('slide', {direction: 'up'}, 500);
$('#news_id_upload').attr('value', '".$db->lastInsertId()."');
</script>";
echo "Status: Added.";
}else{
// set the css variables to failed
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}else{
$data = array(
'header' => $_POST['header'],
'message' => $_POST['message'],
'image' => $_POST['image'],
'active' => $_POST['active'],
'category' => $_POST['category']
);
$db = new Admin_Model_DbAccess();
if($db->updateNews($_POST['id'], $data)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
</script>";
echo "Status: Updated.";
}else{
// set the css variables to failed
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}
}
public function uploadAction(){
$this->_helper->layout->disableLayout();
if ($this->_request->isPost()) {
//Startup the adapter to upload
$adapter = new Zend_File_Transfer_Adapter_Http();
//Define the upload path
define('UPLOAD_NEWS_IMAGE_PATH', APPLICATION_PUBLIC_PATH. "/img/news/");
// Fixa upload path
$adapter->addValidator('Extension', false, array('jpg', 'jpeg' , 'gif' , 'png'))
->addValidator('Count', false , array( 'min' => 0, 'max' => 0));
$file = $adapter->getFileInfo();
$adapter->receive();
$messages = $adapter->getMessages();
if(isset($messages['fileCountTooMany']) && !isset($messages['fileExtensionFalse'])){
//If the file does exists (Everything went fine);
$fileinfo['ext'] = end(explode(".", $file['upload_0_']['name']));
$uploaded_filename = $_POST['id'].".".$fileinfo['ext'];
// Change name to id.jpg for example
move_uploaded_file($file['upload_0_']['tmp_name'], UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename);
// resize to
$full_thumb = Butikadmin_Model_PhpThumbFactory::create(UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename);
$full_thumb->resize(960, 500);
$id = $_GET['id'];
if($full_thumb->save(UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
$('#upload_box').fadeOut(500);
</script>";
echo "Status: Uploaded.";
}
}else{
// If the file is not right format
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}
}
why not using an ajax call instead of .submit?
and in the php code, remove the js record and return data (array or ojbect) from the function and handle it back in the js script with a callback function which return that data

Categories