Ajax returned title value for tooltip isn't in one line, in Bootstrap - ajax

I am having a weird bug with dynamic created tooltips using ajax. I am creating a simple notes function. When data is coming from the database everything looks nice
But when i am creating a new note, using ajax i am creating the new entry in the db and then return the value to be shown in the new tooltip...But this is how it comes out to the user.
Is there a way to 'force' it to one line like the 1st image ?
Here is the code in question:
.js part
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
////////
var inText = $('.evnt-input').val(); //Whatever the user typed
$.ajax({
type: 'POST',
url: 'request.php',
data: {action:'addnotes', data: inText},
dataType: 'json',
success: function(s){
if(s.status == 'success'){
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
}
},
error: function(e)
{
console.log('error');
}
});
.php part
if ($_POST["action"] == "addnotes"){
function addnotes($data)
{
$insert = db_query("insert into notes(description) values('$data')");
if($insert)
return db_inserted_id();
}
$data = $_POST['data'];
$status = addnotes($data);
if($status != ''){
$timestamp = strtotime(date('Y-m-d G:i:s'));
$curTime = date( 'F j, Y, g:i a', $timestamp );
$output = array('status'=>'success','id'=>$status, 'curTime'=>$curTime);
}
else
$output = array('status'=>'error');
echo json_encode($output);
}
I have an identical code with the .js part to show the notes when the page loads...of course that works fine.

Lol it was so easy.... I changed the .js part to this, to 'reinitialize' the tooptip:
if(s.status == 'success'){
var curTime = s.curTime;
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
}

Related

How to programatically update dropzone preview filename after using fileRename option

