Ajax does not display the result from mysql database - php

I have an issue with my ajax request and I can't figure out what is wrong, in console there is no error...
Here is my javascript file:
$(document).ready(function(){
done();
});
function done(){
setTimeout(function(){
updates();
done();
}, 50000);
}
function updates() {
$.getJSON("sedinte.php", function(data){
$("#results").empty();
$(".pagination").empty();
$.each(data.result, function() {$("#results").append("<tr class='"+this['aclass']+"'><td>"+this['object']+"</td><td>"+this['date']+"</td><td>"+this['amount']+"</td><td>"+this['paid']+"</td></tr>");
});
$.each(data.pagination, function() {
$("ul.pagination").append(this['controls']);
});
});
}
$("#btnAdd").click(function(){
$.post(
$("#addForm").attr("action"), $("#addForm :input").serializeArray(), function(info) {
$("#feedback").html(info);
});
clearInput();
});
$("#addForm").submit(function(){
return false;
});
function clearInput() {
$("#addForm :input").each( function() {
$(this).val(' ');
});
}
Here is my file I want to request:
<?php
#Get the total number of rows
$rows = $db->getTotalRows("sedinte");
#Set number of result to show on each page
$page_rows = 10;
#Get the last page
$last = ceil($rows/$page_rows);
#Make sure the last page is not below 1
if($last <1)
{
$last = 1;
}
$pagenum = 1; #Default page
#Get page number from URL vars if it is pressent, else it is = 1
if(isset($_GET['page']))
{
$pagenum = preg_replace('#[^0-9]#', '', $_GET['page']);
}
#Make sure the page number isn't below 1, or more than our last page
if($pagenum < 1)
{
$pagenum = 1;
}
else if($pagenum > $last)
{
$pagenum = $last;
}
#This sets the range of rows to query for the chosen page number
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows . ',' .$page_rows;
#This is for grabbing just one page worth of rows by applying limit
$sql = "SELECT * FROM sedinte ORDER BY id DESC $limit";
$query = mysqli_query($db->Conn(), $sql);
#Enstablish the pagination controls variable
$paginationCtrls = null;
#<li>2 <span class="sr-only">(current)</span></li>
#If there is more than 1 page worth of results
if($last != 1)
{
if($pagenum > 1)
{
$previous = $pagenum - 1;
$paginationCtrls .= '<li>«</li>';
#Render clickable number links that should appear on the left of the target page number
for($i = $pagenum - 4; $i < $pagenum; $i++)
{
if($i > 0)
{
$paginationCtrls .= '<li>'.$i.'</li>';
}
}
}
#Render the current page
$paginationCtrls .= '<li class="active">'.$pagenum.'<span class="sr-only">(current)</span></li>';
#Render clickable number lnks that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++)
{
$paginationCtrls .= '<li>'.$i.'</li>';
if($i >= $pagenum+4)
{
break;
}
}
if($pagenum != $last)
{
$next = $pagenum + 1;
$paginationCtrls .= '<li>»</li>';
}
}
$paginationArray = array();
array_push($paginationArray, array('controls' => $paginationCtrls));
$listTest = null;
$resultArray = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
//$id = $row['id'];
$obiect = $row['obiect'];
$data = $row['data'];
$suma = $row['suma'];
$achitat = $row['achitat'];
if($achitat == 'Da')
{
$active_class= null;
}
else
{
$active_class= "danger";
}
array_push($resultArray, array('object' => $obiect,
'date' => $data,
'amount' => $suma,
'paid' => $achitat,
'aclass' => $active_class
));
/*
$listTest .=' <tr class="'.$active_class.'">
<td>'.$obiect.'</td>
<td>'.$data.'</td>
<td>'.$suma.'</td>
<td>'.$achitat.'</td>
</tr>';*/
}
echo json_encode(array("result" => $resultArray, "pagination" => $paginationArray));
mysqli_close($db->Conn());
?>
And here is my index file:
<?php
require 'includes/settings.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sedinte</title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-md-12">
<div role="tabpanel">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><span class="glyphicon glyphicon-eye-open"></span> Vezi Sedinte</li>
<li role="presentation"><span class="glyphicon glyphicon-plus-sign"></span> Adauga Sedinta</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="sedinte">
<div class="row">
<div class="col-xs-6 col-md-4">
<h4><span class="glyphicon glyphicon-usd"></span> Buget: 460 RON</h4>
</div>
<div class="col-xs-6 col-md-4 col-md-offset-4">
<h4><span class="glyphicon glyphicon-calendar"></span> Data: <?php echo date('D d M Y');?></h4>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th><span class="glyphicon glyphicon-edit"></span> Obiect</th>
<th><span class="glyphicon glyphicon-calendar"></span> Data</th>
<th><span class="glyphicon glyphicon-usd"></span> Suma</th>
<th><span class="glyphicon glyphicon-ok"></span> Achitat</th>
</tr>
</thead>
<tbody id="results">
<?php //echo $listTest;?>
</tbody>
</table>
<ul class="pagination">
<?php //echo $paginationCtrls;?>
</ul>
</div>
<div role="tabpanel" class="tab-pane" id="adauga">
<div class="row">
<div class="col-md-6 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-body">
<form action="add.php" method="post" id="addForm">
<div class="form-group">
<label for="obiect">Obiect</label>
<input type="text" class="form-control" name="boxObiect" placeholder="M, L, R">
<!--
<select name="boxObiect" class="form-control">
<option>Matematica</option>
<option>Romana</option>
<option>Logica</option>
</select>
-->
</div>
<div class="form-group">
<label for="data">Data: </label>
<input type="text" class="form-control" name="boxData" placeholder="YYYY-MM-DD">
</div>
<div class="form-group">
<label for="radioAchitat">Achitat: </label>
<label class="radio-inline">
<input type="radio" name="radioAchitat" id="radioAchitat" value="Da"> Da
</label>
<label class="radio-inline">
<input type="radio" name="radioAchitat" id="radioAchitat" value="Nu" checked="checked"> Nu
</label>
</div>
<button type="submit" id="btnAdd" class="btn btn-primary">Adauga</button>
</form>
</div>
</div>
<div id="feedback"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="ajax/main.js"></script>
</body>
</html>
My data from the database is not showing... just the main template.
Please help me!

