User limit for organizations - javascript

I am making a website with organizations. You can request to become part of an organizations. But the organizationshas to get a user limit of 500 people. it doesn't give an error and it won't go to my function either. Normally it just has to check if current_users is less then 500. And then the function has to update the user table and the organization.
this is what I tried so far:
<?php
require '../conn.php';
include '../session.php';
$count = "SELECT `current_users` FROM `organisations` WHERE `org_id` =
'".$_POST['org']."'";
$result = mysqli_query($conn, $count); // your query execution
$row = mysqli_fetch_array($result);
if($row['current_users'] < 500){
$this->requestUserCreate()
} else {
throw new Exception('Limit reached')
}
function requestUserCreate() {
$q = "UPDATE `organisations` SET `current_users` = `current_users` + 1 WHERE
`org_id`='".$_POST['org']."'";
$sql = "UPDATE `users` SET `active`= 1, `type` = 0 WHERE `user_id` = '" .
$_POST['user'] . "'";
if ($conn->query($sql) && $conn->query($q) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
this is my table for the organizations
CREATE TABLE `organisations` (
`org_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`path` varchar(100) NOT NULL,
`type` int(1) NOT NULL,
`branche` varchar(50) NOT NULL,
`niveau` int(11) DEFAULT NULL,
`current_users` int(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
and this is for the users:
CREATE TABLE `users` (
`user_id` int(5) NOT NULL,
`fnln` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`org_id` int(5) DEFAULT NULL,
`part_id` int(11) NOT NULL DEFAULT '0',
`type` int(1) NOT NULL,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
my javascript
function approveOne(user, org) {
swal({
title: 'Are you sure to approve this users?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Approve user'
}).then(function () {
$.ajax({
url: "functions/save/approveUser.php",
type: "POST",
data: {user, org},
success: function (data) {
swal(
'Approved!',
'You have approved the selected user.',
'Success'
);
$("#newUsers").hide(250);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
}
and here is my html
<!doctype html>
<html lang="en">
<head>
<?php include 'include/header.php'; ?>
<title>Student Concepts | Users</title>
</head>
<?php
if (isset($_SESSION['type'])) {
if ($_SESSION['type'] != '1') {
header('Location: index');
die();
}
}
function getUsers($orgID, $type)
{
require 'functions/conn.php';
$sql = "SELECT users.*, parts.* FROM users INNER JOIN parts ON users.part_id
= parts.part_id WHERE users.org_id = '" . $orgID . "' AND users.active = '"
. $type . "';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<tr id="' . $row['user_id'] . '">';
echo ' <td>' . $row['fnln'] . '</td>';
echo ' <td>' . $row['username'] . '</td>';
echo ' <td>' . $row['name'] . '</td>';
echo ' <td>';
if ($row['active'] == 0 || $row['active'] == 2) {
echo ' <button class="button button-green"
onclick="approveOne('.$row['user_id'].',
'.$_SESSION['org_id'].')">Approve</button>';
}
echo ' <button class="button button-red"
onclick="deleteFromRelation(' . $row['user_id'] .
');">Delete</button><br/>';
echo ' </td>';
echo '</tr>';
}
}
}
?>

You need to parse the result of the query. Also, you have a logic error in the if if ($count > 500) should be if ($count < 500) because you want to add when you have less then 500
$result = mysqli_query($conn, $count);
if ($result !== false) {
$totalRows = mysqli_num_rows($result);
if ($totalRows < 500) {
$this->requestUserCreate();
} else {
throw new Exception('Limit reached');
}
} else {
echo "Error: " . $count . "<br>" . mysqli_error($conn);
}
Now, an optimisation will be to remake the query, to use a count() function instead of select

Related

Adding DropDown list in jQuery DataTable

I want to display table's data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.
The main code for fetching data (fetch.php) is:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["part_manufacturer"];
$sub_array[] = $row["part_id"];
$sub_array[] = $row["part_category"];
$sub_array[] = $row["part_stock"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
while the DataTable is defined in index.php as follows:
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"actions/fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 1],
"orderable":false,
},
],
});
In index.php, i've created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():
$(document).on('change', '#sub3_category_item', function(){
load_parts();
});
function load_parts()
{
var action = 'fetch_data';
var filter_part_id = $('#sub2_category_item').val();
$.ajax({
url:"actions/fetch.php",
method:"post",
data:{action:action, filter_part_id:filter_part_id},
success:function(data)
{
$('#user_data').DataTable().ajax.reload();
}
});
}
The problem is that i can't filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?
I've modified the index.php as follows:
$(document).on('change', '#sub3_category_item', function(){
var filter_part_id = $('#sub3_category_item').val();
$('#user_data').DataTable().destroy();
fill_datatable(filter_part_id);
});
fill_datatable();
function fill_datatable(filter_part_id = '')
{
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"searching" : false,
"ajax":{
url:"actions/fetch.php",
type:"POST",
data:{filter_part_id:filter_part_id}
}
});
and fetch.php:
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST['filter_part_id']) && $_POST['filter_part_id'] != '')
{
$query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["filter_part_id"]."') ";
}
but dataTable crashes, when #sub3_category_item is selected. Any idea, how to filter datatable with the value $_POST["filter_part_id"]?

Having trouble with datatable invalid JSON response

I keep having this error. I manage to track down the response by inspecting the dataTable which lead me to believe that this is the source of the problem. Please bear with me for I'm still a beginner in javascript and PHP.
image link to error:
source of error
here are my codes:
config.php
<?php
class dbConfig {
protected $serverName;
protected $userName;
protected $password;
protected $dbName;
function dbConfig() {
$this -> serverName = 'localhost';
$this -> userName = 'root';
$this -> password = '';
$this -> dbName = 'database';
}
}
?>
user.php
<?php
require('config.php');
class User extends dbconfig {
protected $hostName;
protected $userName;
protected $password;
protected $dbName;
private $userTable = 'user';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$database = new dbConfig();
$this -> hostName = $database -> serverName;
$this -> userName = $database -> userName;
$this -> password = $database -> password;
$this -> dbName = $database -> dbName;
$conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
} else{
$this->dbConnect = $conn;
}
}
}
private function getData($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
private function getNumRows($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$numRows = mysqli_num_rows($result);
return $numRows;
}
public function userList(){
$query = "SELECT * FROM ".$this->userTable." ";
if(!empty($_POST["search"]["value"])){
$query .= 'where(user_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_fname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_mname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_lname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_address LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_contactnumber LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_birthdate LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(!empty($_POST["order"])){
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$result = mysqli_query($this->dbConnect, $query);
$numRows = mysqli_num_rows($result);
$userData = array();
while ($user = mysqli_fetch_assoc($result)) {
$userRows = array();
$userRows[] = $user['user_id'];
$userRows[] = ucfirst($user['user_fname']);
$userRows[] = $user['user_mname'];
$userRows[] = $user['user_lname'];
$userRows[] = $user['user_address'];
$userRows[] = $user['user_contactnumber'];
$userRows[] = $user['user_birthdate'];
$userRows[] = '>button type="button" name="update" id="'.$user['user_id'].'"class="btn btn-warning btn-xs update"<Update>/button<';
$userRows[] = '>button type="button" name="delete" id="'.$user['user_id'].'"class="btn btn-danger btn-xs update"<Delete>/button<';
$userData[] = $userRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $userData
);
echo json_encode($output);
}
}
?>
ajax.js
$(document).ready(function(){
var userRecords = $('#userList').DataTable({
"lengthChange": false,
"processing": true,
"serverSide": true,
"order":[],
"ajax":{
url:"process.php",
type: "POST",
data: {action: 'listUser'},
dataType: "json"
},
"columnDefs":[
{
"targets": [0, 6, 7],
"orderable": false,
},
],
"pageLength": 10
});
});
process.php
<?php
include('user.php');
$user = new User();
if (!empty($_POST['action']) && $_POST['action'] == 'listUser') {
$user -> userList();
}
?>

how can i get form data validate it with javascript and send it to database using php

I have tried to pass my data from ajax to php then to database but I find errors saying uncaught error - "undefined function is_ajax"
..............my js code................
var form = document.getElementById('form');
form.addEventListener("submit",validateForm)
function validateForm(e) {
e.preventDefault();
var name = document.forms["form"]["name"] .value;
var ml = document.forms["form"]["mail"] .value;
var num = document.forms["form"]["number"] .value;
var ctry = document.forms["form"]["country"] .value;
var date_in = document.forms["form"]["date_in"] .value;
var time_in = document.forms["form"]["time_in"] .value;
var time_out = document.forms["form"]["time_out"] .value;
$.ajax({
type: "POST",
url: "data.php",
data:{myname:name,myemail:ml,c_num:num,c_ctry:ctry,in_date:date_in,in_time:time_in,out_time:time_out},
success:function(reply){
var respOutPut = String(reply);
console.log("OutPut:" + respOutPut);
if (respOutPut.trim() == "not Ajax Request"){
}
},
error: function () {
console.log("Error:");
}
});
}
.......php..........
<?php
if (is_ajax()) {
if( $_POST["myname"] && isset($_POST["myemail"]) &&
isset($_POST["c_num"]) && isset($_POST["c_ctry"]) &&
isset($_POST["in_date"]) && isset($_POST["in_time"]) &&
isset($_POST["out_time"])){
$name = $_POST["myname"];
$email = $_POST["myemail"];
$number = $_POST["c_num"];
$country = $_POST["c_ctry"];
$arrival_d = $_POST["in_date"];
$arrival_t = $_POST["in_time"];
$dep_t = $_POST["out_time"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "triangle";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error . "<br>");
}
echo "Connected successfully<br>";
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS triangle";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . $conn->error."<br>";
}
$conn->close();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error."<br>");
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS Customer (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
number VARCHAR(50),
country VARCHAR(50),
date_in VARCHAR(50),
time_in VARCHAR(50),
dep_time VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table customer created successfully<br>";
} else {
echo "Error creating customer table: " . $conn->error."<br>";
}
$conn->close();
$sql = "INSERT INTO customer (name, email, number,country,date_in,time_in,dep_time)
VALUES ('$_POST[myname]','$_POST[myemail]','$_POST[c_num]','$_POST[c_ctry]','$_POST[in_date]','$_POST[in_time]','$_POST[out_time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
$conn->close();
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
}
?><?php
if (is_ajax()) {
if( $_POST["myname"] && isset($_POST["myemail"]) &&
isset($_POST["c_num"]) && isset($_POST["c_ctry"]) &&
isset($_POST["in_date"]) && isset($_POST["in_time"]) &&
isset($_POST["out_time"])){
$name = $_POST["myname"];
$email = $_POST["myemail"];
$number = $_POST["c_num"];
$country = $_POST["c_ctry"];
$arrival_d = $_POST["in_date"];
$arrival_t = $_POST["in_time"];
$dep_t = $_POST["out_time"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "triangle";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error . "<br>");
}
echo "Connected successfully<br>";
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS triangle";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . $conn->error."<br>";
}
$conn->close();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error."<br>");
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS Customer (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
number VARCHAR(50),
country VARCHAR(50),
date_in VARCHAR(50),
time_in VARCHAR(50),
dep_time VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table customer created successfully<br>";
} else {
echo "Error creating customer table: " . $conn->error."<br>";
}
$conn->close();
$sql = "INSERT INTO customer (name, email, number,country,date_in,time_in,dep_time)
VALUES ('$_POST[myname]','$_POST[myemail]','$_POST[c_num]','$_POST[c_ctry]','$_POST[in_date]','$_POST[in_time]','$_POST[out_time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
$conn->close();
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
}
?>
You can send your form data like this
var formData = $(form).serializeArray();
$.ajax({
type: "POST",
url: "data.php",
data:{formData},
success:function(reply){
var respOutPut = String(reply);
console.log("OutPut:" + respOutPut);
if (respOutPut.trim() == "not Ajax Request"){
}
},
error: function () {
console.log("Error:");
}
});
And in your php you can get them by $_POST.

jQuery DataTables column sorting on other column

My jQuery Datatable is not sorting properly in some columns. When I sort the GGC_ID column, it's sorting properly, but when I sort the CustomerID column, its not sorting. And when I sort the Customer Name column, the CustomerID column is the one that is sorting.
Here's my code:
record.js:
var tbl = $('#tbl').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"searchable": true,
"columnDefs": [
{
"orderable": false,
"targets": [0,4]
}
],
"ajax": {
url: "fetch.php",
method: "POST"
}
});
fetch.php
$query = '';
$query .= "SELECT records.GGC_ID, company.Comp_Name, customer.CUST_ID, customer.CUST_NAME FROM records INNER JOIN company on company.Comp_ID = records.COMP_ID INNER JOIN customer ON customer.CUST_ID = records.CUST_ID ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE Comp_Name LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR CUST_NAME LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR GGC_ID LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"])) {
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].
' ';
} else {
$query .= "ORDER BY GGC_ID DESC ";
}
if($_POST["length"] != -1) {
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$data = array();
$filtered_rows = $stmt->rowCount();
foreach ($result as $row) {
$sub_array = array();
$sub_array[] = $row["Comp_Name"];
$sub_array[] = $row["GGC_ID"];
$sub_array[] = $row["CUST_ID"];
$sub_array[] = $row["CUST_NAME"];
$sub_array[] = '<button type="button" name="update" id="'.$row["CUST_ID"].'"
class = "btn btn-default details" data-toggle="modal" data-target="#customer_modal">Details</button> ';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
$_REQUEST["order"][0][column] - does not have field name, it has index of field in columns
$index = $_REQUEST["order"][0][column];
ORDER BY $_REQUEST["columns"][ $index ]["name"]
You can open google console, network tab, find server request - header tab to see variables it sends.
Also
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
exit();
Your fixed code:
$index = $_POST['order']['0']['column'];
$field = $_POST["columns"][ $index ]["name"];
$query .= 'ORDER BY '.$field.' '.$_POST['order']['0']['dir'].
' ';
When you sort the Customer Name column, echo $query, check sql is right.

Upload image with PHP and AngularJS

I am working on a admin panel which is going to add data on a SQLite DB using AngularJS and PHP and then show it in HTML. All good with data as arrays text date etc. The problem that I have is to upload an Image in a specified folder and store the path in my DB.
This is my PHP which store data in DB
<?php
try {
if (
empty($_POST['item']) ||
empty($_POST['description']) ||
empty($_POST['release']) ||
empty($_POST['demo']) ||
empty($_POST['type']) ||
empty($_POST['live']) ||
empty($_POST['client'])
) {
throw new PDOException("Invalid Request");
}
$item = $_POST['item'];
$description = $_POST['description'];
$release = $_POST['release'];
$demo = $_POST['demo'];
$type = $_POST['type'];
$live = $_POST['live'];
$client = $_POST['client'];
$objDb = new PDO('sqlite:../database/database');
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO 'items'
('id', 'item', 'description', 'release', 'demo', 'type', 'live', 'client')
VALUES (null, ?, ?, ?, ?, ?, ?, ?)";
$statement = $objDb->prepare($sql);
if (!$statement->execute(array($item, $description, $release, $demo, $type, $live, $client))) {
throw new PDOException("The execute method failed");
}
And this is my PHP which upload Images in a specified folder
<?php
if (isset($_POST['submit'])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<b>Stored in:</b> " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "<span>***Invalid file Size or Type***<span>";
}
}
?>
And this is my insert function from angular
$scope.insert = function() {
if ($scope.goodToGo()) {
var thisData = "item=" + $scope.item;
thisData += "&description=" + $scope.description;
thisData += "&release=" + $scope.release;
thisData += "&demo=" + $scope.demo;
thisData += "&client=" + $scope.client;
thisData += "&type=" + $scope.type;
thisData += "&live=" + $scope.live;
thisData += "&image=" + $scope.image;
$http({
method : 'POST',
url : urlInsert,
data : thisData,
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(_recordAddedSuccessfully(data)){
$scope.items.push({
id : data.item.id,
item : data.item.item,
description : data.item.description,
release : data.item.release,
demo : data.item.demo,
client : data.item.client,
client_name : data.item.client_name,
type : data.item.type,
type_name : data.item.type_name,
live : data.item.live,
live_name : data.item.live_name,
image : data.item.image,
done : data.item.done
});
$scope.clear();
}
})
.error(function(data, status, headers, config){
throw new Error('Something went wrong with inserting');
});
}
};
Have anyone any idea how to do this?
If you are uploading image then content type should be set to multipart/form-data i.e
headers : {'Content-Type' : 'multipart/form-data'}
rest looks fine.

Categories