Loadmore plugin does not display proper the items - javascript

I have these 3 files that I found, its a plugin that loads more data when a user click a button and uses ajax and json to do that. It works very well and has only one problem. It is not displaying the data in screen but only the parenthesis (). The thing is that I don't know so good javascript to solve the problem if it is in js for that I asking your help. If anyone can solve it I would appreciated this.
The source for the plugin is this
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Load more</title>
</head>
<body>
<div class="articles">
<div class="items">
<div class="item">
<h3><span data-field="title"></span> (<span data-field="id"></span>)</h3>
<p data-field="description"></p>
</div>
</div>
Load more
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="loadmore.js"></script>
<script>
$('.articles').loadmore({
source: 'articles.php',
step: 2
});
</script>
</body>
</html>
articles.php
<?php
header('Content-Type: application/json');
include('db_conx.php');
?>
<?php
$articles = array();
$start = isset($_GET['start']) ? (int)$_GET['start'] - 1 : 0;
$count = isset($_GET['count']) ? (int)$_GET['count'] : 1;
$article = mysqli_query($db_conx, "SELECT * FROM articles LIMIT {$start}, {$count}");
$articlesTotal = mysqli_query($db_conx, "SELECT COUNT(*) as count FROM articles");
$articlesTotal = mysqli_fetch_assoc($articlesTotal);
$articlesTotal = $articlesTotal['count'];
if ($articlesCount = $article->num_rows) {
$articles = $article->fetch_all();
}
echo json_encode(array(
'items' => $articles,
'last' => ($start + $count) >= $articlesTotal ? true : false,
'start' => $start,
'count' => $count
));
?>
loadmore.js
(function($) {
"use strict";
$.fn.loadmore = function(options) {
var self = this,
settings = $.extend({
source: '',
step: 2
}, options),
stepped = 1,
item = self.find('.item'),
items = self.find('.items'),
finished = function() {
self.find('.items-load').remove();
},
append = function(value) {
var name, part;
item.remove();
for (name in value) {
if (value.hasOwnProperty(name)) {
part = item.find('*[data-field="'+name+'"]');
if (part.length) {
part.text(value[name]);
}
}
}
item.clone().appendTo(items);
},
load = function(start, count) {
$.ajax({
url: settings.source,
type: 'get',
dataType: 'json',
data: {start: start, count: count},
success: function(data) {
var items = data.items;
if (items.length) {
$(items).each(function(index, value) {
append(value);
});
stepped = stepped + count;
}
if (data.last === true) {
finished();
}
}
});
};
if (settings.source.length) {
self.find('.items-load').on('click', function() {
load(stepped, settings.step);
return false;
});
load(1, settings.step);
} else {
console.log('Source required to load more.');
}
};
}(jQuery))
Database
id int not null auto_increment primary key,
title varchar(200),
description text
Is good to have at least above 10 inserts to see it work right and understand it!

Found the solution.. The problem was at articles.php file in line 19 instead of
if ($articlesCount = $article->num_rows) {
$articles = $article->fetch_all();
}
it must have declare that fetch is assoc so here is the solution:
if ($articlesCount = $article->num_rows) {
$articles = $article->fetch_all(MYSQLI_ASSOC);
}

Related

Insert javascript Array into database by clicking a button php