I Don't kow what's the problem because i did not read the full code, but that is a bug that i found so you can correct that and can try again :), i hope it will work, Thanks
header('Content-type: application/json');
echo json_encode(array("result" => $resultArray, "pagination" => $paginationArray));
mysqli_close($db->Conn());

Related

how to remember the radio selection?

after I post it use ajax,the value of radio disappear,but I want the radio part to remember the selection. I need the page to remember the radio button selections when I leaves and returns. Would this require database? If so, how do i implement it? I try to add the select =selected ,but it do not help.
<input value="<?php echo $key; $key++;?>" type="radio" class="radioOrCheck" name="answer<?php echo $num_select;?>"
id="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>"
below it is the full code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/iconfont.css" rel="stylesheet" type="text/css" />
<link href="css/test.css" rel="stylesheet" type="text/css" />
<style>
.hasBeenAnswer {
background: #5d9cec;
color:#fff;
}
</style>
</head>
<body>
<p>
</p>
<div class="main">
<!--nr start-->
<div class="test_main">
<div class="nr_left">
<div class="test">
<form action="" method="post">
<div class="test_title">
<!--
<p class="test_time">
<i class="icon iconfont"></i><b class="alt-1">01:40</b>
</p>-->
<font><?php echo "<input type='button' name='test_jiaojuan' value='sub' onClick='getinput($ans_json,$id_json)'>";?>
</font>
</div>
<div class="test_content">
<div class="test_content_title">
<h2>word</h2>
<p>
<span>has</span><i class="content_lit"><?php echo $cnt_sel;?></i><span>title</span><span>sum</span><i class="content_fs"><?php echo $cnt_sel*10;?></i><span>min</span>
</p>
</div>
</div>
<div class="test_content_nr">
<ul>
<!--begin select-->
<?php
foreach($results as $temp){
$sql_2="SELECT `description`,`input`,`select_id` FROM `select` WHERE `select_id`=?";
$res_2=pdo_query($sql_2,$temp[0]);
$row = $res_2[0];
?>
<li id="qu_0_<?php echo $num_select;?>">
<div class="test_content_nr_tt">
<i><?php echo $num_select;?></i><font>
<p>
<?php
echo $row[0];
?>
</p>
</font>
</div>
<div class="test_content_nr_main">
<ul>
<?php
if ($row[1]) {
$arr = rtrim($row[1],"<br />");
$arr = explode('<br />', $arr);
foreach($arr as $key => $a){
?>
<li class="option">
<input value="<?php echo $key; $key++;?>" type="radio" class="radioOrCheck" name="answer<?php echo $num_select;?>"
id="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>"
/>
<label for="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>">
<p class="ue" style="display: inline;"><?php echo strip_tags($a,"<img>");//echo trim($a); ?></p>
</label>
</li>
<?php
}
}
if ($row['hint']) {
?><h4><?php echo $MSG_HINT;?></h4><?php
echo $row['hint'];
}
?>
</ul>
</br></br>
</div>
</li>
<?php
$num_select=$num_select+1;
}
?>
<p>
<?php
?>
</p>
<!--end select-->
</ul>
</div>
</form>
</div>
</div>
<div class="nr_right">
<div class="nr_rt_main">
<div class="rt_nr1">
<div class="rt_nr1_title">
<h1>
<i class="icon iconfont"></i>answer
</h1>
<!-- <p class="test_time">
<i class="icon iconfont"></i><b class="alt-1">01:40</b>
</p>-->
</div>
<div class="rt_content">
<div class="rt_content_tt">
<h2>chose</h2>
<p>
<span>sum</span><i class="content_lit"><?php echo $cnt_sel;?></i><span>answer</span>
</p>
</div>
<div class="rt_content_nr answerSheet">
<ul>
<?php
$temp=1;
for($temp=1;$temp<=$cnt_sel;$temp++){
?>
<li><?php echo $temp;?></li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!--nr end-->
<div class="foot"></div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery.easy-pie-chart.js"></script>
<script src="js/jquery.countdown.js"></script>
<script>
$(function() {
$('li.option label').click(function() {
debugger;
var examId = $(this).closest('.test_content_nr_main').closest('li').attr('id');
var cardLi = $('a[href=#' + examId + ']');
if(!cardLi.hasClass('hasBeenAnswer')){
cardLi.addClass('hasBeenAnswer');
}
});
});
$(function() {
$('li.option').click(function() {
debugger;
var examId = $(this).closest('.test_content_nr_main').closest('li').attr('id');
var cardLi = $('a[href=#' + examId + ']');
if(!cardLi.hasClass('hasBeenAnswer')){
cardLi.addClass('hasBeenAnswer');
}
});
});
/*window.onbeforeunload = function(event){
var msg = '';
msg +='do not like?\n';
//msg += '';
return msg;
};*/
function getinput(ans_json,results_json) {
var sum=<?php echo $cnt_sel;?>;
var blank_cnt=0;
var well_cnt=0;
for (var i = 1; i <= sum; i++) {
var radio_name = new String("answer" + i.toString());
var ans_s = $('input:radio[name=' + radio_name + ']:checked').val();
if(!(ans_s)){
blank_cnt++;
}}
//var json = getjson();
var msg = "ok";
if (confirm(msg) == true) {
var radio = new Array();
for (var i = 1; i <= <?php echo $cnt_sel;?>; i++) {
var radio_name = new String("answer" + i.toString());
var ans_s = $('input:radio[name=' + radio_name + ']:checked').val();
if(!(ans_s)){
ans_s=-1;
}
var judge=0;
var answer_true= parseInt(ans_json[i-1]);
var id_true=parseInt(results_json[i-1]);
if(ans_s == answer_true){
judge=1;
}
$.ajax({
type: "GET",
url: "select_ajax.php",
data: {
select_id: id_true,
contest_id:<?php echo $cid;?>,
result:judge
},
success: function(msg){
well_cnt++;
}
});
}
if(well_cnt==5){
alert('success');
}
setTimeout(function (){
window.location.href = "contest.php?cid="+<?php echo $cid;?>;
}, 1000);
} else {
return false;
}
}
</script>
</body>
</html>
You can do it by storing your radio button value in javascript localStorage and then set that localStorage value to your radio button again.

Search filter bootstrap card didn't show the specific image

When I'm searching the specific name of the image. The rest of the name of the row still showing, but I just want to view only the data from the search. See image below
Display: Select all the data from the database.
<?php$checkQuery = "SELECT `h_business_logo`,`h_business_name`,`h_business_desc` FROM user_bsns WHERE h_isActive = 1 ORDER BY h_business_name DESC";
$checkResult = mysqli_query($db->conn, "$checkQuery")
?>
Card: This card has an animation
<div class="card-body col-lg-12" >
<div class="card-body col-lg-12">
<input class="form-control" id="myInput" type="text" placeholder="Search.." style="float:left; width:25%;">
<button class="btn" style="margin-left: 5px;background-color: #e72329;color: white;"> Search </button>
</div>
<?php
if(mysqli_num_rows($checkResult) > 0):{
}
while($row = mysqli_fetch_array($checkResult)){
?>
<div class="panel" id="myDIV">
<div class="holder flipH" >
<div class="card shadow-none">
<div class="col-sm-0 column <?=$row['h_business_name'];?>" >
<div class="front"style="float:left; >
<img src="<?=$row['h_business_logo']; ?> "
style="height:150px; width:155px; border-radius: 50%; ">
</div>
</div>
<span style= "text-align:center;">
<h5><?=$row['h_business_name'];?></h5>
</span>
<span style="text-align:center;">
<p><?=$row['h_business_desc'];?></p>
</span>
</div>
</div>
</div>
<?php
}
endif;
?>
</div>
<!-- /.card-body -->
</div>
And this one is the function of the search filter.
<script>
$(document).ready(function(){
$(".btn").on("click", function() {
var value = $("#myInput").val();
lastval = "col-sm-5 column "+value;
x = document.getElementsByClassName("column");
$("#myDIV div").filter(function() {
for (i = 0; i < x.length; i++) {
element = x[i];
if (element.className.indexOf(value) == -1){
element.classList.add("nonshow");
element.classList.remove("show");
}
else {
element.classList.add("show");
element.classList.remove("nonshow");
}
}
});
});
});
</script>
Please help me to improve the codes.
Update: I solved my problem using this script(jquery)
update: I used this script in order to search automatically.
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDiv ").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
});

