I am trying to upload a file and some text with it using ajax, but my problem is that it's not uploading to the database. I tried to use console.log to fix the problem but all it does is redirect me to the home page of my website, so it means there's an error. Am I doing something wrong? Please help me.
Javascript:
<script>
$(document).ready(function() {
$("#post-btn").click(function(e) {
var fd = new FormData();
var pst = ("#txt").value;
var files = document.getElementById("fileToUpload").files[0];
e.preventDefault();
// Check if file selected or not
if(('#fileToUpload').length != 0 ){
fd.append('fileToUpload',files[0]);
$.ajax({
url: 'posting.php',
type: 'post',
data: {pst: txt, fileToUpload: fd},
contentType: false,
processData: false,
complete: function(r){
if(r != 0){
console.log(r.responseText);
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Select a file!");
}
});
});
</script>
posting.php:
<?php
$thePst = $_POST['txt'];
if (strpos($thePst, '<script>') !== false) { echo "<script>history.go(-1)</script>";
exit();
} else {
session_start();
if (isset($_POST['txt'])) {
?>
<?php
$sender = $_SESSION['username'];
$post1 = $_POST['txt'];
$post = nl2br($post1);
$submit = $_POST['submit'];
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "posts";
$id = $_SESSION['id'];
$img = $_SESSION['img'];
$stringLength = strlen($post);
if (isset($post) && $stringLength <= 550 && strpos($post, '<script>') !== true) {
$target_dir = "attatch/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 30000) {
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "tiff" && $imageFileType != "mp4" && $imageFileType != "mov" && $imageFileType != "mkv") {
echo "Sorry, only JPG, JPEG, PNG, TIFF & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random = substr(str_shuffle($permitted_chars), 0, 25);
$newfilename = $sender.".".$random.".".$imageFileType;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "attatch/" . $newfilename)) {
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$today = date("F j, Y, g:i a");
try {
$attach = 'attatch/'.$newfilename;
$conn = new PDO("mysql:host=$host;dbname=$dbName", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$preparedStatement = $conn->prepare('INSERT INTO posts (sender, post, sender_id, image_attach, sender_img, date) VALUES (:sender, :post, :sender_id, :image_attach, :sender_img, :tod)');
$preparedStatement->bindParam(':sender', $sender);
$preparedStatement->bindParam(':post', $post);
$preparedStatement->bindParam(':sender_id', $id);
$preparedStatement->bindParam(':image_attach', $attach);
$preparedStatement->bindParam(':sender_img', $img);
$preparedStatement->bindParam(':tod', $today);
$preparedStatement->execute();
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
} finally {
$sess = $_SESSION['id'];
echo "<script>history.go(-1)</script>";
}
$conn = null;
} else {
echo "<script>history.go(-1)</script>";
}
?>
<?php
}else{
header("Location: index");
exit();
}
?>
<?php } ?>
Your help is appreciated.
You need to:
Include all the data you want in the FormData object
Pass the FormData object to data: directly without wrapping it in another object
Related
I am developing a site that has a login form and a newsfeed. when i use ajax as my action to submit values to the controller my controller url disappears instead of having mypage/newsfeed
here is the script im using
$('#submitButton').on('click',function(){
var userid = $('#studentID').val();
var password = $('#password').val();
$('#errorHandler').empty();
var URL = '<?php echo base_url('newsfeed')?>';
if(userid.trim()!='' || password.trim()!=''){
$.ajax({
type:'POST',
url: URL,
data:{userid:userid,password:password},
success:function(data){
if(data)
$("body").load(data);
},error:function(errorw){
if( errorw.status == 400 ) { //Validation error or other reason for Bad Request 400
var json = $.parseJSON( errorw.responseText );
}
$('#errorHandler').append($('<label class="red-text text-darken-2">'+json+'</label>'));
}
});
}else{
$('#errorHandler').append($('<label class="red-text text-darken-2">ID/Password is Required</label>'));
}
});
UPDATE: controller code i am using custom routes $route['newsfeed'] = 'Login/Login';
public function Login(){
$userid = $this->input->post('userid');
$userpw = $this->input->post('password');
$validate = $this->loginmodel->validateAccount($userid,$userpw);
if($validate == NULL){
$this->output->set_status_header('400');
$details = $this->data['message'] = 'Incorrect Login/Password';
echo json_encode($details);
}
else{
$data['details'] = $this->loginmodel->getUserType($userid);
if(is_array($data) || is_object($data)){
foreach ($data as $key => $value) {
$type = $value->accounts_type;
}
}
$this->session->set_tempdata('accountID', $userid,18000);
$userid = $this->session->tempdata('accountID');
$data['init'] = $this->loginmodel->getGroups($userid);
$data['groupId'] = $userid;
if($type == "STUDENT"){
$data['details'] = $this->loginmodel->getDetails($userid);
$token = array(
'accountid' => $userid,
'groups' => $data['init'],
'details' => $data['details'],
);
$this->session->set_userdata($token);
$this->load->view('header');
$this->load->view('sidenav1', $data);
}
elseif($type == "PROFESSOR"){
$data['details'] = $this->loginmodel->getDetailsProf($userid);
$this->load->view('header');
$this->load->view('sidenav2', $data);
}
elseif($type == "ADMIN"){
$this->load->view('header');
$this->load->view('superadmin');
}
else{
$data['details'] = $this->loginmodel->getDetails($userid);
$this->load->view('header');
$this->load->view('Surveypage',$data);
}
}
}
When I pass data into my file upload controller, it is giving an error of undefined offset: 1.
function TestFileUpload() {
$i=0;
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
$count = count($_FILES[$i]['name']). ' ';
while ($i <= 4 )
{
echo $count;
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
echo $_FILES[$i]['name'].' '.$_FILES[$i]['type'].' '.$_FILES[$i]['size'] ;
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else{
$data = array('upload_data' => $this->upload->data());
$this->new_development_model->insertonAttachments($data['upload_data']);
$i++;
}
}
}
}
It's probably related cause you need to check in your loop if $_FILES[$i] is defined.
You do this but only one time, when $i = 0.
I even think that if you check in the loop, you wont need to do
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else { /*...*/ }
before the loop
I want to make an ajax request on click with jquery, but it's not working:
This is what I have:
The button:
$photos_box .= '<a id="' . $imgID . '" class="like_button">' . $like . '</a>';
Maybe there's an error in the script:
// Like function
$('.like_button').click(function() {
$(this).toggleClass('liked');
var status = '';
if ($(this).hasClass('liked')) {
status = 'like';
$(this).html('Ya no me gusta');
console.log('like_works');
} else {
status = 'unlike';
$(this).html('Me gusta');
console.log('unlike_works');
}
var data = {
img_id : this.id,
sta : status
};
$.ajax({
type : 'POST',
url : '/includes/like.php',
data : data
}).done(function(reslike) {
if (reslike == 1) console.log('ajax_works');
});
});
And this is the like.php file:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
sec_session_start();
// User id
if (login_check($mysqli) == true) {
$user_id = $_SESSION['user_id'];
}
$img_id = $_POST['img_id'];
$status = $_POST['sta'];
$stmt = $mysqli->prepare("SELECT * FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$usr_likes = $result->num_rows;
if ($status == 'like') {
if ($usr_likes == 0) {
$stmt->close();
$stmt = $mysqli->prepare("INSERT INTO img_likes (img_id, user_id) VALUES(?, ?)");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
else if ($status == 'unlike') {
if ($usr_likes != 0) {
$stmt->close();
$stmt = $mysqli->prepare("DELETE FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
}
At last! Thanks to everyone. Hope my code help someone.
Check the URL in your ajax request, I'm not certain but I don't think '../includes/like.php' is a valid URL I think you actually have to give it a valid server URL like "http://example.com/includes/like.php"
I am having a little trouble figuring out why my ajax response is sending me the entire page.
I am not using conventional AJAX code simply because this is how the guy was doing it in a tutorial I was following. I am using firebug to track all my javascript variables and when I break the code at the responseText var it gives me the entire page. Here is the code for the javascript on the page I am working with :
function changepass() {
var u = _("username").value;
var cp = _("currentPass").value;
var np = _("newPass").value;
var cnp = _("confirmNewPass").value;
if(np != cnp) {
_("status").innerHTML = "The passwords given do not match!";
} else if (cp === "" || np === "" || cnp === "") {
_("status").innerHTML = "Please fill out all of the fields.";
} else {
_("changepassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "change_password.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var response = ajax.responseText;
if(response == "success"){
_("status").innerHTML = "Your password change was successful! Click the button below to proceed.<br><br>Back To Home Page";
} else if (response == "no_exist"){
_("status").innerHTML = "Your current password was entered incorrectly.";
_("changepassbtn").style.display = "initial";
} else if(response == "pass_failed"){
_("status").innerHTML = "Change password function failed to execute!";
_("changepassbtn").style.display = "initial";
} else {
_("status").innerHTML = "An unknown error occurred";
_("changepassbtn").style.display = "initial";
}
}
}
ajax.send("u="+u+"&cp="+cp+"&np="+np+"&cnp"+cnp);
}
}
Here is the AJAX code that I use to handle the requests.
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Any help would be greatly appreciated.
Thanks!
Here is the server side PHP:
if(isset($_POST["u"]) && isset($_POST['oe']) && isset($_POST['ne']) && isset($_POST['p'])) {
$oe = mysqli_real_escape_string($db_conx, $_POST['oe']);
$ne = mysqli_real_escape_string($db_conx, $_POST['ne']);
$p = md5($_POST['p']);
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
var_dump($oe, $ne, $p, $u);
$sql = "SELECT username, password, email FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_username = $row[0];
$db_password = $row[1];
$db_email = $row[2];
var_dump($db_username, $db_password, $db_email);
if($db_email != $oe) {
echo "bad_email";
exit();
} else if($db_password != $p) {
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET email='$ne' WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$sql = "SELECT email FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newemail = $row[0];
if($db_newemail == $ne) {
echo "success";
exit();
} else {
echo "email_failed";
exit();
}
}
}
My mistake was a simple syntax error. Gosh PHP is picky! The error occurs in the ajax.send command. I am miss an '=' on the last parameter.
Thanks for your help guys!
I am trying to create a zip folder on the fly. The zip will hold images that a user has selected from a library that is hosted on Amazon S3. Below is the code I have so far.
REQUEST URL FROM POST
function download_multi() {
//$user_id, $files, $project_id, $project_name
$this->load->library('aws');
$user = User::get_user();
$requestedHashes = $this->input->post("files");
$files = array();
foreach($requestedHashes as $hash) {
$files[] = hex_to_string($hash);
}
$project_id = $this->input->post("projectid");
$project = new Project($project_id);
$project_name = $project->project_name;
$this->aws->create_zip($user->id, $files, $project_id, $project_name, (int)$this->input->post("downloadToken"));
}
Create Zip
public function create_zip($user_id, $files, $project_id, $project_name, $cookie) {
//create a random folder name to avoid collision.
$this->folder = md5(time() . rand());
if(!mkdir('./files' . '/' . $this->folder, 0777, TRUE)) {
exit("Folder not created\n");
}
//create zipfile
$this->filename = $this->local_file_path . $this->folder . '/files.zip';
$zip = new ZipArchive();
if ($zip->open($this->filename, ZIPARCHIVE::CREATE) !== TRUE) {
exit("cannot open <$this->filename>\n");
}
//create options for downloading each file to the server
//temporarily to add to archive
$opt = array('preauth' => '+1 minutes');
//download each file to the server.
foreach ($files as $file) {
//generate a link.
$response = $this->s3->get_object($this->bucket, $this->_make_path($user_id, $project_id) . $file, $opt);
//get filename.
$file_name = explode('?', basename($response));
//add filename to array
$local_files[] = $file_name[0];
//copy the file from aws to local server.
if(copy($response, $this->local_file_path . $this->folder . '/' . $file_name[0])) {
$zip->addFile($this->local_file_path . $this->folder . '/' . $file_name[0], $file_name[0]);
}
}
//close zip
$zip->close();
//die(var_dump(file_exists($this->filename)));
//kill each temp file
/*foreach ($local_files as $file) {
unlink($this->local_file_path . $this->folder . '/' . $file);
}*/
//load download helper.
$this->ci->load->helper('download');
//download
stream_download("APP_{$project_name}_" . time() . ".zip", $this->filename, $cookie);
}
The Download Helper
function stream_download($filename = '', $data = '', $cookie = NULL)
{
//die($cookie);
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (is_file(APPPATH.'config/mimes.php'))
{
include(APPPATH.'config/mimes.php');
}
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Set-Cookie: fileDownloadToken="'.$cookie.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".filesize($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Set-Cookie: fileDownloadToken="'.$cookie.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".filesize($data));
}
flush();
}
JAVASCRIPT
downloadSelectedFiles: function(e) {
//window.XmlHttpRequest = new XmlHttpRequest();
console.log("Block UI");
var that = this;
var url = config.base + "projects/download_multi";
var projectId = $("li.selected").find('li.js-select-file').data('projectid');
var images = {};
images.hashes = [];
var token = new Date().getTime();
$("li.selected").each(function(i){
images.hashes.push($(this).find('li.js-select-file').data('filename'));
});
//window.location.href = url;
$.post(url, { files: images.hashes, projectid: projectId, downloadToken: token }, function(data){
var fileDownloadCheckTimer = window.setInterval(function() {
console.log("checking...");
var cookieValue = $.cookie('fileDownloadToken');
console.log(parseInt(cookieValue), parseInt(token));
if( parseInt(cookieValue) == parseInt(token) ) {
that.finishDownload()
} else {
console.log("Don't Match");
}
}, 1000);
/*var iframe = document.createElement("iframe");
iframe.src = config.base + data;
iframe.style.display = "none";
document.body.appendChild(iframe);
return false;*/
});
},
finishDownload: function() {
window.clearInterval(fileDownloadCheckTimer);
$.removeCookie('fileDownloadToken');
console.log("Unblock UI");
}
One thing I have noticed is that when I am checking to see of the cookie value and the token match one is a string and the other an int. Other that I also not that I only get the headers in my reposonse, I never actually get the download window.