Codeigniter Smiley Not Showing Up In Preview Area - javascript

I have created a area where user can type in some text and also add smiley into the text area. smiley helper
How ever when I click on my preview button it does not show the generated smiley.
Question how to make sure on the preview are if has any smiles on
question will show up in preview properly. I use preg_replace_callback on my preview function on controller. and also .replace on script Update I found this on user guide but not sure where to add it on code
Generate the smiles here.
<?php
class Question extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->helper('smiley');
}
public function create() {
$this->load->library('table');
$image_array = get_clickable_smileys(base_url('assets/img/smiley'), 'question');
$col_array = $this->table->make_columns($image_array, 8);
$data['smileys'] = $this->table->generate($col_array);
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');
if ($this->form_validation->run() == true) {
}
$data['page'] = 'question/create';
$this->load->view($this->config->item('config_template') . '/template/template_view', $data);
}
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = $new_data;
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
}
Script On View
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
$.ajax({
url: "<?php echo base_url('question/preview');?>",
type: 'POST',
data: {
question: $('#question').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataType: 'json',
success: function(response){
if (response.success) {
$('#preview').html(response.question);
if ($("#preview").find("pre").length > 0){
var html = $('#preview pre').html().replace(/</g, "<").replace(/>/g, ">");
$('#preview pre').html(html);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
} else {
}
}
});
e.preventDefault();
});
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$(document).ready(function(){
$('#bold').click(function() {
wrapText('question', "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("question", "<i>", "</i>");
});
$('#underline').click(function() {
wrapText("question", "<u>", "</u>");
});
$('#pre').click(function() {
wrapText("question", "<pre>", "</pre>");
});
});
</script>

Got it working
I had to use $data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}

Related

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

AJAX Custom error handling Code issue

My Code Igniter PHP page returns json_encode query when page is load with success data. I made a json_encode when no records found. But i dont know how to pass my no record error to jQuery
PHP
if (($query->num_rows() > 0) && ($counter > 0)){
echo(json_encode($query->result()));
$counter = 0;
} else {
//return false;
$response["error"] = 1;
$response["error_msg"] = "NO records found";
echo json_encode($response);
}}
JQuery
$.ajax({
url: <? base_url() ?> +'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) { //working
$.each(retdata, function(i) {
$("#main_div").append('<div>' + retdata[i].name + '<br>' + retdata[i].marks+ '</div>');
});
}
});
controller:
public function controller_function()
{
//$query = your get query code
$response = array(
'result' => array(),
'error_msg' => '',
);
if ($query->num_rows() > 0)
{
$response['result'] = $query->result();
}
else
{
$response['error_msg'] = 'NO records found';
}
echo json_encode($response);
}
Javascript:
$.ajax({
url: <? base_url() ?> +'main/data',
dataType: "JSON",
type: "POST",
success: function (retdata)
{
if (retdata.error_msg)
{
alert(retdata.error_msg);
}
else
{
$.each(retdata.result, function (i)
{
$("#main_div").append('<div>' + retdata.result[i].name + '<br>' + retdata.result[i].marks + '</div>');
});
}
}
})

Ui Autocomplete return all values online but in localhost works