How to convert from string to array with angularjs?

I'm trying to delete a row from my database table using php and angular. I'm using "Splice" but my data is a string and I need to convert to an array. can someone please help?
This is my code:
controller:
$scope.delete = function(deletingId, $index) {
var params = $.param({"customer_id":deletingId});
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/hamatkin/api/delete-customer.php/',
method: "GET",
data: params
}).success(function(data){
console.log(data);
var arr=JSON.parse(JSON.stringify(data))
$scope.customerDetails = arr;
$scope.customerDetails.splice($index, 1);
The error I'm getting :
angular.js:13550 TypeError: $scope.customerDetails.splice is not a function
delete-customer.php
<?php header('Content-Type: text/html; charset=utf-8');
$connect=mysqli_connect("localhost", "root", "", "hamatkin");
include_once 'Customer.php';
mysqli_query($connect,"SET character_set_client = utf8");
mysqli_query($connect,"SET character_set_connection = utf8");
mysqli_query($connect,"SET character_set_results = utf8");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$customer = new Customer();
if(isset($_GET['customer_id'])){
$customer_id = $_GET['customer_id'];
$del = "DELETE FROM posts WHERE customer_id='".$customer_id."'";
mysql_query($connect, $del);
}
$newURL = "/hamatkin/#/customerCards";
header('Location: '.$newURL);
?>
html
<tbody>
<tr ng-repeat="x in customers | filter:search_query | orderBy: order_query:reverse_query">
<!-- <td>{{$index + 1}}</td> -->
<td>{{ x.customer_id}}</td>
<td>{{ x.kind_Of_Customer}}</td>
<td>{{ x.full_name}}</td>
<td>הצג פרטי לקוח </td>
<td><a ng-click="delete(x.customer_id, $index)" class="btn btn-primary btn- active">מחיקה</td>
</tr>
</tbody>
console.log(data)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Styles -->
<link rel="stylesheet" href="lib\bootstrap.css" />
<link rel="stylesheet" href="styles/layout.css" />
<!-- Liberaries -->
<script src="scripts/angular.min.js"></script>
<script src="lib/jquery-1.12.0.min.js"></script>
<!-- <script src="lib/angular.js"></script> -->
<script src="lib/angular-route.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>
<!-- <script src="scripts/angular-route.min.js"></script> -->
<script src="lib/bootstrap.js"></script>
<link href="scripts\bootstrap.min.js" />
<!-- Application Model, Direectives, Services & Controllers -->
<script src="scripts/App.js"></script>
<!-- <script src="scripts/angular.min.js"></script> -->
<!-- controllers-->
<script src="Controllers/loginCtrl.js"></script>
<script src="Controllers/customerFormCtrl.js"></script>
<script src="Controllers/customerCardsCtrl.js"></script>
<script src="Controllers/stockCtrl.js"></script>
<script src="Controllers/bodyCtrl.js"></script>
<script src="Controllers/ordersCtrl.js"></script>
<script src="Controllers/reportsCtrl.js"></script>
<script src="Controllers/recordExpensesCtrl.js"></script>
<script src="Controllers/supplierListCtrl.js"></script>
<script src="Controllers/supplierFormCtrl.js"></script>
<script src="Controllers/customerCardDetailsCtrl.js"></script>
<title>מערכת מידע רומן המתקין</title>
</head>
<body ng-app="dataSystem" ng-controller="bodyCtrl">
<!--Navigation Bar-->
<nav class="navbar navbar-inverse navbar-fixed-top" ng-hide="isNavTabsHidden()">
<div class="container-fluid">
<div class="navbar-header navbar-right">
<img class="img-rounded" src="images/black logo.jpg" style="width:155px" />
</div>
<ul class="nav navbar-nav navbar-right">
<li>דוחות</li>
<li>הכנסות והוצאות</li>
<li>ניהול מלאי וספקים</li>
<li>ניהול הזמנות</li>
<li>ניהול לקוחות</li>
</ul>
<ul class="nav navbar-nav navbar-left">
<li><span class="glyphicon glyphicon-log-out"></span> התנתק</li>
<li><span class="glyphicon glyphicon-wrench"></span> ניהול הרשאות</li>
</ul>
</div>
</nav>
<br /><br /><br />
<!--טאב ניהול לקוחות-->
<div class="containers-wrapper">
<div class="container" ng-hide="costumerHidden()">
<div class="list-group">
טופס רישום לקוח
כרטיסי לקוחות
רשימת פניות מלקוחות
</div>
</div>
<!--טאב ניהול מלאי וספקים-->
<div class="container" ng-hide="stockHidden()">
<div class="list-group">
טופס רישום מלאי
טופס עריכת/מחיקת מלאי
רשימת מלאים למכירה
רשימת ציוד עבודה
בדיקת זמינות מלאי
טופס רישום ספק
רשימת ספקים
</div>
</div>
<!--טאב ניהול הזמנות-->
<div class="container" ng-hide="ordersHidden()">
<div class="list-group">
טופס הזמנה חדשה
רשימת הזמנות
טופס הצעת מחיר
הצעות מחיר בהמתנה
</div>
</div>
<!--טאב דוחות-->
<div class="container" ng-hide="reportsHidden()">
<div class="list-group">
דו"ח מלאים לפי סוגים
דו"ח הצעות מחיר
דו"ח מכירות על פי סוגי מלאי
דו"ח הוצאות לספקים
דו"ח הוצאות לפי חודשים
דו"ח הכנסות לפי חודשים
דו"ח לקוחות חדשים חודשי
</div>
</div>
<!--טאב הכנסות והוצאות-->
<div class="container" ng-hide="isIncome_expensesHidden()">
<div class="list-group">
טופס תיעוד הוצאה
טופס תיעוד הכנסה
רשימת הוצאות
</div>
</div>
<!--left side screen-->
<div class="view-content left-side-screen">
<ng-view></ng-view>
</div>
</div>
<!--Footer-->
<div class="footer" ng-hide="isFooterHidden()">
<p>Copyright # 2016 Denis & Denis. All Rights Reserved</p>
</div>
</body>
</html>
Hi u have to first find the index which one u wants to splice then u have to splice , SPlice is for Array Items check whether the Item is array first for refrence https://plnkr.co/edit/Nzz4T4AmkLmcr7frxyH1?p=preview
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.arrylist = [{
"id": 53,
"name": "abced"
}, {
"id": 53,
"name": "gayu"
}]
$scope.doc = {
"id": 53,
"name": "abced"
}
console.log($scope.arrylist)
var index = $scope.arrylist.findIndex(function(item) {
if (item.id == $scope.doc.id) {
return true;
}
});
if (index !== -1) {
//Removing the test from list;
$scope.arrylist.splice(index, 1);
}
console.log($scope.arrylist)
});
Using JSON.parse will turn JSON into JS object. In your scenario, you are invoking a splice function which exists on Array prototype, whereas your arr variable is in fact a plain string object which has no such function.
Assuming your string is formatted in some way, let's say - customer names are seperated by a comma, you can use split function. This will turn your string into an array of seperated elements devided by the required format.
Like this:
var clientsToDelete = arr.split(","); // comma splitting
clientsToDelete.splice($index, 1);

