Value is not passing through Javascript it directly goes to PHP - javascript

I'm trying to pass a file and some text field and a drop down value to php in order to upload them all in a query in database. I'm validating the text field input in JavaScript to prevent giving any wrong input. But the problem is the values are not going through JavaScript all the time. So i've set the php file in form action. So now what is happening that, it is not checking individual text field input and not showing error. Rather goes direct to the php. Now how can i resolve this
HTML
<form id="jobform" class="form-horizontal" method="post" action="test.php" enctype="multipart/form-data">
<h2><b>Post your job</b></h2><br><br>
<div class="form-group">
<label class="control-label col-sm-2">Job Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="jName" placeholder="Enter job name" name="jName" required>
<p id="jErr"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Job Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="sal" placeholder="Enter job salary" name="sal" required>
<p id="salErr"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Job Type:</label>
<div class="col-sm-10">
<div class="dropdown">
<select id="jType">
<option value="part-time">Part-Time</option>
<option value="full-time">Full-Time</option>
<option value="internship">Internship</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Job Location:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="loc" placeholder="Enter job locations" name="loc" required>
<p id="locErr"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Add some detailed description:</label>
<div class="col-sm-10">
<input id="u_file" value="u_file" type="file" name="u_file" size="5000000" multiple onchange="showname()"><br><br>
</div>
</div>
<div class="container-fluid text-center">
<br><button name="submitJob" id="submitJob" type="submit" class="btn btn-default" onclick="job_checker()">Submit</button>
<p id="submitJobErr"></p></div>
</form>
JavaScript
signFlagj = 0;
function job_checker() {
checkJobName();
checkSalary();
checkJobType();
checkJobLoc();
databasejobEntry();
}
function checkJobName() {
jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname)){
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else {
jobnameError.innerHTML = "";
}
}
function checkSalary() {
var salaryET = document.getElementById("sal");
var salaryError = document.getElementById("salErr");
jobsal = salaryET.value;
console.log(jobsal);
var regex = /^[1-9.,][0-9.,]*$/;
if(!regex.test(jobsal)){
salaryError.innerHTML = "Only numbers with or without comma or point is allowed";
signFlagj = 1;
}
else {
salaryError.innerHTML = "";
}
}
function checkJobType() {
var jobTypeET = document.getElementById("jType");
jobType = jobTypeET.value;
console.log(jobType);
}
function checkJobLoc() {
var jobLocET = document.getElementById("loc");
var locError = document.getElementById("locErr");
jobLocation = jobLocET.value;
console.log(jobLocation);
var regex = /^[a-zA-Z0-9\/\s,'-]*$/;
if(!regex.test(jobLocation)){
locError.innerHTML = "Enter valid amount";
signFlagj = 1;
}
else {
locError.innerHTML = "";
}
}
function showname() {
jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
/*function toSubmit(){
preventDefault();
alert('I will not submit');
return false;
}*/
function databasejobEntry() {
if(signFlagj==1) {
console.log("fill up correctly!");
alert("Sign up correctly!");
window.location.href = "test.html";
}
else
{
// console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success") {
alert("Successfully submitted :)");
var formdata = $('#jobform').serializeArray();
//alert(formdata);
document.getElementById("jobform").submit();
//window.location.href = "uploadJob.html";
}
}
}
xhttp.open("POST", "test.php?jobname="+jobname+"&jobType="+jobType+"&jobsal="+jobsal+"&jobLocation="+jobLocation+"&jobFilename="+jobFilename,true);
//xhttp.open("POST", "three.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xhttp.open("POST", "test.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
PHP
<?php
require_once('DBconnection.php');
//ini_set('display_errors', 1);
//ini_set('log_errors', 1);
$val="";
$jobName = $_POST["jName"];
$jobType = $_POST["jType"];
$jobSalary = $_POST["sal"];
$jobLocation = $_POST["loc"];
echo "$jobName";
echo "$jobType";
echo "$jobSalary";
echo "$jobLocation";
//print_r($jobName);
echo"<br>";
//$u_file = $_FILES['jobFilename'];
$file_type = $_FILES['u_file']['type'];
$file_size = $_FILES['u_file']['size'];
$file_name = $_FILES['u_file']['name'];
//echo "$jobName";
print_r($file_name);
echo"<br>";
print_r($file_size);
echo"<br>";
print_r($file_type);
echo"<br>";
//echo "****************";
$currentdir = getcwd();
$targetfolder = $currentdir . "/testupload/";
// echo "****************";
print_r($targetfolder);
$targetfile = $targetfolder . basename( $_FILES['u_file']['name']) ;
print_r($targetfile);
//print_r($currentdir);
//echo "****************";
$uploadOk=1;
//print_r($file_type);
//echo "The file ". basename( $_FILES['u_file']['name']). " is uploaded";
if ($file_type != "application/pdf" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/jpg") {
echo "Sorry, only JPG, JPEG, PNG & PDF files are allowed.";
$uploadOk = 0;
}
if (file_exists($targetfile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($uploadOk==0){
echo "Problem in uploading file";
}
else {
if(move_uploaded_file($_FILES['u_file']['tmp_name'], $targetfile)) {
$fileUpQueryjob = "INSERT INTO jobs (job_name,job_type,job_salary,job_location,job_filename) VALUES ('$jobName','$jobType','$jobSalary','$jobLocation','$file_name')";
$upJob = $db->query($fileUpQueryjob);
if ($upJob == true) {
$val = "Success";
echo "The file ". basename( $_FILES['u_file']['name']). " is uploaded";
}
else
echo "Error: " . $fileUpQueryjob . "<br>" . mysqli_error($db);
}
}
//echo "$val";
$db->close();
?>

It may be due to the fact that your button type is 'sumbit' and its taking preference over the onlick. So cleanest way, remove submit type, and manually submit after validation:
<button name="submitJob" id="submitJob" class="btn btn-default" onClick="job_checker()">Submit</button>
Find your DOM form on your "validating" function, and submit it if all is ok:
function job_checker() {
// just refactor all these functions to return "true" or "false"
var isValid = checkJobName() &&
checkSalary() &&
checkJobType() &&
checkJobLoc() &&
databasejobEntry();
// if all these validations went through,
if (isValid) {
document.querySelector('#jobForm').submit();
}
}

There are errors in your javascript. Try this:
JAVASCRIPT
signFlagj = 0;
function job_checker()
{
checkJobName();
checkSalary();
checkJobType();
checkJobLoc();
databasejobEntry();
}
function checkJobName()
{
var jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
var jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname))
{
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else jobnameError.innerHTML = "";
}
function checkSalary()
{
var salaryET = document.getElementById("sal");
var salaryError = document.getElementById("salErr");
var jobsal = salaryET.value;
console.log(jobsal);
var regex = /^[1-9.,][0-9.,]*$/;
if(!regex.test(jobsal))
{
salaryError.innerHTML = "Only numbers with or without comma or point is allowed";
signFlagj = 1;
}
else salaryError.innerHTML = "";
function checkJobType()
{
var jobTypeET = document.getElementById("jType");
var jobType = jobTypeET.value;
console.log(jobType);
}
function checkJobLoc()
{
var jobLocET = document.getElementById("loc");
var locError = document.getElementById("locErr");
var jobLocation = jobLocET.value;
console.log(jobLocation);
var regex = /^[a-zA-Z0-9\/\s,'-]*$/;
if(!regex.test(jobLocation))
{
locError.innerHTML = "Enter valid amount";
signFlagj = 1;
}
else locError.innerHTML = "";
}
function showname()
{
var jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
/*
function toSubmit()
{
preventDefault();
alert('I will not submit');
return false;
}
*/
function databasejobEntry()
{
if(signFlagj==1)
{
console.log("fill up correctly!");
alert("Sign up correctly!");
window.location.href = "test.html";
}
else
{
// console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success")
{
alert("Successfully submitted :)");
var formdata = $('#jobform').serializeArray();
//alert(formdata);
document.getElementById("jobform").submit();
//window.location.href = "uploadJob.html";
}
}
}
xhttp.open("POST", "test.php?jobname="+jobname+"&jobType="+jobType+"&jobsal="+jobsal+"&jobLocation="+jobLocation+"&jobFilename="+jobFilename,true);
//xhttp.open("POST", "three.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xhttp.open("POST", "test.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
PHP
<?php
require_once('DBconnection.php');
// ...
// Since you are using a database connection consider using a function
// to escape strings like mysli_real_escape_string() if you are using MySQL
$jobName = $_POST["jName"];
$jobType = $_POST["jType"];
$jobSalary = $_POST["sal"];
$jobLocation = $_POST["loc"];
?>

Related

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

Pass Array From Select Into xmlhttp

I want to pass an array of values from my select into the xmlhttp.open request below so I can parse the variables in the new page. How can this be achieved? I attempted the syntax below, but it throws a 500 error when the button is pressed.
<script type="text/javascript">
function GetData() {
var xmlhttp = new XMLHttpRequest();
var hiredate = document.getElementById("hiredate").value;
var termdate = document.getElementById("termdate").value
var arr = document.getElementById("bq").value;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "Query.php?hiredate="+hiredate+"&termdate="+termdate+"&array="+arr, true);
xmlhttp.send();
}
</script>
<select name="bq" size="12" multiple="multiple" tabindex="1">
<option value="HireDate">HireDate</option>
<option value="TermDate">TermDate</option>
<option value="Dept">Dept</option>
<option value="Manager">Manager</option></select>
Start Date: <input type="date" name="hiredate" id="hiredate">
End Date: <input type="date" name="termdate" id="termdate">
<input type="submit" value="Submit" id="ajaxButton" onclick="GetData()">
<div id="data">
EDIT
This is my Query.php - I omitted the actual connection to the server as I know that is sound
<?php
$hiredate = $_GET['hiredate'];
$termdate = $_GET['termdate'];
$sql = '';
$selected_fields = array();
foreach ($_GET['array'] as $selectedOption){
$selected_fields[] = $selectedOption;
}
if(!empty($selected_fields)){
$fields = implode(',', $selected_fields);
$sql = 'SELECT '.$fields.' from testtable';
}
$sql = $sql & "WHERE hiredate = $hiredate AND termdate = $termdate";
echo $sql
?>

How to know if the do_upload is already started and done?

I'm using CodeIgniter, and I created a form where the user can upload a video. I wanted to create a progress bar to show the user its still uploading and hides it after the upload is done. What I wanted to do is when the submit button is click it will call my loading gif and i want it to keep loading until the upload is finished. How can i detect if the upload is finish?
CSS
<?php echo form_open_multipart('video_controller/video_form');?>
<div class="form-group">
<label for="title">Video</label>
<input type="file" accept=".mp4" class="form-control" name="video_field" placeholder="Video"></input>
</div>
<button class="btn btn-success pull-right" type="submit" value="upload" id="btn-submit">Create</button>
<?php echo form_close();?>
CodeIgniter
public function video_form(){
if (empty($_FILES['video_field']['name'])){
$this->form_validation->set_rules('video_file', 'Video File', 'required');
}
if($this->form_validation->run() == FALSE){
.....
}else{
$uploaderror = "";
$video_info = $this->upload_videos();
.....
Insert query code here
.....
}
}
private function upload_videos(){
$config = array();
$config['upload_path'] = './uploads/videos/';
$config['allowed_types'] = 'mp4';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('video_field'))
{
$error_msg = $this->upload->display_errors('','');
error_log('UPLOAD ERROR: '.$error_msg);
if($error_msg!='You did not select a file to upload.'){
$filename = array('error' =>$error_msg.'('. $this->input->post('video_field') .')');
}
}
else
{
$vid = $this->upload->data();
$filename = array('video_field' =>$vid['file_name']);
}
return $filename;
}
You can use change event, XMLHttpRequest.upload.progress event
html
<input type="file" /><progress min="0" max="0" value="0"></progress>
javascript
var progress = $("progress");
$(":file").change(function(e) {
var file = e.target.files[0];
progress.val(0);
var request = new XMLHttpRequest();
if (request.upload) {
request.upload.onprogress = function(event) {
if (progress.val() == 0) {
progress.attr("max", event.total)
}
if (event.lengthComputable) {
// show `.gif` or update `progress` value here
// if `event.loaded` === `event.total`
// set `.gif` `display` to `none`
console.log(event.loaded, event.total);
progress.val(event.loaded)
}
}
request.onload = function() {
// do stuff with response
}
};
request.open("POST", "/path/to/server/");
request.send(file)
});
jsfiddle https://jsfiddle.net/576wrxLg/
i did the same in my codeigniter project with this code in JS..
i am 100% sure this will work for you. :)
$('#importForm').submit(function(e) {
var formData = new FormData(this);
$.ajax({
type:'POST',
url: base_url + "student/importAjax",
data:formData,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
cache:false,
contentType: false,
processData: false,
dataType : "json",
success:function(data){
//console.log(data);
}
});
e.preventDefault();
});
function progress(e){
if(e.lengthComputable){
var max = e.total;
var current = e.loaded;
var Percentage = (current * 100)/max;
console.log(Percentage);
$('#progress-bar').css('width',Percentage+'%');
$('.sr-only').html(Percentage+'%');
if(Percentage >= 100)
{
// process completed
}
}
}
and this is my view (Bootstrap theme)
<form name="importForm" id="importForm" enctype="multipart/form-data">
<?php //echo form_open_multipart('admin/upload/do_upload'); ?>
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Select File</label>
<input type="file" id="importInputFile" name="importInputFile" />
<p class="help-block">.xls / xlsx </p>
</div>
<div class="form-group">
<input type="checkbox" name="mid_term" class="check"><label style="margin-left: 10px;"> Mid Term User</label>
</div>
<div class="progress progress-sm active">
<div style="width:0%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="20" role="progressbar" id="progress-bar" class="progress-bar progress-bar-success progress-bar-striped">
<span class="sr-only"></span>
</div>
</div>
<div class="box-footer">
<button class="btn btn-primary" id="ajaxImportUpload" type="submit">Submit</button>
</div>
</div>
</form>
my Controller
public function importAjax() {
$upload_path = './uploads/';
$newname = rand(0000, 9999) . basename($_FILES["importInputFile"]["name"]);
$target_file = $upload_path . $newname;
$filename = $newname;
$filenameArray = explode(".", $filename);
$extension = end($filenameArray);
if ($extension == 'xlsx' || $extension == 'xls') {
if (move_uploaded_file($_FILES["importInputFile"]["tmp_name"], $target_file)) {
// echo "The file ".$newname . " has been uploaded.";
} else {
//echo "Sorry, there was an error uploading your file.";
}
$this->load->library('Excel');
$csvData = $this->excel->parseFile($target_file, false);
$fileType = 'Excel';
} else {
echo json_encode(array('error' => true, 'msg' => 'xlsx and xls are allowed extnsion'));
return false;
}
array_shift($csvData);
$user = array();
if (isset($_POST['mid_term']) && $_POST['mid_term'] == 'on') {
$mid_term = 1;
} else {
$mid_term = 0;
}
$insertedCount=0;
$totalCount=0;
foreach ($csvData as $studentData) {
$totalCount++;
$id = $this->StudentModel->checkImportSchool($studentData[2]);
$cid = $this->StudentModel->checkImportclass($studentData[7]);
$sid = $this->StudentModel->checkImportStudentUsername($studentData[0]);
if ($id > 0 && $sid=="notFound") {
$fullname = explode(" ", $studentData[1]);
if (isset($fullname[1]) == '')
$middlename = '';
else
$middlename = $fullname[1];
if (isset($fullname[2]) == '')
$lastname = '';
else
$lastname = $fullname[2];
$user['username'] = $studentData[0];
$user['firstname'] = $fullname[0];
$user['middlename'] = $middlename;
$user['lastname'] = $lastname;
$user['phone'] = $studentData[3];
$user['email'] = $studentData[4];
$password_salt = substr(sha1(uniqid(rand(), true)), 1, 20);
$password = md5($studentData[5] . $password_salt);
$parentPassword = md5($studentData[6] . $password_salt);
$user['password'] = $password;
$user['parentPassword'] = $parentPassword;
$user['password_salt'] = $password_salt;
$user['mid_term'] = $mid_term;
$user['userType'] = 'student';
$school = $id;
$class = $cid;
$this->StudentModel->importFromExcel($user, $class, $school);
$insertedCount++;
}
else {
$skipData[]=$studentData;
}
}
unlink($target_file);
if(!empty($skipData)){
$this->session->set_userdata(array('item'=>$skipData));
}
else{
$skipData=array();
}
$skipDataCount=count($skipData);
echo json_encode(array('error' => false, 'msg' => 'Data Inserted Successfully','skipData'=>$skipData,'insertedCount'=>$insertedCount,'skipDataCount'=>$skipDataCount,'totalCount'=>$totalCount));
}

Uncaught SyntaxError: Unexpected token < (anonymous function) on console

I am creating an upload file application. I wrote it using AJAX and PHP.
It is working fine on the localhost but when I uploaded it to my web server. It returns the error:
Uncaught SyntaxError: Unexpected token <
It is pointing to the line
uploaded = JSON.parse(this.response);
This line is in my upload.js script file
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
Here are the other codes for reference
upload.php
<?php
header('Content-Type: application/JSON');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
and here's my html form
index.php
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
anchor = document.createElement('p');
anchor.innerText = "Upload Completed!";
anchor.target = '_blank';
succeeded.appendChild(anchor);
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
This code works on the localhost. It is uploading the files to my localhost server and shows the loading progressbar.
But when I deploy this to my web server it shows the progressbar loading slowly until it reaches 100%. But when I look into the uploads directory in my server nothing was uploaded.
you have a missing } at the end of the code in upload.php, before the php end (?>):
'failed' =>$failed
));
}
}
?>

