So i have problem whit symbols "&", here my code on javascript
$("#shipCurr").change(function(){
var curr = $(this).val();
$("#shipPO").empty();
if(curr != "")
{
$("#shipPO").prop('disabled',false);
$.ajax
({
type: "POST",
url: host+"buypo/ListPOShippDoc",
data:{
'curr':curr
},
cache: false,
success:function(data)
{
console.log($("#shipPO").html(data));
}
});
}
else
{
$("#shipPO").prop('disabled',true);
}
// console.log("test");
});
and on php code
public function ListPOShippDoc()
{
$currency = $_POST['curr'];
$fullName = $_SESSION['fullName'];
$PONo = $this->shippDoc->ListPO($fullName,$currency)['items'];
$option .= '<option value=""></option>';
while ($val = $PONo->fetch_assoc()) {
$option .= '<option value="'.utf8_decode($val['PONo']).'">'.utf8_decode($val['PONo']).'</option>';
}
echo $option;
}
My problem is,if the PONo value like H&M-000762-001 it show on my html into H&M-000762-001.
How do i get wrong in here? Wy it show H&M-000762-001 not H&M-000762-001? Any idea?
I try utf8_decode() utf8_encode() is still same result H&M-000762-001.
function convertSymbol($value)
{
$value = mb_convert_encoding($value, "ISO-8859-1", "UTF-8");
$ampersandval = str_replace("&", "&", $value);
return $ampersandval;
}
?>
/* mb_convert_encoding this function is used to Convert ISO to UTF-8 */
Using str_replace function we can convert & to &
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
I am performing a foreach loop and then sending that data. Then in my AJAX function I am outputting the information in the success function. This all works fine.
However, I just tweaked the code to include a new data-attribute. This data-attribute holds the $creator variable. It can be seen here:
$html .= '<div class="projectCont" data-current="'.$category.'" data-creator="'.$project_creator.'">';
The correct data is outputting.
What I am having issues with is adding the active class to the container - .projectCont when the data-attribute - data-creator is customer.
Right now it seems like only the last looped object is being checked and then whatever this is, the rest of the data is taking on.
For example: I have around 10 looped object being outputted. For testing purposes, I changed the creator to "Customer" for only one of these - the last one in the database. Now when all of these loop and output, every single record has the class that was added based on my condition in the success.
Does anyone know why this is happening? I nested this condition in the each function thinking that it would check and modify each individual record.
Condition in question (see JS for more code):
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
JS:
success: function (data) {
//console.log(data);
if (data == null) {
alert("Unable to retrieve projects!");
alert(data);
} else {
var displayProjects = JSON.parse(data);
$wrapper.empty();
$(displayProjects).each(function() {
$wrapper.append(this.html);
//console.log(this.html);
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
});
$wrapper.append(startBuilding);
}
PHP:
if ($projects_stmt = $con->prepare($projects_sql)) {
$projects_stmt->execute();
$project_rows = $projects_stmt->fetchAll(PDO::FETCH_ASSOC);
$proj_arr = array();
foreach ($project_rows as $project_row) {
$project_creator = $project_row['creator'];
$html = '';
$html .= '<div class="projectCont" data-current="'.$category.'" data-creator="'.$project_creator.'">';
$html .= '<div class="creatorIcon"><img src="/Projects/expand.png" alt="Customer Photo"></div>';
$html .= '</div>';
$data = array('id' => $project_row['id'], 'date' => $project_row['date_added'], 'html' => $html);
$proj_arr[] = $data;
}
}
echo json_encode($proj_arr);
More JS:
$('.categoryList').on('click', function (event) {
$('#projectsWrap').addClass('active'); //Once a category is selected the project wrap section will show
$wrapper = $('#projectGallery');
category = $(this).data('category');
//console.log(category);
$.ajax({
url: '/php/projectLoadTest.php',
type: 'POST',
data: {
'category': category
},
success: function (data) {
//console.log(data);
if (data == null) {
alert("Unable to retrieve projects!");
alert(data);
} else {
var displayProjects = JSON.parse(data);
$wrapper.empty();
$(displayProjects).each(function() {
$wrapper.append(this.html);
//console.log(this.html);
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
});
$wrapper.append(startBuilding);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
alert('There are currently no project images for this selection');
}
});
//was here
});
I think you shouldn't mess with the JS in this case - you can do this class manipulation in your PHP:
if ( $projects_stmt = $con->prepare( $projects_sql ) ) {
$projects_stmt->execute();
$project_rows = $projects_stmt->fetchAll( PDO::FETCH_ASSOC );
$proj_arr = array();
foreach ( $project_rows as $project_row ) {
$project_creator = $project_row[ 'creator' ];
$html = '';
$html .= '<div class="projectCont" data-current="' . $category . '" data-creator="' . $project_creator . '">';
// setting the active string - if Customer -> ' active'
$is_active = ( $project_creator == 'Customer' ) ? ' active' : '';
$html .= '<div class="creatorIcon' . $is_active . '"><img src="/Projects/expand.png" alt="Customer Photo"></div>';
$html .= '</div>';
$data = array( 'id' => $project_row[ 'id' ], 'date' => $project_row[ 'date_added' ], 'html' => $html );
$proj_arr[] = $data;
} // foreach
} // if
echo json_encode( $proj_arr );
AJAX
function ajax_json_gallery(folder) {
alert(folder);
var thumbnailbox = $('#thumbnailbox');
$.ajax({
type: "POST",
url: "json_gallery_data.php",
contentType: "application/x-www-form-urlencoded",
dataType: "json",
data: "folder=" + folder,
success: function(d) {
for (var obj in d) {
if (d.hasOwnProperty(obj)) {
alert(d[obj]); //access data//
alert(d[obj].src); //undefined//
}
}
}
});
}
PHP
header('Content-Type: application/json');
$folder = "Img/Company1/Jersey1";
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$directoryfiles[] = '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
echo json_encode($directoryfiles);
console.log(d)
[""img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },",
""img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },",
""img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },",
""img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" },"]
x3
i am using ajax to get all image inside the folder directory , and return to ajax but when i tried to access the d[o].src it return undefined ,i had no idea what am i missing here.
Don't try to write JSON text yourself. Just create an associative array or stdClass object, add the appropriate key/values, then add that to $directoryfiles. json_encode will then do the proper encoding
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$temp = new stdClass;
$temp->num = $i;
$temp->src = $src;
$temp->name = $file;
$directoryfiles["img".$i] = $temp;
}
}
closedir($dirHandle);
echo json_encode($directoryfile);
change the format of json to,
{"img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },
"img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },
"img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },
"img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" }};
then u use the code,
console.log(d.img1.src);
I am running a simple chat application and it's powered by a process.php file, but the chat is on chat.php.
Basically people can search for a "Topic", and it'll take them to domain.tld/chat.php?topic=topicname (topicname being whatever they searched for)
I need my process.php file to echo
<?php echo $_GET['topic']; ?>.txt
instead of chat.txt, so that each topic has a unique text file (so that all chats aren't linked)
This is my process.php file:
<?php
$function = $_POST['function'];
$log = array();
switch($function) {
case('getState'):
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists('logs/chat.txt')){
$lines = file('logs/chat.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = htmlentities(strip_tags($_POST['nickname']));
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
$message = preg_replace('/#(\w+)/', ' #$1', $message);
fwrite(fopen('logs/chat.txt', 'a'), "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n");
}
break;
}
echo json_encode($log);
?>
This is my chat.js file
/*
Created by: Kenrick Beckett
Name: Chat Engine
*/
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
In theory this should create a unique topicname.txt file in /logs/ whenever somebody starts chatting in a topic that's nonexistent. I'm just having trouble adding the topicname in place of chat.txt in process.php. So far I know that it does create a chat.txt file by itself, so it should create a unique .txt file once I echo it correctly.
Also, I'm aware that a database is a better option when compared to storing messages in unique .txt files, but this is how I want to do it.
Here's an example of how I was trying to add it to my process.php a snippet from process.php)
case('getState'):
if(file_exists('logs/<?php echo $_GET['topic']; ?>.txt')){
$lines = file('logs/<?php echo $_GET['topic']; ?>.txt');
}
^ That probably isn't even the right format, as I'm new to PHP and make tons of mistakes, and it probably won't know what the GET is because it's not a part of chat.php ... it's a separate file.
Try with -
'logs/' . $filename . '.txt'
where ever you want.
Update
if (!empty($_GET['topic'])) {
$filename = $_GET['topic'];
} else {
$filename = 'something else';
}
if(file_exists('logs/' . $filename . '.txt')){ $lines = file('logs/' . $filename . '.txt') ....
It is already in php. So no need to add <?php ?> and echo. Just simply concatenate them.
you are already in php tag.. no need to add extra php tags
case('getState'):
if(file_exists("logs/".$_GET['topic'].".txt")){
$lines = file("logs/".$_GET['topic'].".txt");
}
or Try this
case('getState'):
if(isset($_GET['topic']){
$filename = "logs/".$_GET['topic'].".txt";
if(file_exists($filename)){
$lines = file($filename);
}
}
}
This piece should create a csv file. The method that is calling to the nonAjaxPost is:
function exportCSV()
{
nonAjaxPost('getExport', 'post', {action: '/getView', 'view': current_pi, 'parameters': encodeURIComponent(JSON.stringify(current_parameters))});
}
function nonAjaxPost(action, method, input) {
"use strict";
var form;
form = $('<form />', {
action: action,
method: method,
style: 'display: none;'
});
if (typeof input !== 'undefined') {
$.each(input, function (name, value) {
$('<input />', {
type: 'hidden',
name: name,
value: value
}).appendTo(form);
});
}
form.appendTo('body').submit();
}
My problem is that i just can't seem to understand how this is going to create a csv file for me. I'm probaly missing out on something that i just can't see.
I really hope someone could help me out.
Update:
This is the getExport function:
$databundle = $this->_getData();
$data = $databundle['rows'];
$columns_all = $databundle['columns'];
$columns = array("Id");
foreach($data[0] as $key => $column) {
$column = "";
$found = false;
foreach($columns_all as $col_search) {
if($col_search['key'] == #$key) {
$found = true;
$column = $col_search['title'];
break;
}
}
if($found) {
//echo $key . ",";
$columns[] = $column;
}
}
$contents = putcsv($columns, ';', '"');
foreach($data as $key => $vals) {
if(isset($vals['expand'])) {
unset($vals['expand']);
}
array_walk($vals, '__decode');
$contents .= putcsv($vals,';', '"');
}
$response = Response::make($contents, 200);
$response->header("Last-Modified",gmdate("D, d M Y H:i:s") . " GMT");
$response->header("Content-type","text/x-csv");
$response->header("Content-Disposition","attachment; filename=".str_replace(" ","_",$databundle['title'])."_".date("Y-m-d_H:i").".csv");
return $response;
It also calls the getData function which is this:
$viewClass = str_replace('/', '', (isset($_POST['view']) ? $_POST['view'] : $_GET['view']));
$fileView = '../app/classes/view.'.$viewClass.'.php';
if(file_exists($fileView))
{
require_once($fileView);
$className = 'view_'.$viewClass;
if(class_exists($className))
{
$view = new $className();
//Seek for parameters
if(isset($_REQUEST['parameters']))
{
//Decode parameters into array
$parameters = json_decode(urldecode((isset($_POST['parameters']) ? $_POST['parameters'] : $_GET['parameters'])),true);
//Get supported parameters
$parameterTypes = $view->getVars();
$vars = array();
foreach($parameterTypes as $key => $type)
{
//If a value is found for a supported parameter in $_GET
if(isset($parameters[$key]))
{
switch($type)
{
case 'int':
$vars[$key] = intval($parameters[$key]);
break;
case 'float':
$vars[$key] = floatval($parameters[$key]);
break;
case 'filterdata':
// todo: date validation
$vars[$key] = $parameters[$key];
break;
}
}
}
$view->setVars($vars);
}
return $view->getData();
}
else {
/*
header('HTTP/1.1 500 Internal Server Error');
echo 'Class ' . $className . ' does not exist.';
*/
return false;
}
}
else {
/*
header('HTTP/1.0 404 Not Found');
die('Cannot locate view (' . $fileView . ').');
*/
return false;
I hope this is sufficient.
In short what i am trying to find out is that the csv that it produces has more columns than columns headers and where the difference comes from
My guess would be that the page you are calling (on the server) is generating the CSV file.
You would need to write code on the server to do the conversion.
This method is making a post request to getView page. Your csv create code would be present on getView page.
This is the front end code that creates an invisible form with your data: current_parameters.
See the content of current_parameters in the the current file.
Review back-end code and look for the "getExport" function (it should be the current php file loaded)
If you just copied this function from some example... you have to add also the back-end code on your own.
Update:
look at the getExport code:
$contents = putcsv($columns, ';', '"');
$contents .= putcsv($vals,';', '"');;
First row insert the titles , and the second loops the data and insert the other rows.
Print the content of $columns and $vals and see what is happening.
There are some strange conditions for filtering the columns... but can help you if you don't show the data you try to parse.