Can't iterate through data with a foreach - javascript

I get this error when I refresh the page:
Uncaught TypeError: listaDeAutos.autos.foreach is not a function
I built the data here, which iterates and gets the data from the database and stores it in "salidaJson":
<?php
$salidaJson = '{"autos": [';
while ($row = $result->fetch_assoc()) {
$salidaJson = $salidaJson. '{';
$salidaJson = $salidaJson. '"idAuto":"' . $row['idAuto'] . '",';
$salidaJson = $salidaJson. '"Marca":"' . $row['Marca'] . '",';
$salidaJson = $salidaJson. '"Modelo":"' . $row['Modelo'] . '",';
$salidaJson = $salidaJson. '"idTipoDeVehiculo":"' . $row['idTipoDeVehiculo'] . '",';
$salidaJson = $salidaJson. '"FechaDeLanzamiento":"' . $row['FechaDeLanzamiento'] . '"';
$salidaJson = $salidaJson. '},';
}
$salidaJson = $salidaJson. '{"idAuto":"FIN", "Marca":"FIN","Modelo":"FIN","idTipoDeVehiculo":"FIN","FechaDeLanzamiento":"FIN"}';
$salidaJson = $salidaJson . ']}';
?>
Now this is the Javascript with the function that I'm trying to make, the objective is pretty simple, build a table with the data from the collection, I half wrote the table-building, but wanted to see if it was working at least the first part and I got the error:
<script>
var miTabla = $("#tableBody");
var listaDeAutos = <?php echo $salidaJson ?>;
console.log(listaDeAutos);
function cargaTabla() {
listaDeAutos.autos.foreach(function() {
var html = '<tr><td>'+ idAuto + '</td><td>' + Marca + '</td><td>'+ Modelo + '</td></tr>';
miTabla.append(html);
})
}
From what I understand forEach is used on Arrays but my data is an object because it contains "autos" that contains the arrays but I don't know how to make that function work with my object.
This is the data more clearly seen:
console.log output

Not sure where you got your foreach formatting there, but this should be the correct syntax
$.each(listaDeAutos.autos, function(i, item) {
var html = '<tr><td>'+ item.idAuto + '</td><td>' + item.Marca + '</td><td>'+ item.Modelo + '</td></tr>';
miTabla.append(html);
});
or using the forEach syntax if you prefer
(FWIW it's slightly slower)
listaDeAutos.autos.forEach(function(e, i) {
var html = '<tr><td>'+ e.idAuto + '</td><td>' + e.Marca + '</td><td>'+ e.Modelo + '</td></tr>';
miTabla.append(html);
});
This is based on this Plunker
While you're at it, you can use .= in PHP to clean up your code a bit.
$salidaJson .= '{';
...

First of all, the way you create the JSON is not elegant and kinda difficult to create with all these quotes and everything. You better create a PHP array and then json_encode that array.
$res = array("autos" => array());
while ($row = $result->fetch_assoc())
{
$res['autos'][] = array("idAuto" => $row['idAuto'],
"Marca" => $row['Marca'],
"Modelo" => $row['Modelo'],
"idTipoDeVehiculo" => $row['idTipoDeVehiculo'],
"FechaDeLanzamiento" => $row['FechaDeLanzamiento']);
}
$res['autos'][] = array("idAuto" => "FIN",
"Marca" => "FIN",
"Modelo" => "FIN",
"idTipoDeVehiculo" => "FIN",
"FechaDeLanzamiento" => "FIN");
$res = json_encode($res);
Secondly, in your JS script, you need to parse that variable listaDeAutos and then you can iterate through autos as mentioned by adriani6
var listaDeAutos = JSON.parse(<?php echo $res ?>);
Secondly, you don't need to parse it as you inject a JSON object already by <?php echo $res ?>. This was edited after nico-westerdale comment on this answer.
Thirdly, be careful with the camel case forEach as #JaromandaX pointed out. There is no foreach in JS.

Related

how to generate this code mysql_fetch_array in codeigniter

how do I write mysql_fetch_array code in codeigniter
<?php
$result = mysql_query("select * from tb_mhs");
$jsArray = "var dtMhs = new Array();\n";
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['nim'] . '">' . $row['nim'] . '</option>';
$jsArray .= "dtMhs['" . $row['nim'] . "'] = {nama:'" . addslashes($row['nama']) .
"',jrsn:'".addslashes($row['jurusan'])."'};\n";
}
?>
Form Input :
<td><input type="text" name="nm" id="nm"/></td>
<td><input type="text" name="jrsn" id="jrsn"/></td>
Javascript :
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(nim) {
document.getElementById('nm').value = dtMhs[nim].nama;
document.getElementById('jrsn').value = dtMhs[nim].jrsn;
};
</script>
If you want to return result as a array from the database, you can use something like this
// in application/config/autoload.php, make database available globally
$autoload['libraries'] = array('database');
// fetch the results from the database
$query = $this->db->get('tb_mhs'); // produces select * from tb_mhs
// get the result as a array
$result = $query->result_array();
// to do the other operations you were doing you can use a loop
foreach ($result as $key => $item) {
// do stuff
}