I have a DropZone script (as below) that renames the uploaded image into a unique folder with a unique timestamp to avoid duplicates. When I add the file, it creates the unique directory (session_id) and uploads and renames the image correctly, however, the DropZone preview image still shows the original filename so the remove links do not work. If I refresh the page, the thumbnails are labelled correctly with the new filename and the remove links work. How can I update the script to do this after the initial upload/rename?
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
url: "upload.php",
addRemoveLinks: true,
maxFiles: 5,
acceptedFiles: "image/*",
// Check for previously uploaded images and display in the dropzone
init: function() {
myDropzone = this;
$.ajax({
url: 'upload.php',
type: 'post',
data: {request: 2},
dataType: 'json',
success: function(response) {
$.each(response, function(key,value){
var mockFile = { name: value.name, size: value.size };
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
},
// Rename uploaded files to unique name
renameFile: function (file) {
let newName = new Date().getTime() + '_' + file.name;
return newName;
},
// Remove the uploaded file if the "Remove file" link is pressed
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'post',
url: 'delete.php',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
});
This is the upload.php file:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/inc/config.inc.php';
$upload_folder = "uploads/".session_id();
if(!file_exists($upload_folder)) {
mkdir($upload_folder);
}
$target_dir = $upload_folder."/";
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Upload file
if($request == 1){
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo $target_file;
}else{
echo 0;
}
die;
}
// Read files from
if($request == 2){
$file_list = array();
// Target directory
$dir = $target_dir;
if (is_dir($dir)){
if ($dh = opendir($dir)){
// Read files
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
// File path
$file_path = $target_dir.$file;
// Check its not folder
if(!is_dir($file_path)){
$size = filesize($file_path);
$file_list[] = array('name'=>$file,'size'=>$size,'path'=>$file_path);
}
}
}
closedir($dh);
}
}
echo json_encode($file_list);
exit;
}
?>
This is the delete.php file:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/inc/config.inc.php';
$upload_folder = "uploads/".session_id();
$target_dir = $upload_folder."/";
if(isset($_POST['id'])){
$filename = $_POST['id'];
}
// Delete file
$target_file = $target_dir . $filename;
if (unlink($target_file)) {
echo $target_file;
}else{
echo 0;
}
die;
?>
(NOTE: session_start() is called in the included config file)
Feel free to let me know if there are any other bad ideas in here! :)
Ben
So the answer for this has been solved! For reference the following is the fixes applied.
renameFile: and removedfile: have both been updated as per the comments below.
The changes in the renameFile: section make the newly generated filename available to be referenced later when using the removedfile: Ajax call to delete.php
The init: > success: has been updated changing the mockFile variable.
This ensures that removefile: still works correctly on a page reload (e.g. is there was a form POST and an error needed to be corrected) where the images are now read directly from the folder location.
Full code update:
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
url: "upload.php",
dictDefaultMessage: "", // remove default text
addRemoveLinks: true,
maxFiles: 5,
acceptedFiles: "image/*",
// Check for previously uploaded images and display in the dropzone
init: function() {
myDropzone = this;
$.ajax({
url: 'upload.php',
type: 'post',
data: {request: 2},
dataType: 'json',
success: function(response) {
$.each(response, function(key,value){
var mockFile = {
newName: value.name,
name: value.name.substr(value.name.indexOf('_') + 1),
size: value.size
};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
},
// Rename uploaded files to unique name
renameFile: function (file) {
let newName = new Date().getTime() + '_' + file.name;
// Add new name to the file object:
file.newName = newName;
// As an object is handed over by reference it will persist
return newName;
},
// Remove the uploaded file if the "Remove file" link is pressed
removedfile: function(file) {
// Get new name from file object:
var newName = file.newName;
$.ajax({
type: 'post',
url: 'delete.php',
data: "id="+newName,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
});
Thanks to the user "Sempervivum" on webdeveloper.com for the fix.

ckeditor validation for spaces

How can i implement validation on ckeditor to prevent user from adding spaces only . Any answer within today will be greatly appreciated .
following is what i tried for validations so far :
//Save note from ckeditor
$("input.save_note").click(function()
{
var note_id1 = $(this).attr("rel");
var thiss1 = this;
var profile_user_id = $(this).attr("rel1");
var txt=CKEDITOR.instances.editor1.getData();
var no_space_txt = txt.replace(" ","");
// var txt = txt1.replace(/ +(?= )/g,'');
var editor_val1 = CKEDITOR.instances.editor1.document.getBody().getChild(0).getText() ;
var editor_val = editor_val1.replace(/ +(?= )/g,'');
// if( editor_val == "")
// {
// alert('sak');
// return;
// }
if(editor_val !=="" && editor_val !=="")
{
$(this).attr("disabled","disabled");
var loading_img = addLoadingImage($(this),"before");
jQuery.ajax({
url: "/" + PROJECT_NAME + "profile/save-note-in-editor",
type: "POST",
dataType: "json",
data: { "profile_user_id" : profile_user_id , "note" : txt },
timeout: 50000,
success: function(jsonData) {
if(jsonData){
$("p#clickable_note_"+note_id1).hide();
$(thiss1).hide();
$(thiss1).siblings("input.edit_note").fadeIn();
$("span#"+loading_img).remove();
$(".alert-box").remove();
$(".alert-box1").remove();
$(".alert-box2").remove();
showDefaultMsg( "Note saved successfully.", 1 );
$(thiss1).removeAttr('disabled');
// $(".cke_inner cke_reset").hide();
CKEDITOR.instances.editor1.destroy();
$(".editor1").hide();
$("p#clickable_note_"+note_id1).html(jsonData);//to display the saved note in clickable p tag .
$("p#clickable_note_"+note_id1).fadeIn('slow');// To display the note paragraph again after editing and saving note.
}
else{
$(thiss1).removeAttr('disabled');
$(thiss1).before('<span class="spanmsg" id="note-msg" style="color:red;">Server Error</span>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
else
{
alert("You cannot make an empty note. Please insert some text.");
}
});
I have implement alert to check if no text is entered but i want to check if user only enter spaces . please suggest some accurate way .
Since you are evidently using jQuery, you can add jQuery.trim() as an additional check for your condition:
jQuery.trim(editor_val).length != 0
This will trim all whitespace from the submitted form and check whether there are any characters remaining. If the input consists only of whitespace, the statement will evaluate to false. You would integrate it into the following line:
if (editor_val != "" && editor_val != "" && jQuery.trim(editor_val).length != 0)

How to upload image using ajax and zend?

Thank you for the consideration, I'm sorry for my non-informative question.
Actually I am using ajax and zend for uploading a file.
My ajax code looks like this:
$.ajax({
type: "POST",
url: "/business_general/imagesave",
enctype: 'multipart/form-data',
data: {'file': files.getAsBinary(), 'fname' : file.fileName},
success: function(arrReturn){
alert( "Data Uploaded: ");
}
});
Here, I called a controller action(imagesave) to save my image in database
My Controller file action looks like this:
$config = Zend_Registry::get('config');
$vehiclelogo = $config->paths->vehiclelogo;
$file = $objRequest->getParam('file');
$ret = $objRequest->getParam('fname');
$path_parts = pathinfo($ret);
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
$targetPath = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
try {
echo "POSTED FILE NAME"." ". $ret;
echo "TYPE OF FILE UPLOADED"." "."-". gettype($ret);
$strFilePath = $vehiclelogo.'/'.$targetPath.'.'.$path_parts['extension'];
$OPfile = fopen($strFilePath,"w");
fwrite($OPfile,$file);
fclose($OPfile);
echo "completed";
}
catch (Exception $e) {
echo "error";
}
Here, I am uploading the selected image into a folder.Acually, I am able to upload text files. But if I upload png/jpeg files,it gets uploaded into the folder, But the fact is that it could not be opened.
I should be able to able to upload every type of files.
How to execute this in zend-php and ajax?
Sorry .I think getAsBinary() doesn't support in modern browsers.you can use an invisible canvas for uploding files using ajax.
Example
var canvas = document.getElementById("canvas")
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
var strdata = canvas.toDataURL("image/png");
document.getElementById("company_logo").src=strdata;
$.ajax({
type: "POST",
url: "/business_vehicle/vehiclegeneralsave",
data: "&data="+strdata,
success: function(arrResult) {
//do something
}
});
In controller side you can recive the image ` public function vehiclegeneralsaveAction() {
$file = $arrVehicleDetails = trim($objRequest->getParam('data'));
$strEncodedData = str_replace(' ', '+', $file);
$strFilteredData = explode(',', $strEncodedData);
$strUnencoded = base64_decode($strFilteredData[1]);
file_put_contents('../public/image/image.png', $strUnencoded);
}`

AJAX loop for WordPress (posts from different categories)

I try to implement AJAX posts loop for WordPress from Tuts+
I want this loop to show under comments form in single post page in three columns (each for another category)
In single.php I have divs (numbers comes from category):
<div class="news_posts-6"></div>
<div class="news_posts-3"></div>
<div class="news_posts-2"></div>
My ajaxLoop:
jQuery(function($){
var page = 1;
var loading = true;
var $window = $(window);
var cat = [6,3,2];
var load_posts= jQuery.each(cat, function(){
var $content = $(".news_posts-" + this);
$.ajax({
type : "GET",
data : {numPosts: 2, pageNumber: page, cat: this},
dataType : "html",
url : "http://127.0.0.1:4001/wordpress/wp-content/themes/twentyeleven-child-theme/loopHandler.php",
beforeSend : function(){
if(page != 1){
$content.append('<div id="temp_load" style="text-align:center">\
<img src="/images/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
$content.append($data);
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
});
Part of loopHandler.php:
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;
echo $numPosts;
echo $page;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $cat
));
I tried use simple array containing categories numbers but it doesn't work. Depends on
data : {numPosts: X, pageNumber: page, cat: this},
there is X post displaying in each column (same posts from first category).
I guess I need to use JSON, which I tried, but it was total disaster (I don't know how to put it together). I just need to call AJAX for three different arguments.
Thanks for any help
Well, there are various ways you can go about this.
One way is looping over your categories client side first, and make separate request per category. This is what you are essentially doing in your code. You are iterating over an array of categories and making a request for each.
Another way is to pass that array of categories to your handler. All you need to do is modify your handler to accept an array of integers or categories. Then you can return a JSON object. But this involves a lot more editing and on top of that it does not solve the issue of having different sizes and heights for each section.
Thus, below, I have modified the code a little bit to also keep track of multiple sections. There are just a few small edits we need:
Each section needs to have a category number, pagination number, content section, and a flag whether its loading or not. Each needs to be stored in a single list for tracking.
We need to iterate over each category to initialize it.
We need to iterate over each category on window scroll and check if the next item should be loaded
We need to make sure that each request relates to the requested category
Start by modifying your divs a little (this is just a matter of preference, i prefer storing metadata like this in an attribute instead of a class):
<div class="news_posts" data-category="6"></div>
<div class="news_posts" data-category="3"></div>
<div class="news_posts" data-category="2"></div>
Here's a modified JS (please be aware that I changed up some variable and function names):
jQuery(function($){
var $window = $(window);
var cats = [];
var contentDivs = $(".news_posts");
var initializeCats = function(){
// adds category objects to a list for tracking
for(var i = 0; i < contentDivs.length; i++){
var catNum = $(contentDivs[i]).attr("data-category");
var cat = {
catNum : catNum,
catPage : 1,
loading : true,
catDiv : $(contentDivs[i]);
};
cats.push(cat);
load_post(cat);
}
};
var load_post = function(cat) {
$.ajax({
type : "GET",
data : {
numPosts : 2,
pageNumber : cat.catPage,
cat : cat.catNum
},
dataType : "html",
url : "http://127.0.0.1:4001/wordpress/wp-content/themes/twentyeleven-child-theme/loopHandler.php",
beforeSend : function(){
if(page != 1){
// this was a bad idea when i wrote the article originally
// never concatenate strings on multiple lines by escaping
// the carriage return
// $content.append('<div id="temp_load" style="text-align:center">\
// <img src="/images/ajax-loader.gif" />\
// </div>');
cat.catDiv.append("<div class='temp_load' style='text-align:center'>" +
"<img src='/images/ajax-loader.gif' />" +
"</div>");
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
cat.catDiv.append($data);
$data.fadeIn(500, function(){
cat.catDiv.find(".temp_load").remove();
cat.loading = false;
});
} else {
cat.catDiv.find(".temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
cat.catDiv.find(".temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
var onWindowScroll = function(){
for(var i = 0; i < cats.length; i++){
var cat = cats[i];
var contentDiv = cat.catDiv;
var content_offset = contentDiv.offset();
if( !cat.loading &&
($window.scrollTop() + $window.height()) >
(contentDiv.scrollTop() + contentDiv.outerHeight() + content_offset.top)
) {
cat.loading = true;
cat.catPage++;
load_post(cat);
}
}
}
initializeCats();
$window.scroll(onWindowScroll);
});
The PHP file is pretty much the same, just comment out the echo $numPosts line:
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;
// echo $numPosts;
echo $page;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $cat
));
This is just something quick I whipped up. I HAVE NOT TESTED IT. Try it out, watch out for syntax errors, and cross your fingers :). I hope this will work for you and if it does not, we can look into modifying it so that it does.

Return array from php to ajax success

I want to return an array from a php function to my ajax call. After that I want to use the array values from the page the ajax call is made.
So this is my ajax call:
$(function() {
$("#find").click(function() {
var url = $("#form_url").val();
var dataString = 'url=' + url;
$.ajax({
type: "POST",
url: "/ajax/add_url.php",
data: dataString,
}).done(function( result ) {
myresult(result);
});
return false;
});
});
function myresult(result) {
var result_lines = result.split("<splitter>");
if (result_lines[0] == '1') {
$('#content_error').html(result_lines[1]).fadeIn(250);
$('#content_error').delay(1500).fadeOut(500);
} else if (result_lines[0] == '2') {
$('#content_success').html('Succesfully get images').fadeIn(250);
$('#url_result').delay(500).fadeIn(500);
$('#content_success').delay(1500).fadeOut(500);
alert(eval(data));
}
return true;
}
and this is my php script:
if($_POST['url']) {
$url = $Db->escape($_POST['url']);
$html = file_get_html($url);
$count = 0;
$goodfiles = array();
foreach($html->find('img') as $element) {
$pic = url_to_absolute($url, $element->src);
if(!empty($pic)){
$pics = parse_url($pic);
list($width, $height, $type, $attr) = getimagesize($pic);
if($pics["scheme"]=="http" && $width >= 300 && $height >= 250) {
array_push($goodfiles,$pic);
$_SESSION['pictures'] = $goodfiles;
$count++;
}
}
}
if($count == 0){
$_SESSION['count'] = 'empty';
echo "1<splitter>";
echo "No items found with the correct size";
}else{
$_SESSION['count'] = $count;
echo "2<splitter>";
echo json_encode($_SESSION['pictures']);
}
$_SESSION['url'] = $url;
$html->clear();
$empty = 1;
}
}
when the ajax call is successful I use json_encode on the array to use it on my php page. But I don't know how I get this array to a javascript on the page the ajax call was made of.
right now I'm receiving the following content:
["image.jpeg","image.jpg"]
And I want to put this in a javascript array...
The error is this with this line:
var result_lines = result.split("<splitter>");
result (the AJAX response) is an object or array (depending on the nature of your JSON) but you are trying to call a string method (split()) on it.
This would cause an error in your JS console - always check the console.
Finally, eval() is evil and almost never required except in exceptional circumstances. Try to avoid it.
I don't know how to work with $.ajax but here is an alternative.
Replace this
$.ajax({
type: "POST",
url: "/ajax/add_url.php",
data: dataString,
}).done(function( result ) {
myresult(result);
});
with
$.post("/ajax/add_url.php",{dataString:dataString},function(data){
alert(data['you array index']);
},'json')
I repeat ,this is my alternative so don't take it hard!

Resources