How to insert jstree checkbox value into database - javascript

<script type="text/javascript">
$(document).ready(function(){
//fill data to tree with AJAX call
$('#tree-container').jstree({
'plugins': ["wholerow", "checkbox"],
'core' : {
'data' : {
"url" : "response.php",
"dataType" : "json" // needed only if you do not supply JSON headers
}
}
})
});
</script>
<div id="tree-container"></div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "defectsystem";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM `treeview_items` ";
$res = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_assoc($res) ) {
$data[] = $row;
}
$itemsByReference = array();
// Build array of item references:
foreach($data as $key => &$item) {
$itemsByReference[$item['id']] = &$item;
// Children array:
$itemsByReference[$item['id']]['children'] = array();
// Empty data class (so that json_encode adds "data: {}" )
$itemsByReference[$item['id']]['data'] = new StdClass();
}
// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
$itemsByReference [$item['parent_id']]['children'][] = &$item;
// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item) {
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
unset($data[$key]);
}
// Encode:
echo json_encode($data);
?>
I had successfully create a jstree with checkbox. However, how I can insert the checkbox value into the database when I click it and submit.
Thankss if anyone could help me!! If any question can ask me below comment.

Try some thing like this:
var array = [];
// create an array
$.each($("input[name='user_permission']:checked"), function(){
permissions.push($(this).val());
});
// Iterate over each checkbox which is checked and push its value in the array variable.
Ex:
......
var permissions = [];
$.each($("input[name='user_permission']:checked"), function(){
permissions.push($(this).val());
});
$.ajax({
url : 'add_permission.php',
method : 'post',
data :
{
permissions : JSON.stringify(permissions)
}
....
});
// After complete iteration you will get the value of each checked checkbox.
Now insert it in database using ajax call

Related

How to pass variable from controller to ajax request in view and then retrieve it in php script (codeigniter)

Hello I want to pass this variable: ID_person to view and then send it to php script to get requested data from database.
Controller:
public function view($id){
$data = array();
if(!empty($id)){
$data['zakaznici'] = $this->Zakaznici_model->getRows($id); //$data['temperatures'] = $this->Temperatures_model->getRows($id);
$data['title'] = 'Údaje o zákazníkovi';
$data['ID_person'] = $id;
$this->load->view('zakazniciview', $data);
}else{
redirect('/zakaznici');
}
}
So far I'm using this request in my view:
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
It is working but I need to get somehow that ID_person variable from controller and sent it to chart_vypozicky.php script and then retrieve it in query in this script.
Php script:
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID= "; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Is it somehow possible to get this done? I will be really thankful for all suggestions.
In your view pass ID_person and then Use $_GET['ID_person'] in chart_vypozicky.php page
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
data:{ID_person:'<?php echo $ID_person; ?>'},
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$person_ID=$_GET['ID_person']
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID='".$person_ID."'"; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Use this updated code

Json dynamic display vs server ressources

I'm aiming to display dots with javascript by their coordinates. Each person click on an image, (X,Y) will be stored in the database. On the same image will be displayed all dots, when a person is visualing the image with dots and another person will submit new dot, this last will appears because array_x and array_y tabs will be refreshed every 1s.
The question is : is it the best way in terms of using server ressources of doing that ? suppose i've 1000 persons that will participate to this study, that signify that for one person there is at least one request every 1s. Suppose that one person will spend 30s, that will be a huge amount of requests.
I am afraid to have a server breakdown due to multiple requests. Is it a way more guaranteed than this one ?
My js :
window.setInterval(loadNewPosts, 1000); //load simultaneous choice in 1 second
function loadNewPosts(){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "latest.php",
data: "current_id=" + current_id +"&nextType=" + nextType,
success: function(data) {
for (var i = 0; i < data['array_x'].length; i++) {
array_x.push(data['array_x'][i]);
array_y.push(data['array_y'][i]);
}
}
});
}
my php latest.php :
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$current_id = intval($_GET['current_id']);
$Type = (string)$_GET['nextType'];
$sql = "SELECT * FROM `table` WHERE id > $current_id and Type='".$Type."'";
$result = mysqli_query($conn, $sql);
$array_x= [];
$array_y= [];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($array_x,$row["X"]);
array_push($array_y,$row["Y"]);
}
} else {
echo "";
}
mysqli_close($conn);
// return the posts as a JSON object
header('Content-Type: application/json');
$data=array(
'array_x' => $array_x,
'array_y' => $array_y
);
echo json_encode($data);

How to save my jquery array to php using ajax

I have a script that gets the contents of a table that i added.
And i want to do is save the content into a database.
In the picture the table and the content of my dataSet variable that i get from the table.
i check the dataSet and alert it to check if it has value.
My problem is im having trouble saving the array that i passed to php cause its not working its not saving. I got an error in my saveTable.php invalid argument foreach.
script:
var names = [].map.call($("#myTable2 thead th"), function (th) {
return $(th).text();
});
var x = [].map.call($("#myTable2 tbody tr"), function (tr) {
return [].reduce.call(tr.cells, function (p, td, i) {
p[names[i]] = $(td).text();
return p;
}, {});
});
var dataSet = JSON.stringify(x);
alert(dataSet);
$.ajax(
{
url: "saveTable.php",
type: "POST",
data: { tableArray: dataSet},
success: function (result) {
}
});
saveTable.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tableArray = isset($_REQUEST['tableArray']) ? $_REQUEST['tableArray'] : "";
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
$sth = $dbc->prepare($sql);
foreach( $tableArray As $v){
$sth->bindValue(':name', $v[0], PDO::PARAM_STR);
$sth->bindValue(':age', $v[1], PDO::PARAM_STR);
$sth->bindValue(':gender', $v[2], PDO::PARAM_STR);
$sth->bindValue(':action', $v[3], PDO::PARAM_STR);
$sth->execute();
}
?>
new error:
It looks that you are trying to use a String type in the foreach loop. Try:
$tableArray = isset($_REQUEST['tableArray']) ? json_decode($_REQUEST['tableArray']) : array();
This should make it work. Good luck, hope this helps!
You have to convert the string to an array using json_decode to be able to use it as an array.

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

cant fillter characters in jcombo

Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.

Categories