Ajax calling is breaking my code

I'm trying to make a multiplayer turn-based browser game with Ajax, Javascript and Php and in order to actually play the game you have to type in a user's username and it searches for that player. But when I try to add that function in it breaks my code when repeats all the html. When I view the network via inspect element with Chrome, it show that it keeps sending requests to the jquery and then it get stuck on the pre-loader, but when i take the isset post out from the php it loads, but I can't search for a player. How would I go about fixing this issue? Here is my code
Javascript: var match = null;
function popUp(what){
if(!what) errorMessage('Error: params', 'params', 'none');
switch(what){
case 'search':
preLoad('Loading please wait . . .');
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
$('.search').load('./?page=game&mode=search&type=private', function(){
$('#preloader').fadeOut('slow',function(){
$('#preloader').remove();
});
});
break;
case 'match':
$.ajax({
url : _path + "/core/ajax.php",
type : 'POST',
data : { f: 'checkMatch'},
dataType : 'text',
success : function(data) {
if(data){
$('#main_container').prepend(data);
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
}
});
break;
case 'submit':
$.post('./?page=game&mode=search&type=private', $("#form-pb").serialize(), function(data){
var $response=$(data);
var error = $response.filter('h3').text();
$('.search').html(data);
if(!error){
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content'); var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
});
break;
}
}
Php: if (isset($_GET['mode'])) {
$mode = $secure->clean($_GET['mode']);
} else {
$mode = '';
}
if ($mode == 'selection') {
$page_title .=' > Character Selection';
$page_titles .= ' Character Selection - Power Bond';
} else if ($mode == 'search') {
if (isset($_GET['type'])) {
$type = $secure->clean($_GET['type']);
} else {
$type = '';
}
if ($type == 'private') {
if (isset($_POST['pbsubmit'])) {
$name = $secure->clean($_POST['name']);
}
}
}
if (isset($_POST['f']) && $_POST['f'] == 'checkMatch') {
$checkMatch = $db->query("SELECT * FROM accounts WHERE `id` = '".$account['id']."'");
while ($info = mysql_fetch_array($checkMatch)) {
$status = $info['status'];
$gameid = $info['gameid'];
}
$getGame = $db->fetch("SELECT * FROM Games WHERE `gameid` = '$gameid'");
$status = $info['status'];
$gameid = $info['gameid'];
if(!$getGame = 'NULL') {
$data = 'testaeta';
} else {
$data = '<h1> Who do you want to battle against? </h1>
<br />
<form action="" method="post" id="form-pb" name="pb" target="_self">
USERNAME:<input name="name" type="text" size="40" maxlength="40" />
<input name="pbsubmit" type="submit" value="Search"/>
</form>
<a class="goback" href="#">Cancel</a>';
}
echo $data;
}

Categories

Resources