I have the following code:
- the javascript helps me select a text file and it chooses only the id from the text file. example of text file is below:
ID,Name,Surname
re-002,ram,kelu
rf-897,rem,juke
When i added the button 'loader', the javascript readText no longer displays the id that it took from the text file.
What i want to do is to allow user to select a text file, read only the ids, and then place the ids in my database.
My html page:
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "-":
output = output.split("\n").filter((line, i) => i != 0).map(line => line.split(",")[0]).join("<br/>\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}
}
$("#loader").on("click", function(){
var upload = $.ajax({
type: "POST",
url: "loader.php",
data: {array:output},
cache: false,
beforeSend: function() {
}
});
</script>
</head>
<body>
<h1> Utilisateur Nommé </h1>
<h3> Import : <button id="loader" onclick='btn()'> Import</button>
<h3> Choose file : <input type="file" onchange='readText(this)' />
</h3>
</body>
</html>
My php page 'loader.php':
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_NAME', 'dbapp' );
$array = json_decode($_POST['output']);
$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME');
$arr_id = $mysqli->real_escape_string($array[0]);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO `user` (id) VALUES($arr_id)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br
/>';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
// close connection
$mysqli->close();
?>
Your code is brittle. But moving output declaration outside readText might help actually send some data
var output; // move the output declaration here
var reader = new FileReader();
function readText(that) {
if (that.files && that.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
output = e.target.result;
//process text to show only lines with "-":
output = output.split("\n").filter((line, i) => i != 0).map(line => line.split(",")[0]).join("<br/>\n");
document.getElementById('main').innerHTML = output;
}; //end onload()
reader.readAsText(that.files[0]);
}
}
function btn() {
var upload = new XMLHttpRequest();
upload.open("POST", "loader.php");
upload.send(JSON.stringify({ array: output }))
upload.onreadystatechange = function () {
if (upload.readyState === XMLHttpRequest.DONE) {
if (upload.status === 200) {
alert(upload.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
}
<main id="main"></main>
<h1> Utilisateur Nommé </h1>
<h3> Import : <button id="loader" onclick="btn()"> Import</button>
<h3> Choose file : <input type="file" onchange='readText(this)' />
Bonus: done without jQuery.
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started

Can't create desired json data and read their values correctly (php, ajax)

I'm making a clothes store and I want to display data in modal when product link is clicked. Each product can have more sizes and each size have its quantity.
This line opens modal (this work fine)
<span>View</span>
The code below sends "id" to fetch_id.php file and displays data in modal
<script type="text/javascript">
$(document).ready(function() {
$('.quick-view-btn').bind('click', function() {
var id=$(this).attr("id");
$.ajax({
url:"fetch_id.php",
cache:false,
data:'id='+id,
dataType: "json",
success:function(data){
var aslika = data['artikli']['artslika']; //get picture
var aime = data['artikli']['artime']; //get name
var acijena = data['artikli']['artcijena']; //get price
var artcode = data['artikli']['artcode']; //get art code
var aopis = data['artikli']['artopis'];
$('.a_slika').attr("src", 'slike/'+aslika);
$('.a_ime').html(aime);
$('.a_cijena').html(acijena+' Kn');
$('.a_artcode').html('šifra: '+artcode);
$('.a_opis').html(aopis);
$('.a_id').attr("href", 'single-product.php?id='+artcode);
}
});
});
});
</script>
Here is my fetch_id.php file
$prid = $_GET['id'];
$active = 1;
if ($stmtart = $mysqli->prepare("SELECT aid, art_code, glkat, kat, ime_a, opis, kolicina, cijena, stara_cijena, ocjena, slika, status, datum, xs, s, m, l, xl, xxl, xxxl FROM artikli WHERE status = ? and aid = ? LIMIT 1")) {
$stmtart->bind_param('ii', $active, $prid );
$stmtart->execute();
$stmtart->store_result();
$stmtart->bind_result($a_id, $aart_code, $a_glkat, $a_kat, $a_ime, $a_opis, $a_kolicina, $a_cijena, $a_scijena, $a_ocjena, $a_slika, $a_status, $a_datum, $a_xs, $a_s, $a_m, $a_l, $a_xl, $a_xxl, $a_xxxl);
$stmtart->fetch();
}
if ($stmtvelicine = $mysqli->prepare("SELECT vid, oznaka, kolicina FROM velicine WHERE artid = ? ORDER BY vid ASC")) {
$stmtvelicine->bind_param('i', $prid );
$stmtvelicine->execute();
$stmtvelicine->store_result();
$stmtvelicine->bind_result($v_id, $v_oznaka, $v_kolicina);
}
$artikli = array("artikli" => array("artslika"=>$a_slika, "artime"=>$a_ime, "artcijena"=>$a_cijena, "artcode"=>$aart_code, "artopis"=>$a_opis));
$counter = 0;
while($stmtvelicine->fetch()) {
$counter = $counter + 1;
$velicine = array('vel'.$counter => $v_oznaka);
$komada = array('kom'.$counter => $v_kolicina);
array_push($artikli, $velicine);
array_push($artikli, $komada);
}
$json = json_encode($artikli);
echo $json;
The result I'm receiving is in this format...
{"artikli":{"artslika":"sn.jpg","artime":"Dress","artcijena":"129.56","artcode":"PD1001","artopis":"Default Description"},"0":{"vel1":"XS"},"1":{"kom1":5},"2":{"vel2":"L"},"3":{"kom2":2},"4":{"vel3":"XL"},"5":{"kom3":4}}
The problem is that my "while loop" creates numbers as keys so if some product have many sizes it will have many unknown keys.
Can you help me to read their values with ajax? Is there a better way to solve this?
Thank you very much,
Ivan.

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

Insert javascript into php file (or vice versa)

I have a Server file written in php, and a client html file (mainly javascript), I want to have both put into one file and still communicate. I tried copying the php code of the server above the client code but it didn't work. So this is how it was like:
<!doctype html>
<html>
<meta charset='UTF-8' />
<style>
input, textarea {border:1px solid #CCC;margin:0px;padding:0px}
#body {max-width:800px;margin:auto}
#log {width:100%;height:400px}
#message {width:100%;line-height:20px}
</style>
<?php
// prevent the server from timing out
set_time_limit(0);
// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';
// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
// check if message length is 0
if ($messageLength == 0) {
$Server->wsClose($clientID);
return;
}
$x = 0;
//The speaker is the only person in the room. Don't let them feel lonely.
for ($i=1; $i <= 10; $i++) {
$q=".68.111.160";
$string =100+$i*10;
$string .= $q;
$Server->wsSend($clientID, $string);
sleep (3);
}
}
// when a client connects
function wsOnOpen($clientID)
{
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
$Server->log( "$ip ($clientID) has connected." );
//Send a join notice to everyone but the person who joined
foreach ( $Server->wsClients as $id => $client )
if ( $id != $clientID )
$Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}
// when a client closes or lost connection
function wsOnClose($clientID, $status) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
$Server->log( "$ip ($clientID) has disconnected." );
//Send a user left notice to everyone in the room
foreach ( $Server->wsClients as $id => $client )
$Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}
// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('127.0.0.1', 9300);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="fancywebsocket.js"></script>
<script>
var Server;
function log( text ) {
$log = $('#log');
//Add text to log
$log.append(($log.val()?"\n":'')+text);
//Autoscroll
$log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
}
function send( text ) {
Server.send( 'message', text );
}
</script>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://datamaps.github.io/scripts/datamaps.world.min.js?v=1"></script>
<script src="converter.js"></script>
<div id="container1" style="position: relative; width:900px; height: 700px;"></div>
<script>
var map = new Datamap({
scope: 'world',
element: document.getElementById('container1'),
projection: 'mercator',
fills: {
lt50: 'rgba(0,244,244,0.9)',
on: 'red',
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(50,0,0)',
off: "#ABDDA4",
defaultFill: "#ABDDA4"
},
data: {
}
})
var x;
var colors = d3.scale.category10();
$(document).ready(function() {
log('Connecting...');
Server = new FancyWebSocket('ws://127.0.0.1:9300');
$('#message').keypress(function(e) {
if ( e.keyCode == 13 && this.value ) {
log( 'You: ' + this.value );
send( this.value );
$(this).val('');
}
});
//Let the user know we're connected
Server.bind('open', function() {
log( "Connected." );
});
//OH NOES! Disconnection occurred.
Server.bind('close', function( data ) {
log( "Disconnected." );
});
//Log any messages sent from server
Server.bind('message', function( payload ) {
log( payload );
var ip = payload;
$.get("http://ipinfo.io/" + ip, function(response) {
x = response.country;
}, "jsonp");
var interval_x = window.setInterval(function() {
var country_name = convert[x];
var interval_1 = window.setInterval(function() {
var country = {}
var country = {}
country[country_name] = {
fillKey: 'on'
}
map.updateChoropleth(country);
}, 2000);
myVar = window.setTimeout(function() {
clearInterval(interval_1);
var country = {}
country[country_name] = {
fillKey: 'off'
}
map.updateChoropleth(country);
}, 4000);
}, 4000);
});
Server.connect();
});
//---------------------------------------IP Goes Here------------------------------------------------
</script>
<body>
<div id='body'>
<textarea id='log' name='log' readonly='readonly'></textarea><br/>
<input type='text' id='message' name='message' />
</div>
</body>
</html>
But it wouldn't work, knowing that this was put in an html file.
We don't have all your embedded scripts for this special case. But generally you can put HTML, CSS, PHP and JavaScript in the same file. The file has to end with '.php' and PHP must be installed ("test.php"):
<!doctype html>
<html><head>
<title>Test</title>
</head><body>
<div id="test">
<?php echo 'foobar'; ?>
</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
</body></html>
Should output "foobar".

Javascript cannot process JSON text file

I am following some tutorial to pass a JSON text file from server to display the data after some javascript processing on a html file. As a test, try to display a LI of one column, but cannot get any output in the browser. Your help is appreciated.
I tried two approaches.
Approach 1 xmlhttp:
Apparently, the browser complain about the html format:
Uncaught SyntaxError: Unexpected string (15:08:42:080 | error, javascript)
at testJSON3.html:12
Is my xmlhttp call format correct?
Thank you for your help in advance.
Here's JSON text myTutorial.txt:
[
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name 1",
"eventDesc":"2015 class of course name 1"
},
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name21",
"eventDesc":"2015 class of course name "
}
]
And processed by the below html to process the xmlhttp access to the file on server localhost directory phpTWLLT
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost/phpTWLLT/myTutorial.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for (i = 0; i < arr.length; i++) {
out += '<li'> + arr[i].courseCode +'</li><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Approach 2 getJSON():
This one is interesting. If the server side is static array ($DEBUG = true:), javascript is able to process and get browser display. But fail when generate the text from mysql ($DEBUG = false).
I am scratching my head to get the $DEBUG=false work? Apparently, both cases generated a valid JSON text.
If $DEBUG is set true,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr#example.com"},{"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"john_doe#example.com"}]
the list displayed in browser.
0
1
If $DEBUG is set false,
output from localhost/phpTWLLT/json_encode_array.php
[{"active":"1"},{"active":"1"}]
The browser display is blank.
html file:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<!--
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'> </script>
-->
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script type='text/javascript'>
$(document).ready(function () {
/* call the php that has the php array which is json_encoded */
//$.getJSON('json_encoded_array.php', function(data) {
$.getJSON('json_encoded_array.php', function (data) {
/* data will hold the php array as a javascript object */
$.each(data, function (key, val) {
$('ul').append('<li id="' + key + '">' + val.active + '</li>');
});
});
});
</script>
</body>
</html>
PHP script: json_encoded_array.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/* set out document type to text/javascript instead of text/html */
$DEBUG = true;
if ($DEBUG) {
header("Content-type: text/javascript");
$arr = array(
array(
"active" => "0",
"first_name" => "Darian",
"last_name" => "Brown",
"age" => "28",
"email" => "darianbr#example.com"
),
array(
"active" => "1",
"first_name" => "John",
"last_name" => "Doe",
"age" => "47",
"email" => "john_doe#example.com"
)
);
} else {
require_once('connection.php');
// $m_id= 8 has many enrolled course and 11 got exactly one course enrolled.
$m_id = 8;
$p_id = 1;
$qry1 = "SELECT distinct event.active as active, subject.code as 'courseCode', subject.name as 'courseName', event.event_desc as 'eventDesc' FROM applicant, event, subject, part where applicant.applicant_id = $m_id and applicant.event_id = event.id and event.subject_id=subject.id and part.id = subject.owner_id and part.id = $p_id order by event.active DESC, event.from_month DESC ";
mysqli_set_charset($bd, 'utf-8');
$result = mysqli_query($bd, $qry1);
$arr = array();
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ( $rs = mysqli_fetch_assoc($result) ) {
$colhead = "active";
$str = $rs['active'];
$arr[$i] = array($colhead => $str);
$i++;
// just generate two record for testing
if ($i === 2)
break;
}
}
}
echo json_encode($arr);
?>
For approach 2, did you try debugging the javascript code to check if the data variable contains the expected data?
You could also check the network tab to see if the response data sent from your server is correct.

Categories