How to change js code to php

Currently I am learning Php. For an Ebay shop I try to get my page free of JS and to switch to pure CSS via PHP.
For this I have so far a backend, into which I enter my links and texts. These are stored in my menu.js.
$remote_directory = UPLOAD_PATH;
$renaming_file = $remote_directory . '/js/menu.js';
$renaming_file_to = $remote_directory . '/js/menu.old';
$_remc = new Admin_Remote_Copy(ADMIN_UPLOAD_SERVER_HOST, ADMIN_UPLOAD_USER_NAME, ADMIN_UPLOAD_PASSWORD, ADMIN_UPLOAD_SSH_PORT);
$_remc->remote_copy($renaming_file, $renaming_file_to);
if ($_remc->remote_is_writeable($renaming_file)) {
$menu_string = "document.getElementById('categories_menu').innerHTML='";
for ($z = 0; $z < count($_POST['menu_lvl1_text']); $z++) {
$menu_string .= '<li>' . htmlentities($_POST['menu_lvl1_text'][$z], ENT_QUOTES, "UTF-8") . '';
if (isset($_POST['menu' . $z . '_lvl2_text']) && !empty($_POST['menu' . $z . '_lvl2_text'])) {
$menu_string .= '<ul>';
for ($zs = 0; $zs < count($_POST['menu' . $z . '_lvl2_text']); $zs++) {
$menu_string .= '<li>' . htmlentities($_POST['menu' . $z . '_lvl2_text'][$zs], ENT_QUOTES, "UTF-8") . '';
}
$menu_string .= '</ul>';
}
$menu_string .= '</li>';
}
$menu_string .= "';";
$_remc->remote_content_copy($renaming_file, $menu_string);
$local_renaming_file = ADMIN_LOCAL_PATH . '/js/menu.js';
$_remc->local_content_copy($local_renaming_file, $menu_string);
} else {
$file_error = true;
}
Now I had thought to pass these values ​​into an array and save it via JSON PrittyPrint. However, I have no idea at all how to build this array.
My idea is to build a navigation with fixed IDs and fill it with the JSON file.
In the latter I see no problems, but the array is not clear to me.
Let's assume that array would look something like this:
$m =array(
"10100" => array('menu_lvl1_text' => 'menu_lvl1_link'),
"10101" => array('menu_lvl2_text' => 'menu_lvl2_link'),
"10102" => array('menu_lvl2_text' => 'menu_lvl2_link'),
"10103" => array('menu_lvl2_text' => 'menu_lvl2_link')
);
Am I on the wrong path?
And how does my array know that it is to assign value 1 to ID 10000?
Thanks,
Patrick
I think that you forgot to open a folder first! You can use some php functions like opendir at first then get or create a new file there.

