html_entity_decode is not working properly with json_encode ajax - javascript

Hi I've this Testing's Ones value stored in database now when I'm fetching my value into text field it is not showing like this Testing's and my code is
$loadingPlanName = "SELECT * FROM " . DB_PREFIX . $tableName . " WHERE $tablePrimaryKey='$loadingPlanId'";
$sqlResult = mysqli_query($dbCon, $loadingPlanName);
if (#mysqli_num_rows($sqlResult) > 0) {
$jsonReturnArray["lpListingsData"] = mysqli_fetch_assoc($sqlResult);
if($jsonReturnArray["lpListingsData"]["loadingPlanName"]) {
$jsonReturnArray["lpListingsData"]["loadingPlanName"] = html_entity_decode($jsonReturnArray["lpListingsData"]["loadingPlanName"]);
}
}
echo json_encode($jsonReturnArray);
exit;
and my javascript/jquery code is
$("#loadingPlanName").val(data.lpListingsData.loadingPlanName);
but in text field it is not showing data properly the data should be in text filed Testing's instead of Testing's Ones. I didn't understand why html_entity_decode is not working.

Related

How to extend string limit, while converting it from MYSQL database to excel in dropdown list using PHP

I'm trying to get my MySQL data to Excel file as dropdownlist, but I'm having problems with its string limit. The excel file get corrupted if string limit exceed from 255. Here is my code:
foreach ($sequence as $sequence_no) {
if ($pattern_record['attribute_' . $sequence_no . '_name'] != "") {
$cell = $objWorkSheet->getCell($column . $row);
$cell->setValue($pattern_record['attribute_' . $sequence_no . '_name']);
if (!empty($pattern_record['attribute_' . $sequence_no . '_variable_value'])) {
for ($j = 2; $j <= $no_emp; $j++) {
$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()
->setCellValue($column . "" . $j, "");
$configs = $pattern_record['attribute_' . $sequence_no . '_variable_value'];
$objValidation = $excel->getActiveSheet()->getCell($column . $j)->getDataValidation();
$objValidation->setType(PHPExcel_Cell_DataValidation::TYPE_LIST);
$objValidation->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
$objValidation->setAllowBlank(false);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setShowDropDown(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Value is not in list.');
$objValidation->setPromptTitle('Pick from list');
$objValidation->setPrompt('Please pick a value from the drop-down list.');
$objValidation->setFormula1('"' . $configs . '"');
}
}
//check and set datatype in excel
//General format
else if (in_array($sequence_no, $datatype_varchar)) {
$excel->getActiveSheet()->getStyle($column)
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
} else if (in_array($sequence_no, $datatype_text)) {
//text format
$excel->getActiveSheet()->getStyle($column)
->getNumberFormat()
->setFormatCode(
'0'
);
} else if (in_array($sequence_no, $datatype_int)) {
// numerical format
$excel->getActiveSheet()->getStyle($column)
->getNumberFormat()
->setFormatCode(
'0'
);
} else if (in_array($sequence_no, $datatype_date)) {
// date format
$excel->getActiveSheet()->getStyle($column)->getNumberFormat()
->setFormatCode('yyyy-mm-dd');
}
$excel->getActiveSheet()->getStyle("$column$row:$column$row")->getFont()->setSize(14);
$excel->getActiveSheet()->getStyle("$column:$column")->getFont()->setSize(12);
$excel->getActiveSheet()
->getColumnDimension($column)
->setAutoSize(true);
$excel->getActiveSheet()->getStyle($column . $row . ':' . $column . $row)->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFE8E5E5');
$col++;
$column++;
} }
It is downloading properly if data it is in between 255 length but get corrupted if it is exceed. Please suggest something.
Don't put the data directly into the dropdown. Write it to a set of cells, and then set the dropdown to the cellrange. That way, it's not restricted by the MS Excel string limit for a data validation list

bring data from a JSON and show in a popup

I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!

Issue with PHP and Javascript when building auto suggest text box

I'm trying to build a simple auto suggest input bar that connects to a MySql database and retrieves data. The issue that I'm running into is that when I type in the name of an object that I know exists in the databse, the text bar doesn't return any results, instead it just provides me with an empty dropdown box.
The best I can tell, the issue has to do with the javascript that is used within the PHP portion of the code. Unfortunately, I can't seem to figure out why it's causing an issue.
<?php
mysql_connect("host", "user", "passsword") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DBName');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo"<script type='text/javascript'>";
echo"this.nameArray = new Array()";
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray" .$row ['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
When I take out the echo"<script type='text/javascript'>"; and echo"this.nameArray = new Array()"; then It displays the Device_type content on the top of the page when the page is loaded. This obviously isn't what I want, but it does prove that the database connection is at least set up correctly. Since this chunk of PHP is referring to some javascript, I will also prove the function in which it's referring to.
function doSuggestions(text) {
var input = text;
//window.alert(text);
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
Any suggestions as to why the suggestion box isn't providing suggestions when I start typing? If I type A into the text box, the suggestion box should appear showing me all items in the database that start with A.
there are some errors in your js strings
`echo"var nameArray = new Array()";`
`echo("nameArray.push('" .$row ['Device_type'] . "');");`
that way you'll push device types into the nameArray var.

How to retrieve data from .php and display in <select> within Cordova hybrid app?

I am writing a hybrid app using Visual Studio with Cordova exetnstion and trying to pull data from www.a.com/b.php
My b.php code is:
<?php
// Connect to database server
mysql_connect("http://www.yo.com", "ya", "ye") or die (mysql_error());
// Select database
mysql_select_db("oh") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Properties ORDER BY number DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
echo '<select name="Address" id="address_search" style="width:282px; display:block;" required>';
while($row = mysql_fetch_array($rs))
{
// Write the value of the full address including unit code, address, city, state, zipcode (which is now in the array $row)
echo '<option value="'. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .'">'
. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .
'</option>';
}
echo '</select>';
// Close the database connection
mysql_close();?>
I already add select tag form directly in php code, but I don't know how to display the whole select box (with options being retrieved data) in .html.
Any help or tutorial? Thanks.
I have solved this issue like this:
First, in the server side-code (php in this case), in "file.php", I have an array with the database elements and I do the following:
$arrayElements = json_encode($arrayElements );
echo $_GET['jsoncallback'] . '(' . $arrayElements . ');';
After that, in the app js code, I use jQuery method $.getJSON() for getting the php array we prepare before. When the function get the server answer, then execute the code inside. Note that the variable "respuestaServer" is the array you have sent from php file, so you can go throw it with a loop and taking its values to your select (if you need to pass variables to your php file and receive them via GET just add the js variables inside the {}, in this example I send the variable datosUsuario and in php I receive it $_GET['usuario']).
var archivoValidacion = "http://example.com/file.php?jsoncallback=?";
var select = document.getElementById("idSelect");
$.getJSON( archivoValidacion, { usuario:datosUsuario ,password:datosPassword})
.done(function(respuestaServer) {
for(var i = 0; i < respuestaServer.length;i++){
var option = document.createElement("option");
var textNode = document.createTextNode(respuestaServer[i]);
option.appendChild(textNode);
select.appendChild(option);
}
})
I hope this can help you. If you have some questions just tweet me #ulisesveraes ;)
it is not clear how you call this code
I suppose you do this with jQuery ajax function
so your code will like something this
$('box-selector').load('b.php');

Creating D3 Line Graph Based off of Drop-down selection

I am trying to create a D3 line graph that will display a graph specific to the item that is selected in the drop-down menu. I have one script that queries my MySQL database and fills a drop-down menu with all of the correct options. From there, I want to click on an option and go to another page that creates a line graph based off of that selection. When I click on an option, I use json_encode to create a JSON object that should be compatible with D3.
I have another script that deals completely with drawing the graph and try to use d3.json to get the JSON object that is created when the specific selection is clicked. Whenever I try to load the graph page, it is completely blank. I am not sure if what I am trying to do is even possible. I have not tried including the drop-down in the same script as the one that creates the graph but do not think that I will be able to get the information from the database the same way.
Any guidance or suggestions would be greatly appreciated. I can post the code later if it is determined what I am trying to do is possible. Thanks!
EDIT:
This is the script that queries my database for the users that are put in the drop-down menu and then queries the database again for that selection's data. The drop-down menu has the desired result and the data is correctly echoed as well.
<?php
if (isset($_POST['name']))
{
$out = $_POST['name'];
$temp = explode(",", $out);
$populate_selection = "SELECT id, lastname, firstname FROM users WHERE id != '$temp[0]' ORDER BY lastname";
$out = $temp[1] . ', ' . $temp[2];
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
}
else
{
$temp[0] = " ";
$populate_selection = "SELECT id, lastname, firstname FROM users ORDER BY lastname";
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
$out = " ";
}
$result = $mysqli->query($populate_selection);
$option = "<option value= '{$temp[0]}'>$out</option>";
while($row = mysqli_fetch_assoc($result)) {
$option .= "<option value = '{$row['id']}, {$row['lastname']}, {$row['firstname']}'>{$row['lastname']}, {$row['firstname']} </option>";
}
if($student_results = $mysqli->query($student_hours))
{
$data = array();
for ($x = 0; $x < mysqli_num_rows($student_results); $x++)
{
//this array contains the data that I want in my graph
//the correct data is echoed every time that I click on the different choices
$data[] = mysqli_fetch_assoc($student_results);
}
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
<form id = "hello" method = "POST" >
<select name = "name" onchange = 'this.form.submit()'> <?php echo $option; ?> </select>
</form>
I then try and use d3.json("filename.php", etc) to get the information from the $data array but this has not worked.

Categories

Resources