Why echo function print data in console? - php

I'm creating page in PHP but when I use AJAX to send data, echo function start to printing data in console instead in DOM elements.
I want to add Quagga barcode reader to my page. Quagga is write in JS but my page is in php. So I have to use Ajax to send barcode result to my php code. And there is a problem. After sending data (POST) and using echo to display that on the screen, every data that echo should display are showing up in console. Not only data I send but whole page html code too. Even header('Location: ') doesn't work correctly. Because I'm sending readed code to barcodereaded.php where I put POST data inside SESSION var, and I try to echo that on the screen in different file barcoderesult.php but everytime data is printed in console log in barcode.php (which code is below). On every other subpage php echo and header functions works fine, only this one case causing troubles.
<div id="scanner-container"></div>
<input type="button" id="btn" value="Start/Stop" />
<script src="js/quagga.min.js"></script>
<script>
var _scannerIsRunning = false;
function startScanner() {
var barcode = {};
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
numOfWorkers: navigator.hardwareConcurrency,
target: document.querySelector('#scanner-container'),
constraints: {
size: 1920,
width: 200,
height: 480,
facingMode: "environment"
},
},
config: {
frequency: 5,
},
locator: {
patchSize: "x-large",
},
decoder: {
readers: [
"code_128_reader",
"ean_reader",
"ean_8_reader",
"code_39_reader",
"code_39_vin_reader",
"codabar_reader",
"upc_reader",
"upc_e_reader",
"i2of5_reader"
],
debug: {
showCanvas: true,
showPatches: true,
showFoundPatches: true,
showSkeleton: true,
showLabels: true,
showPatchLabels: true,
showRemainingPatchLabels: true,
boxFromPatches: {
showTransformed: true,
showTransformedBox: true,
showBB: true
}
}
},
}, function (err) {
if (err) {
console.log(err);
return
}
console.log("Initialization finished. Ready to start");
Quagga.start();
// Set flag to is running
_scannerIsRunning = true;
});
Quagga.onProcessed(function (result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: "green", lineWidth: 2 });
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "#00F", lineWidth: 2 });
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: 'red', lineWidth: 3 });
}
}
});
Quagga.onDetected(function (result) {
Quagga.stop();
barcode.code = result.codeResult.code;
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
});
}
// Start/stop scanner
document.getElementById("btn").addEventListener("click", function () {
if (_scannerIsRunning) {
Quagga.stop();
_scannerIsRunning = false;
} else {
startScanner();
}
}, false);
</script>
I just want to send readed barcode to other file to convert it into data I want to add to database (quantity of elements on the pallet, production date, etc.)

Look at this part of your code :
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
The success method tells what to do with the result of your ajax code.
And here you specifically tell to log the response (res) to the console.
Instead you can use the content of res to append it to your dom via your preferred Javascript solution (vanilla, jQuery,...).
With jQuery you could (if the result from your php code is some text):
$('#my-return-container').text(res)

Related

How to populate Jvector Map with countries from database?