How to use javascript and HTML to add a sql and button?

I have an application where I want to ADD an AND button that, than creates the option to add an AND statement to the query. This is the php and html code I have to do this at the moment. The problem is I don't know how to connect the php part to the javascript part to create a button that adds exacte the same code?
This the html code:
This is the php code:
<?php
include "connect.php";
$table = $_POST['tableSelected'];
$field = $_POST['fieldSelected'];
$attribute = $_POST['attributeSelected'];
$operator = $_POST['operatorSelected'];
$fieldList = $_POST['fieldList'];
if (!empty($table)){
if (!empty($fieldList)){
$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326),6)";
} else {
$fieldstr = "";
}
$pairs = [];
foreach ($_POST['fieldSelected'] as $key => $field) {
if (!empty($field) && !empty($_POST['operatorSelected'][$key]) && !empty($_POST['attributeSelected'][$key])) {
$pairs[] = $field . " " . $_POST['operatorSelected'][$key] . " '" . $_POST['attributeSelected'][$key] . "'";
}
}
if (count($pairs) > 0) {
$sql .= ' WHERE ' . implode(' AND ', $pairs);
}
//echo ($sql);
?>
And this my html at the moment:
<select name="field[]">...</select>
<select name="operator[]">...</select>
<select name="value[]">...</select>
This is what I want:
Button click should produce something like it Javascript (jQuery):
newElement = $("#someSelector").clone(false);
// Some modification of new element. Change id for example
$(newElement).attr("id",newIdValue);
newElement.appendTo("#parentElement");

how to check whether request is made or not