I'm trying about 2 days to fix this I will blow my mind I can't anymore..When I am running it in localhost it's just working fine but when I am trying it online its just returns same values...and all values not returns the search term I can't understand why.
Jquery
$(document).ready(function($){
$('#quick-search-input2').autocomplete({
source:'All/home/directsearch.php',
minLength:2,
autoFocus: true,
select: function(event,ui){
var code = ui.item.id;
if(code != '') {
location.href = 'Movies/' + code;
}
},
html: true,
open: function(event, ui) {
$('ul.ui-autocomplete').slideDown(500)('complete');
$(".ui-autocomplete").css("z-index", 1000);
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("" + item.label + "")
.appendTo(ul);
};
});
PHP
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'search';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
$term = stripslashes($_GET ['term']);
$term = mysql_real_escape_string($_GET ['term']);
$a_json = array();
$a_json_row = array();
include '../../connect.php';
/* ***************************************************************************** */
if ($data = $mysqli->query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5")) {
while($row = mysqli_fetch_array($data)) {
$title = $row['title'];
$year = htmlentities(stripslashes($row['year']));
$type = $row['type'];
$customercode= htmlentities(stripslashes($row['link']));
$category= htmlentities(stripslashes($row['category']));
$synopsis= htmlentities(stripslashes($row['synopsis']));
$img= htmlentities(stripslashes($row['img']));
$id= htmlentities(stripslashes($row['id']));
$category = str_replace(" | ",", ", $category);
$shit = "'";
$ltitle = strtolower($title);
if ($type == "DL-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/HD.png">';
}
else if ($type == "Non-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/NonHD.png">';
}
else if ($type == "CAM")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/CAM.png">';
}
else
{
$qualityresponse = "";
}
$stitle = preg_replace("/[^A-Za-z0-9]/", "", $ltitle);
$a_json_row["id"] = $customercode;
$a_json_row["value"] = ''.$term.'';
$a_json_row["label"] = '
'.$qualityresponse.'<span class="titles">'.$title.'</span><p>'.$year.'</p></center>
';
array_push($a_json, $a_json_row);
}
}
$foundnum = mysql_num_rows(mysql_query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5"));
if ($foundnum == 0)
{
$a_json_row["label"] = '
<li class="ac-no-results ac-item-hover ac-item-selected">No Movies found</li>
';
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
$mysqli->close();
$term = mysql_real_escape_string($_GET ['term']);
to
$term = mysqli->real_escape_string($_GET ['term']);

Ajax function onload

I use this code:
var selected = {
country_id: <?php echo (int)$country_id;?>,
state_id: <?php echo (int)$state_id;?>,
city_id: <?php echo (int)$city_id;?>
},
countryMap = '<?php echo $countryMap;?>',
stateMap = '<?php echo $stateMap;?>',
cityMap = '<?php echo $cityMap;?>';
$("select.event-shipping-country").off().on("change", function() {
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
});
$("select.event-shipping-state").off().on("change", function() {
var $self = $(this);
cityMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'city', 'action' => 'get-cities' ], 'shipping_c_a') ?>',
data: { state: $self.val(), country: $("select.event-shipping-country").val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-city").find("option:gt(0)").remove();
selected.state_id = $self.val();
if(!result.length)
{
return;
}
var html = '';
for(var idx in result)
html += '<option ' + (selected.city_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-city").append(html);
stateMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
},
type: 'POST'
});
stateMap = $self.val() ? $self.text() : '';
});
$("select.event-shipping-city").off().on("change", function() {
selected.city_id = $(this).val();
cityMap = $(this).val() ? $(this).find('option[value="' + $(this).val() + '"]').text() : '';
});
This function select states based on selected country. Problem is that I have only one country with ID 117. But even if I have only one default option selected I must select it again to and only than will show states, but I need that states loads on page loading by selecting country id 117.
Thank you.
$("select.event-shipping-country").off().on("change", function() {
Above line will be called only on change of country.
Call the same function on document.ready() or document.onload also for first time loading and on change will remain same for change on country.
The way to do this is keep the whole code inside separate function and call that function on document.ready() or document.onload and on change of country also
function onCountryChange() {
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
}
$("select.event-shipping-country").off().on("change", onCountryChange );
document.ready(function() {
onCountryChange();
});
Try Like This, Just pass ur code inside a function and call those function at document.ready()
var selected = {
country_id: <?php echo (int)$country_id;?>,
state_id: <?php echo (int)$state_id;?>,
city_id: <?php echo (int)$city_id;?>
},
countryMap = '<?php echo $countryMap;?>',
stateMap = '<?php echo $stateMap;?>',
cityMap = '<?php echo $cityMap;?>';
function onCountryChange(){
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
}
$("select.event-shipping-country").off().on("change", function() {
onCountryChange();
});
function onStateChange(){
var $self = $(this);
cityMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'city', 'action' => 'get-cities' ], 'shipping_c_a') ?>',
data: { state: $self.val(), country: $("select.event-shipping-country").val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-city").find("option:gt(0)").remove();
selected.state_id = $self.val();
if(!result.length)
{
return;
}
var html = '';
for(var idx in result)
html += '<option ' + (selected.city_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-city").append(html);
stateMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
},
type: 'POST'
});
stateMap = $self.val() ? $self.text() : '';
}
$("select.event-shipping-state").off().on("change", function() {
onStateChange();
});
function onCityChange(){
selected.city_id = $(this).val();
cityMap = $(this).val() ? $(this).find('option[value="' + $(this).val() + '"]').text() : '';
}
$("select.event-shipping-city").off().on("change", function() {
onCityChange();
});
$(document).ready(function () {
onCountryChange();
onStateChange();
onCityChange();
});

jquery select2 - Format the results via AJAX php

i use select2, i want to format my results like
name, first.
$("#id").select2({
minimumInputLength : 0,
allowClear: true,
ajax : {
url : "Form/page.php",
dataType : 'json',
data : function (term, page) {
return {
q : term
};
},
results: function (data, page) {
return { results : data.ex};
},
formatResult : function formatResult(ex) {
return '<b>' + ex.name + '</b>';
}
}
});
my php file like
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['text']=$r['name'];
$rows['first']=", ". $r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
how can i do that, thanks
I think the php code has to be like this:
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['name']=$r['name'];
$rows['first']=$r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
So, you pass an array of json objects with an id, name and first.
Change the return of formatResult to:
return '<b>' + ex.name + '</b>, ' + ex.first;
PHP example reposted from the Select2 - source example:
https://github.com/ivaynberg/select2/wiki/PHP-Example
In JS:
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
and in PHP:
<?php
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
?>

Categories

Resources