(I am new to Javascript and jQuery..) I have a dashboard and I want to display a map that shows the countries where participants of a particular event are coming from. With this, I opted with Jvector Map. I am having a hard time displaying the countries in the map, coming from my database.
dashboard.js
var mapData = {};
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 0.9,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 0
}
},
series: {
regions: [{
values: function() {
$.ajax({
url:"includes/sql/fetchcountries.php",
method:"GET",
data:mapData,
dataType:"json",
success: function(data){
mapData = data;
console.log(mapData);
}
})
},
scale: ["#1ab394", "#22d6b1"],
normalizeFunction: 'polynomial'
}]
},
});
fetch.php
<?php
require '../auth/dbh.inc.auth.php';
$id = $_SESSION['ntc_id'];
$stmt = $conn->prepare("SELECT DISTINCT(participants.p_country) FROM ntc_participants
INNER JOIN participants ON participants.p_id=ntc_participants.p_id_fk
WHERE ntc_participants.ntc_id_fk=?");
$data = array();
mysqli_stmt_bind_param($stmt, "i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0);
if($row = $result->fetch_assoc()) {
$data[] = [
$row['p_country'] => 0 ]; //the value 0 is just a placeholder.. The jvector map feeds on this format: "US":298, "SA": 200
}
echo json_encode($data);
?>
Could anyone be gracious enough to walk me through all the wrong things I'm doing in my code? Appreciate all the help! :)
Ajax is asynchronous, so You are creating the map before the data has been downloaded.
Initialize the map with empty values for Your region:
$('#world-map').vectorMap({
...
values: {}
...
});
Then, whenever You need to show the data, set it dynamically:
$.get("includes/sql/fetchcountries.php", function(data) {
var mapObj = $("#world-map").vectorMap("get", "mapObject");
mapObj.series.regions[0].setValues(data);
});
During the ajax invocation and data download maybe You can show a spinner (please look at beforeSend inside the jQuery full ajax documentation: https://api.jquery.com/jquery.ajax/).
Here is the reference for setValues:
http://jvectormap.com/documentation/javascript-api/jvm-dataseries/
http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018
This link will give you up-to-date stats for most common indicators via json - and then you can pluck whatever data that you like. I don't have all the code yet, as I am working on this today too.
This answers the question above whenever your database can also present JSON
document.addEventListener('DOMContentLoaded', () => {
console.log("loaded")
fetchCountryData()
})
function fetchCountryData () {
fetch('http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018')
//
.then(resp => resp.json())
.then(data => {
let country.id = data[1]
let indicator.id = data[1]
create-GDP-Data(country.id,indicator.id)
})
}
function create-GDP-Data(country.id,indicator.id){
let gdpData = ?
}
$('#world-map-gdp').vectorMap({
map: 'world_mill',
series: {
regions: [{
values: gdpData,
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
},
onRegionTipShow: function(e, el, code){
el.html(el.html()+' (GDP - '+gdpData[code]+')');
}
});

Typeahead and bloodhound post request not working in Laravel 5

This is my HTML Code:
<input autocomplete="off" type="text" id="chiefComplaintInput" name="chiefComplaintInp" class="typeahead-chiefcomplaint form-control input-circle-right" placeholder="Chief Complaints">
This is my Jquery bloodhound and typeahead code:
var chiefComplaints = new Bloodhound({
datumTokenizer: function(resp) {
return Bloodhound.tokenizers.whitespace(resp.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
wildcard: '%QUERY',
url: "/opd/searchChiefComplaints/",
transform: function(response) {
return $.map(response, function(restaurant) {
return { value: restaurant.name };
});
}
}
});
$('input#chiefComplaintInput').typeahead({
hint: false,
highlight: true,
minLength: 2,
limit: 10
},
{
name: 'chiefComplaints',
display: 'value',
source: chiefComplaints,
templates: {
header: '<h4 class="dropdown">Restaurants</h4>'
}
});
This is the routes that i ahve defined:
Route::get('opd/searchChiefComplaints/{queryParam}', 'OpdController#searchChiefComplaints');
This is the controller code:
public function searchChiefComplaints(Request $request)
{
// return Response::json($request->get('queryParam'));
return $request->get('queryParam');
}
What i am trying to achieve is that i want to send post request to the controller and receive the JSON in response. Bu i am having problem attaining it i dont know where my code is going wrong :(
JSON posted data cannot be read by $request->get(). You should use $request->input().
See this (declined) PR: https://github.com/laravel/framework/pull/13566#issue-154985037

jquery select2: error in getting data from php-mysql

I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

Kendo UI > Update Grid > Internal Server Error Generated

I've been beating my head against my desk for a few days now… time I asked for help.
I'm trying to update a value within Kendo UI's grid. The grid displays correctly, as does the popup editor. That's where the good times end. Here's the situation:
Click 'Edit' > Popup Opens > Click 'Update' (no change made) > Popup closes. Result = As expected.
Click 'Edit' > Popup Opens > Click 'Cancel' > Popup closes. Result = As expected.
Click 'Edit' > Popup Opens > Update the 'clientName' field > Click 'Update'. Result = Value in the row changes (in the background), popup stays open and a alert is displayed stating 'undefined'. If I then close the popup the change is lost. As part of this process a 500 internal server error is also generated.
Here's my Kendo code:
$(document).ready(function () {
var crudServiceBaseUrl = "assets/data/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "data.clients.php",
},
update: {
url: crudServiceBaseUrl + "data.clients.update.php",
},
create: {
url: crudServiceBaseUrl + "data.clients.create.php",
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 10,
error: function(e) {
alert(e.responseText);
},
schema: {
data: function(result) {
return result.data || result;
},
total: function(result) {
var data = this.data(result);
return data ? data.length : 0;
},
model: {
id: "clientID",
fields: {
clientID: { editable: false, nullable: true },
clientName: { validation: { required: true } },
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: ["create"],
columns: [
{ field: "clientID", title: "Client ID" },
{ field: "clientName", title: "Client Name"},
{ command: "edit", title: " ", width: 110 }],
editable: "popup"
});
});
Here's my PHP:
include '../includes/connect.php';
$clientName = mysql_real_escape_string($_POST["clientName"]);
$clientID = mysql_real_escape_string($_POST["clientID"]);
$rs = mysql_query("UPDATE cms_clients SET clientName = '" .$clientName ."' WHERE clientID = " .$clientID);
if ($rs) {
echo json_encode($rs);
}
else {
header("HTTP/1.1 500 Internal Server Error");
echo "Update failed for EmployeeID: " .$clientID;
}
Oh, and I know this code has issues with potential injection. That's step 2.
Any help would be appreciated.
Thanks,
#rrfive

jqGrid errorTextFormat function

I´m developing an application using CodeIgniter and JQuery.
I have read here jqgrid error message on delete and here jqGrid error message from server side exception some issues about this problem but the fact is that does not work for me.
In my database I have set some business rules in form of index, checks, etc. I need to customize the "error Status: 'error'. Error code: 500" that the jqGrid returns when I have those types of errors.
I´d appreciate any help.
Here is my jquery grid code.
<script type="text/javascript">
var base_url = 'http://localhost/sp/';
var site_url = 'http://localhost/sp/index.php';
var url = '';
$(document).ready(function() {
var grid = jQuery("#newapi_1351019084").jqGrid({
ajaxGridOptions : {type:"POST"},
jsonReader : {
root:"data",
repeatitems: false
},
ondblClickRow: function(id){
dtgLoadButton1();
return;
},
rowList:[10,20,30],
viewrecords: true
,url:'http://localhost/sp/index.php/assigment/getData'
,editurl:'http://localhost/sp/index.php/assigment/setData'
,datatype:'json'
,rowNum:'13'
,width:'800'
,height:'300'
,pager: '#pnewapi_1351019084'
,caption:'Control de asignaciones'
,colModel:[
{name:'username',index:'username',label:'Usuario' ,align:'left',width:300,editable:false,edittype:'text',editrules:{required:true} }
,{name:'StoreName',index:'StoreName',label:'Tienda' ,align:'center',width:200,editable:false,edittype:'text',editrules:{required:true} }
,{name:'Users_idUsers',index:'Users_idUsers',label:'Usuario' ,align:'center',width:100,hidden:true,editable:true,edittype:'select',editoptions:{value:":Select;5:tienda1;6:tienda2;17:tienda3;18:tienda11",size:10},editrules:{edithidden:true,required:true,integer:true} }
,{name:'Stores_idStores',index:'Stores_idStores',label:'Tienda' ,align:'center',width:100,hidden:true,editable:true,edittype:'select',editoptions:{value:":Select;1:EA001;3:EA003;4:EA005;5:EA006;6:EA007;7:EA008;8:EA009;9:EA010;10:EA011;11:EA012;12:EA013;13:EA015;14:EA017;15:EA018;16:EA019;17:EA020;18:EA021;19:EA022;20:EA002;21:EA000",size:10},editrules:{edithidden:true,required:true,integer:true} }
,{name:'SurrugateTurn',index:'SurrugateTurn',label:'SurrugateTurn' ,align:'center',width:100,key:true,hidden:true,editable:true,edittype:'select',editoptions:{value:":Select;1:1;3:3;2:2",size:10},editrules:{hidden:true} }
] })
jQuery("#newapi_1351019084")
.jqGrid('navGrid',
'#pnewapi_1351019084',
{view:false,
edit:'1',
add:'1',
del:'1',
close:true,
delfunc: null ,
search:''
},
{ recreateForm: true,
width : 400 ,
beforeShowForm : function(form) {
},
closeAfterEdit:true }, // edit options
{ recreateForm: true,
width : 400,
closeAfterAdd : true,
beforeSubmit : function(postdata, formid) {
var mensaje = '';
var resultado = true;
return[resultado,mensaje];
}
}, /*add options*/
{mtype: 'POST'} /*delete options*/,
{sopt: ['eq','cn','ge','le' ] ,
multipleSearch: false ,
showOnLoad : false,
overlay:false,mtype: 'POST'} /*search options*/
).navButtonAdd('#pnewapi_1351019084',
{ caption:'', buttonicon:'ui-icon-extlink', onClickButton:dtgOpenExportdata, position: 'last', title:'Export data', cursor: 'pointer'}
);
;
});
</script>
Best regards and thanks for your time,
Assuming the server returns a user-friendly error message with the HTTP 500 response, you can simply to this:
...
{ recreateForm: true,
width : 400 , //removed the empty beforeShowForm callback
errorTextFormat:function(data){
if (data.status == 500)
return data.responseText; // You may need to do some HTML parsing here
}
closeAfterEdit:true }, // edit options
...

Categories