i am using contenteditable property in p tag .. the code is
<p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'A.'.' &nbsp'.$question1['Option1'];?></p>
<p contenteditable="true" id="Option2_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'B.'.' &nbsp'.$question1['Option2'];?></P>
and jquery to make a request to make request
document).ready(function(){
$("p[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("ajax.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
and then php to update my mysql database on receiving the request
<?php
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
session_start();
$mock_test_name=$_SESSION['mock_test_name'];
$num_of_sections = $_SESSION['num_of_sections'];
$school_name = $_SESSION['school_name'];
$class_name = $_SESSION['class_name'];
$section_name = $_SESSION['section_name'];
$con = mysqli_connect("localhost","root","","onlinetest");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$table_space = "$school_name $class_name $section_name $mock_test_name";
$table = str_replace(" ", "_", $table_space);
$table_space1 = "$school_name $class_name $section_name";
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = "$table1 $table";
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode("_",$key);
$user_id = $explode[1];
$field_name = $explode[0];
if(isset($user_id)){
$update = false;
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'"); //Selecting data from MySql
$result = mysqli_fetch_assoc($selectData); //Fetching Data
if($result[$field_name]!==$value){ //Checking if the Value is modified
$update = mysqli_query($con,"UPDATE" + $table2+ "SET" + $field_name+"="+$value+ "WHERE question_id='"+$user_id+"'"); //Updating MySQL if value is Modifie
}
//Update the users Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
But i think the request is not made properly as the database is not getting updated.. Please tell me how to check if a request has been made... or am i making error somewhere in writing code ??
Your mysqli_query function is formed incorrectly. You have to escape out of the parentheses in order to drop in variables.
You need to do something like
mysqli_connect($con, "SELECT " + var1 + " FROM " + var2);
or you'll end up making a query for
EDIT:
For a more apt example, the line
$selectData = mysqli_query($con,"SELECT $field_name FROM $table2 WHERE question_id='$user_id'");
should be
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'");
You'll notice the main difference, especially in coloring between the two, signifying that in the first one, the variables $field_name, $table2, and $user_id are all being interpreted as part of the query. You don't want the NAME of the variable, you want the VALUE of it instead, so you need to concatenate the strings together.
This is just one of the multiple similar fixes you'll need to do for your multiple queries. Every place the editor is marking the thing you're trying to use as a variable as part of the string, take the same steps to concat the strings.
You need to change your code like this,
ajax code
$.ajax({
type:"post",
url:"ajax.php",
data: "your data",
success:function(d){
console.log(d);
}
});
php code:
$table_space = $school_name." ".$class_name." ".$section_name." ".$mock_test_name;
$table = str_replace(" ", "_", $table_space);
$table_space1 = $school_name." ".$class_name." ".$section_name;
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = $table1." ".$table;
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);

Accessing JSON results from jQuery Ajax

I'm working on a web application to maintain the administration for a restaurant kind of type. The idea is to make new orders, put order items in that, check finance overviews etc...
I've also got a function to see all the orders in a list, when you select one of them, the order data (such as the name, emailadress, location of the customer) shows up in a another element inside the document.
I'm doing that with this function, every tr inside the has been given a custom attribute; the order_id. When selecting that, a class is given, called selectedRow.
function select_order(order) {
var item = $(order);
if (!item.hasClass("selectedRow")) {
if (!selectedOrderInformation.is(":visible")) {
switchScreen(selectedOrderInformation, financeOverview);
}
item.parent().find(".selectedRow").removeClass("selectedRow");
item.addClass("selectedRow");
selectedOrderInformation.html("loading......");
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data);
$("#delete-order-btn").prop("disabled", false);
}
});
} else {
console.log("DEBUG: Row is already selected");
}
}
The usage of that function is by doing this:
$("#list tbody tr").click(function () {
select_order(this);
});
At the first place, i was deploying all the HTML data via PHP. This took a pretty long time, it could take from 500ms to about 1 second. In my opinion thats pretty long.
I was doing that like this (select-order.php):
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
while ($row = mysqli_fetch_array($order_data)) {
echo "<h1>Klant informatie</h1>";
echo "<p>Voornaam: " . $row['first_name'] . "</p>";
echo "<p>Achternaam: " . $row['last_name'] . "</p>";
echo "<p>Emailadres: " . $row['email_adress'] . "</p>";
echo "<p>Klant informatie: " . $row['customer_info'] . "</p>";
echo "<br>";
echo "<h1>Bestellingsinformatie</h1>";
echo "<p>Order informatie: " . $row['order_info'] . "</p>";
echo "<p>Locatie: " . $row['location'] . "</p>";
echo "<p>Gemaakt op: " . $row['created'] . "</p>";
}
echo "<br>";
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Product naam</th>";
echo "<th>Hoeveelheid</th>";
echo "</tr>";
echo "</thead>";
while ($row = mysqli_fetch_array($order_items)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
exit;
}
This goes together with the Database class with all the functions:
class Database extends mysqli
{
// single instance of self shared among all instances
private static $instance = null;
private $databaseHost = "";
private $databaseUser = "";
private $databasePassword = "";
private $databaseName = "";
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
function __construct() {
parent::__construct($this->databaseHost, $this->databaseUser, $this->databasePassword, $this->databaseName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
parent::set_charset('utf-8');
}
function get_all_data_by_order_id($order_id) {
$query = "SELECT customers.first_name,
customers.last_name,
customers.email_adress,
customers.customer_info,
orders.order_info,
orders.total_price,
orders.location,
orders.created
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
WHERE orders.id = {$order_id}";
return $this->query($query);
}
function get_order_items_by_order_id($order_id) {
$query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`\n" . "INNER JOIN `products`ON `orders-items`.`products_id` = `products`.`id`\n" . "WHERE order_id=" . $order_id;
return $this->query($query);
}
}
Now someone told me i could better translate the data into json and return that, so i did this:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$rows = array();
while ($row = mysqli_fetch_array($order_data)) {
$rows[] = $row;
}
return json_encode($rows);
exit;
}
But as expected, nothing really happened. So i tried changing the javascript to this (trying it as a array because i'm returning it that way?), to deploy one piece of data:
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html(data['first_name']);
}
});
But that didn't work aswell.
Problems
The previous PHP code was to slow, so i had to find another way.
When trying to deploy HTML into the other screen, it doesnt do anything. It stays on the 'loading...' screen, so the success function was'nt reached.
Question
How can my piece of code be changed so it will actually deploy parts of the data from the mysql database?
In your $.ajax() call you should define what type your response data is expected to be, by adding the following parameter to the call:
dataType: 'json'
Also, you should try echo json_encode($rows); your data instead of returning it.
**Edit: you are receiving an array of arrays, so your original referencing in the success callback won't suffice. Having another look at your MySQL part, If you are only expecting one row to be returned by your query, then you can change your PHP to:
$row = mysqli_fetch_array($order_data);
echo json_encode($row); // instead of $rows
instead of the while loop. That way your selectedOrderInformation.html(data['first_name']); will most likely work.
To clean your query up a bit:
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = " . $order_id;
You could also switch your INNER JOIN to a LEFT JOIN in your "get order data" function. An inner join is absolutely useless here, as you'll have all your data paired based on the foreign keys anyways.
I would try secluding some of the codebase: try commenting out the Database::getInstance() calls, and supplementing some testdata into the processes. To put it short, fake a returned response, by declaring a $row = array('first_name' => 'Joe', 'order_date' => '2014-08-29 11:11:52', ...); and returning that. If its way faster, then your database server might be the bottleneck. If its still slow, then 500ms - 1000ms is actually argueably code related, it might be other hardware aspects that cause the problem. Or for example, do you have your jQuery library loaded from a CDN, or locally?
**Edit: As #Debflav pointed out (and I've also touched upon the matter), that your queries could benefit from not being executed as simple queries, but transforming them into prepared statements. For the full story you could start checking out PHP.net : Prepared Statements, or to keep it short:
Prepared statements look almost just like your everyday query, however variables are not just concatenated into the query string, rather bindings are used.
You use the database handler's prepare function instead of query - with this method, you are requesting the MySQL server to inspect your query and optimize it for later use (which will come handy if you're doing the same query over and over again, just with a few varying values).
For more detailed insights on the mechanics of prepared statements and how to get the hang of it for efficiently utilizing it in your projects I recommend you research the topic a bit, but as a quick conversion for your example at hand, it would look like this:
function get_all_data_by_order_id($order_id) {
$query = "SELECT c.first_name, c.last_name, c.email_adress, c.customer_info,
o.order_info, o.total_price, o.location, o.created
FROM customers AS c
LEFT JOIN orders AS o ON c.id = o.customer_id
WHERE o.id = :order_id";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
and
function get_order_items_by_order_id($order_id) {
$query = "SELECT p.name, ot.quantity FROM orders-items AS ot
LEFT JOIN products AS p ON ot.products_id = p.id
WHERE ot.order_id = :order_id;";
$query_params = array(
':order_id' => $order_id
);
$preparedStatement = $this->prepare($query);
return $preparedStatement->execute($query_params);
}
And to reflect on how you would build up your JSON response with data including the order headers and the connected order-items would be:
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$order_data = Database::getInstance()->get_all_data_by_order_id($order_id);
$order_items = Database::getInstance()->get_order_items_by_order_id($order_id);
$orderObject = array();
$orderObject['header'] = mysqli_fetch_array($order_data);
$orderObject['items'] = array();
while ($orderedItem = mysqli_fetch_array($order_items)){
$orderObject['items'][] = $orderedItem;
}
echo json_encode($orderObject);
}
This way your jQuery could look something as follows:
....
success: function (data) {
selectedOrderInformation.html('<h3>' + data['header']['first_name'] + '</h3><ul>');
$.each(data['items'], function(i, item) {
selectedOrderInformation.append('<li>' + item['name'] + ' x ' + item['quantity'] + '</li>');
});
selectedOrderInformation.append('</ul>');
}
....

Categories