Name being inserted, but file is not being uploaded [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I've an upload input field in a form. the problem that the name of the file is being inserted in the database but the file is not being uploaded to the server, and the same code is working on the same server in a different file in the same directory but in a different query. form is set to enctype="multipart/form-data",
here is the code where its not working
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/dbc.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php confirm_logged_in(); ?>
<?php find_selected_post(); ?>
<?php
$target = "../upload/";
$target = $target . basename( $_FILES['post_photo']['name']);
if (intval($_GET['cat']) == 0) {
redirect_to('cat_posts.php');
}
include_once("includes/form_functions.php");
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('post_title', 'position', 'visible', 'post_content');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$fields_with_lengths = array('post_title' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
$category_id = mysql_prep($_GET['cat']);
$post_title = trim(mysql_prep($_POST['post_title']));
$post_content = mysql_prep($_POST['post_content']);
$post_description = mysql_prep($_POST['post_description']);
$post_keywords = mysql_prep($_POST['post_keywords']);
$post_tags = mysql_prep($_POST['post_tags']);
$post_photo =($_FILES['post_photo']['name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
if (empty($errors)) {
$query = "INSERT INTO ss_posts (
post_title, post_content, post_description, post_keywords, post_tags, post_photo, position, visible, category_id
) VALUES (
'{$post_title}', '{$post_content}', '{$post_description}', '{$post_keywords}', '{$post_tags}', '{$post_photo}', {$position}, {$visible}, {$category_id}
)";
if ($result = mysql_query($query, $connection)) {
$message = "Successfully Created.";
$new_post_id = mysql_insert_id();
redirect_to("cat_posts.php?post={$new_post_id}");
} else {
$message = "The Post Could Not Be Created.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
}
?>
<?php
error_reporting(E_ALL);
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo "<br/>target: " . $target;
if (!move_uploaded_file($_FILES['post_photo']['tmp_name'], $target)) {
echo "<br/>Upload failed.";
} else {
echo "<br/>Upload done.";
}
?>
<meta charset="utf-8"/>
<title>New Post - Administration Panel</title>
<script src="js/ckeditor/ckeditor.js" type="text/javascript"></script>
<link rel="stylesheet" href="js/ckeditor/sample.css">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/form.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/button.css" type="text/css" media="screen" /> <!--[if lt IE 9]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="js/hideshow.js" type="text/javascript"></script>
<script src="js/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.equalHeight.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".tablesorter").tablesorter();
}
);
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
</script>
<script type="text/javascript">
$(function(){
$('.column').equalHeight();
});
</script>
</head>
<body>
<header id="header">
<hgroup>
<h1 class="site_title">Administration Panel</h1>
<h2 class="section_title">New Post</h2><div class="btn_view_site">
View Site</div>
</hgroup>
</header>
<!-- end of header bar -->
<section id="secondary_bar">
<div class="user">
<p>Hello, <?php echo $_SESSION['username']; ?> (Logout)</p>
</div>
<div class="breadcrumbs_container">
<article class="breadcrumbs">Administration Panel
<div class="breadcrumb_divider"></div>
<a class="current">New Post</a></article>
</div>
</section>
<!-- end of secondary bar -->
<aside id="sidebar" class="column" style="height:160%;">
<hr/>
<h3>Pages</h3>
<ul class="toggle">
<li class="icn_new_article">Add a New Page</li>
<li class="icn_edit_article">Edit/Delete a Page</li>
</ul>
<hr/>
<h3>Users</h3>
<ul class="toggle">
<li class="icn_add_user">Add New User</li>
<li class="icn_view_users">View Users</li>
</ul>
<hr/>
<h3>Blog</h3>
<ul class="toggle">
<li class="icn_categories">Create a Category</li>
<li class="icn_new_article">Create/Edit a Post</li>
<li class="icn_settings">Home Blog Settings</li>
<li class="icn_settings">Blog Settings</li>
</ul>
<hr/>
<h3>Settings</h3>
<ul class="toggle">
<li class="icn_settings">Settings</li>
<li class="icn_settings">Site Logo</li>
<li class="icn_jump_back">Logout</li>
</ul>
<footer>
<hr />
<p><strong>Copyright © 2013 Sky Define</strong></p>
<p>Powered by Sky Define</p>
</br>
</br>
</footer>
</aside><!-- end of sidebar -->
<section id="main" class="column">
<?php
move_uploaded_file($_FILES['post_photo']['tmp_name'], $target);
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
<article class="module width_full">
<header><h3>New Post</h3></header>
<div class="module_content">
<h2>Adding New Post</h2>
<?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>
<div class="mws-panel grid_4">
<div class="mws-panel-header">
</div>
<div class="mws-panel-body">
<form class="mws-form" enctype="multipart/form-data" action="new_post.php?cat=<?php echo $sel_category['id']; ?>" method="post">
<div class="mws-form-inline">
<?php $new_post = true; ?>
<?php if (!isset($new_post)) {$new_post = false;} ?>
<div class="mws-form-row">
<label>Post Name:</label>
<div class="mws-form-item large">
<input type="text" name="post_title" id="post_title" class="mws-textinput" placeholder="Post Name Goes Here." />
</div>
</div>
<div class="mws-form-row">
<label>Post Description:</label>
<div class="mws-form-item large">
<input type="text" name="post_description" id="post_description" class="mws-textinput" placeholder="Post Description Goes Here." />
</div>
</div>
<div class="mws-form-row">
<label>Post Keywords:</label>
<div class="mws-form-item large">
<input type="text" name="post_keywords" id="post_keywords" class="mws-textinput" placeholder="Post Keywords Goes Here, Separated By Commas!" />
</div>
</div>
<div class="mws-form-row">
<label>Post Content:</label>
<div class="mws-form-item large">
<textarea name="post_content" id="post_content" class="ckeditor" > </textarea>
</div>
</div>
<div class="mws-form-row">
<label>Post Tags:</label>
<div class="mws-form-item large">
<input type="text" name="post_tags" id="post_tags" class="mws-textinput" placeholder="Post Tags Goes Here, Separated By Commas!" />
</div>
</div>
<div class="mws-form-row">
<label>Edit Post Photo:</label>
<div class="mws-form-item large">
<input type="file" name="post_photo" id="post_photo" />
</div>
</div>
<div class="mws-form-row">
<label>Position:</label>
<div class="mws-form-item large">
<select name="position">
<?php
if (!$new_post) {
$post_set = get_posts_for_category($sel_post['category_id']);
$post_count = mysql_num_rows($post_set);
} else {
$post_set = get_posts_for_category($sel_category['id']);
$post_count = mysql_num_rows($post_set) + 1;
}
for ($count=1; $count <= $post_count; $count++) {
echo "<option value=\"{$count}\"";
if ($sel_post['position'] == $count) { echo " selected"; }
echo ">{$count}</option>";
}
?>
</select>
</div>
</div>
<div class="mws-form-row">
<label>Visible:</label>
<div class="mws-form-item large">
<input type="radio" name="visible" value="0"<?php
if ($sel_post['visible'] == 0) { echo " checked"; }
?> /> No
<input type="radio" name="visible" value="1"<?php
if ($sel_post['visible'] == 1) { echo " checked"; }
?> /> Yes
</div>
</div>
</form>
<div class="mws-button-row">
<input type="submit" name="submit" value="Add Post" class="mws-button green" />
<a class="mws-button red" href="index.php">Cancel</a>
</div>
</div>
</div>
</div>
</article>
<div class="clear"></div>
</div>
</article><!-- end of stats article -->
<div class="spacer"></div>
</section>
</body>
</html>
The way I would try to find the error:
make your errors visible:
<?php error_reporting(E_ALL); ?>
$target should be a full path.
Check your HTML form. Did you add the enctype attribute?
<form enctype="multipart/form-data" method="POST" action="script.php">
Is your Input correct?
<input type="file" name="post_photo"/>
What does the $_FILES array contents?
<?php echo print_r($_FILES); ?>
Edit
Please let us know the data these lines return:
<?php
error_reporting(E_ALL);
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo "<br/>target: " . $target;
if (!move_uploaded_file($_FILES['post_photo']['tmp_name'], $target)) {
echo "<br/>Upload failed.";
} else {
echo "<br/>Upload done."
}
?>
Edit 2 (Solution):
Your submit-button is outside the form-Tag. That's why. Fix it like this:
<form>
<input type="submit" name="submit" value="Add Post" class="mws-button green" />
</form>
Your $target should contain the root path
$target = $_SERVER['DOCUMENT_ROOT']"/upload/";
$target = $target . basename( $_FILES['post_photo']['name']);

Undefined constant php error message in laravel

I am new in MVC framework. I created an application in Laravel Framework & it was working fine. Now after some modification when I want to view the index page the following error is shown to me-
Message:
Use of undefined constant php - assumed 'php'
Location:
C:\wamp\www\alpha.team.com\laravel\view.php(354) : eval()'d code on
line 32
Here is my view code of index.blade.php
#layout('/layouts/layout')
<link href='http://fonts.googleapis.com/css?family=Neucha' rel='stylesheet' type='text/css'>
<div id="top">
#section('navigation')
<!-- <li class="active"><i class="icon-user"></i> My Profile</li> -->
<li><i class="icon-book"></i> Dashboard</li>
#parent
#endsection
</div>
#section('content')
<!-- For showing error message if any error occours-->
<?php if(Session::get('error')): ?>
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Warning!</strong> <?php echo Session::get('error'); ?>
</div>
<?php endif; ?>
<!-- For showing success message.-->
<?php if(Session::get('success')): ?>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Well done!</strong> <?php echo Session::get('success'); ?>
</div>
<?php endif; ?>
<div class="field-section">
<div class="hero-unit">
<!-- <a id="logo" href="#"><img alt="TechIndyeah" src="/uploads/logo.png" style="vertical-align: top;"></a> -->
<h1 style="display:inline;">Team TechIndyeah</h1>
<ul class="teams" style="text-align:center;">
#foreach($departments as $dept)
<?php// print_r($dept); ?>
<li>
<?php echo $dept->name; ?>
</li>
#endforeach
</ul>
</div>
</div> <!-- field-section div ends here-->
<!-- <div class="container"> -->
<div class="wrapper">
<div class="hero-unit" id="bg-pattern">
<h1 class="home-tag"> Tech-ing India<span><p>The team of enthusiastic tech fanatics</p></span></h1>
<p class="home-ptag">We are a team of enthusiastic tech fanatics and yes we are Apple fanboys too. We have sailed out together on a small boat and we do live in what Seth Godin says, “Small is the next big”. We love technology and we love you. Our team is free, creative and always brimming with ideas.</p>
<div class="row" style="background:none;">
<div class="span8">
<h1 class="home-tag" >About Us</h1>
<p class="home-ptag">TechIndyeah has a team which is highly process oriented and has a sharp client-centric approach. Our mission is to help you to build your footprints in business. We are a team inspired by a vision and driven by technology. We are driven by an offbeat approach when it comes to client servicing and support. We have been serving our clients for a long time and have won accolades galore. We are a team and we believe in making our time resourceful so that our clients get the most out of us. We are a band of developers, designers and marketers who can take your business online and also combat the stiff competition from similar players in your domain. </p>
</div>
<div class="span3">
<object type="image/svg+xml" data="/img/logo.svg">
<img alt="TechIndyeah" src="/img/logo.png" style="vertical-align:top;">
</object>
</div>
</div>
<div class="row">
<div class="span4">
<!-- <a id="logo" href="#"><img alt="TechIndyeah" src="/uploads/logo.png"></a> -->
</div>
<!-- <div class="span6" id="caption">
<h3>Here We Are</h3>
</div> -->
</div>
<div class="row">
<?php $something = $errors->all();
if(!empty($something)): ?>
<div class = "alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
#foreach ($errors->all('<p>:message</p>') as $input_error)
{{ $input_error }}
#endforeach
</div>
<?php endif; ?>
</div>
<!-- For showing all employee name in the front page.. Showcasing them..-->
<div id="hero-unit">
<script type="text/javascript">
//The departments are randomly comming in the page when it is first loaded..
(function($) {
// Get the list items and hide them
var items = $(".teams > li").css({opacity:0});
// Shuffle them
shuffle(items);
// Start the fade-in queue
nextItemFade(items);
// Animation callback to start next fade-in
function nextItemFade(items) {
// Fade in the first element in the collection
items.eq(0).animate({opacity:1}, 400, function() {
// Recurse, but without the first element
nextItemFade(items.slice(1));
});
}
// Shuffles an array
// Based on http://jsfromhell.com/array/shuffle
function shuffle(a) {
var j, // Random position
x, // Last item
i = a.length; // Iterator
// Loop through the array
while(i) {
// Select a random position
j = (Math.random() * i) | 0;
// Get the last item in the array
x = a[--i];
// Swap the last item with the item at the selected position
a[i] = a[j];
a[j] = x;
}
return a;
}
/* Minified version
function shuffle(a) {
for(var j, x, i = a.length; i; j = (Math.random() * i) | 0, x = a[--i], a[i] = a[j], a[j] = x);
return a;
} */
})(jQuery);
$(".nav1 li").each(
function(intIndex) {
var l = Math.floor(Math.random() * $(".nav1").width());
var t = Math.floor(Math.random() * $(".nav1").height());
$(this).css("left", l);
$(this).css("top", t);
$(this).on(
"click",
function() {
alert("l=" + l + " t=" + t);
}
);
}
);
$(".nav1 li").each(
function(intIndex) {
var l = Math.floor(Math.random() * 940);
var t = Math.floor(Math.random() * 500);
$(this).css("left", l);
$(this).css("top", t);
$(this).on(
"click",
function() {
alert("l=" + l + " t=" + t);
}
);
}
);
</script>
<style type="text/css">
.nav1
{
position:relative;
}
.nav1 li
{
padding: 10px;
position:absolute;
}
</style>
</div> <!-- #hero-unit ends here-->
<!-- </div> mucarousel div ends here -->
<div class="member-list">
<!-- <object type="image/svg+xml" data="/img/vector-tree2.svg"> -->
<!-- <img alt="TechIndyeah" src="/img/vector-tree2.png" style="vertical-align:top;"> -->
<!-- </object> -->
#foreach($departments as $dept)
<div id="<?php echo implode('_',explode(' ',$dept->name));?>" class="demo">
<ul class="member">
<?php $users = User::where('department_id','=',$dept->id)->get();
// $users = User::where('department_code','=',$dept->code)->get();
?>
#foreach($users as $user)
<li class="new-element" style="display:inline-block;" rel="tooltip" data-placement="right" data-original-title="<?php echo $user->first_name." ".$user->last_name;?>">
<a href="/home/view/<?php echo $user->username;?>" rel="tooltip" data-placement="right" href="#" data-original-title="<?php echo $user->first_name." ".$user->last_name."</br> ".$user->designation;?>">
<img class="hover-img" src="http://graph.facebook.com/<?php echo $user->facebook_id;?>/picture?type=large">
</a>
</li>
#endforeach
</ul>
Back To Top
</div>
#endforeach
<script type="text/javascript">
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
</script>
<script type="text/javascript">
//all links which start with a # will have an animated scroll to the target.
$('a[href^="#"]').on('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
// console.log($target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 10
}, 900, 'swing', function () {
window.location.hash = target;
});
});
$('.new-element').children('a').tooltip();
</script>
</div>
<h1 style="text-align:center;font-family: 'Lato light', sans-serif;text-shadow: 2px 1px #848686;">TechIndyeah Software Pvt. Ltd.</h1>
</div>
</div>
#endsection
</div>
I cannot understand. Please help.
I'm not familiar with Laravel, but it seems that an eval() in a file named view.php is rendering a template. So my guess is that someplace in your template (whatever template is being rendered) you have php where you really mean 'php'.
For example:
echo $data[php]; //you have this
echo $data['php']; //but it should be this
//or
if(php == $var){} //you have this
if('php' == $var){} //but it should be this
Can you share some of the code that is in your view.php file?
You're doing something wrong on line 32 of that file, so it would be very helpful if we can see what the code actually is :)

Categories