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.
Related
How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.
<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
Hi I tried Looping my json_encode() to get all data that are related based on my query
the script is working fine but not the looping part
here's what I have so far:
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_GET['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_GET['name'];
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
echo json_encode($message_array);
}
}
It only returns one data from my database..
this is my javascript for retrieving from my php side:
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
You just keep overwriting $json_string with each loop iteration.
What you want to do is save your DB data to array then encode.
$array = array();
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$array[] = $message_array;
}
}
$json_string = json_encode($array);
echo $json_string;
It also appears that in your AJAX success handler function, you are not properly iterating the array.
Notice here that you only call $.each() on the first array element of the returned result set:
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
I would think you would want to iterate the entire result set like this:
$.each(result, function(rowKey, row) {
// row is single row of result set from database
// rowKey is numerical index of the row in the result set
// rowKey is probably not useful here
// You can just append new div to #clog with
// whatever content from row which you desire
// for example, this would insert message_content value
// in child div to #clog
$("#clog").append('<div>' + row.message_content + '</div>');
});
Try This.....
$i=0;
$fet=mysql_query('select * from tbl1 WHERE tbl1.id='20');
while($row=mysql_fetch_assoc($fet,MYSQL_ASSOC)){
$json[$i]['date']=$row['time'];
$i++;
}
echo json_encode($json);
Please use ->rowCount() to count rows:
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
}
echo json_encode($json);
You should use an array to store your message_arrays, so that you're not just replacing the same variable over and over.
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");
}
})
PHP PAGE:
<?php
include "linkpassword.inc";
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($showresult);
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
addVote();
showVotes();
?>
I am trying to get the output of the array to load into a JavaScript page where I can break up the array into seperate divs that have IDs assigned to them. Here is what I tried
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
Where am I going wrong??
From what you've posted in comments, what you have is an array of objects.. not html, as your function seems to indicate. Depending on what you want done, the answer would be either of the following, to access that object's properties:
showVotes[0].votes
Or
showVotes[0]['votes']
Eg:
$('#rvotes').html(showVotes[0].votes);
Or etc.
Second attempt:
Firstly, change your current 'showVotes' function to this:
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_assoc($showresult)) {
$response[] = $row;
}
return json_encode($response);
}
Secondly, remove your 'connected successfully' text from the page, as well as any other text generated by anything else(aka, the other function which returns a result pointer). I may be wrong, but it would seem to me that the generation of this other text is causing the returned json to be interpreted as malformed.
Quick explanation on PDO:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>";
die();
}
Connecting to the database.. This is how I've learned to do it, though I've been warned(and downvoted) to not check for errors this way, though it was never explained why.
Database interaction:
$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color");
$stmt->bindParam(":color",$_POST['color']);
$stmt->execute();
Result use:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row;
}
And so on and so forth. PDO escapes the values for you, so you don't have to worry about injection attacks.