I have fckeditor working very fine in Mozilla. But it does not save text into database in Chrome Browser. I am sending data from php through $,ajax method. Here is the code in PHP file:
<div class="post_content"> Post Content <?
$sBasePath = $_SERVER['PHP_SELF'] ;
$sBasePath = "fckeditor/";
$oFCKeditor = new FCKeditor('FCKeditor1') ;
$oFCKeditor->Height = '400' ;
$oFCKeditor->BasePath = $sBasePath ;
$oFCKeditor->Value = '';
$oFCKeditor->Create();
?>
</div>
Here is my javascript :
$(document).ready(function(){
$("#add_new_post").submit(function() {
var FCKGetInstance = FCKeditorAPI.GetInstance('FCKeditor1');
var getText = FCKGetInstance.EditorDocument.body.innerHTML;
var StripTag = getText.replace(/(<([^>]+)>)/ig,"");
var dataString = 'FCKeditor1='+ getText;
if(StripTag=='')
{
alert('Please enter Post Content .');
} else {
//alert(dataString);
$.ajax({
type: "POST",
url: "ajax_add_new_blog_post.php",
data: dataString,
cache: false,
success: function(html){
$("body").showMessage({
'thisMessage': [html],
'autoClose': true,
'className': 'tooltip',
'delayTime': 8000,
'displayNavigation': false
});
setTimeout(function() {
window.history.back();
}, 3000);
}
});
}
return false;
});
});
Here is my ajax_add_new_blog_post.php code:
$pagedetail = RTESafe($_REQUEST['FCKeditor1']);
$str="INSERT INTO posts set
post_text='".mysql_real_escape_string($pagedetail)."'";
$success = mysql_query($str);
if($success){
echo 'You have added post successfully!';
}else{
echo 'Adding post was not successful. Try again';
}
function RTESafe($strText) {
$tmpString = trim($strText);
$tmpString = str_replace(chr(145), chr(39), $tmpString);
$tmpString = str_replace(chr(146), chr(39), $tmpString);
$tmpString = str_replace("'", "'", $tmpString);
$tmpString = str_replace(chr(147), chr(34), $tmpString);
$tmpString = str_replace(chr(148), chr(34), $tmpString);
$tmpString = str_replace(chr(10), " ", $tmpString);
$tmpString = str_replace(chr(13), " ", $tmpString);
return $tmpString;
}
My guess would be to use CKeditor instead if possible. FCKeditor is outdated.
Related
I have a code which is works fine, but the data cannot save to the database. I want to insert cost, currency_rate, profit_rate and pprice to database through Ajax. Here are the code of javascript and update.php, I have tried to modify the code to save in my Mysql server, but it didn't success. Can someone help with this?
javascript
$(".profitRate").change(function() {
var myArray = [];
//find closest table->next table
var elem = $(this).closest('table').next('table');
var action = elem.find('tr').data('action');
console.log(action)
var profitRate = Number($("#profitRate").val());
//looping
elem.find('tr').each(function() {
//get cost
var cost = $(this).find('input[name=cost]').val();
//get curency rate
var currecy_rate = $(this).find('select[name=currency_rate]').val();
//calculate profit
var profit_total = Math.round(cost * profitRate * currecy_rate)
$(this).find('input[name=pprice]').val(profit_total)
//add to json object
auto_array = {};
auto_array["cost"] = cost;
auto_array["currecy_rate"] = currecy_rate;
auto_array["pprice"] = profit_total;
myArray.push(auto_array) //push to array
});
console.log(myArray)
form_data = elem.find('tr').data('action');
$.ajax({
data: {
action: action,
form_data: form_data,
},
url: 'update.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
}
}
});
})
update.php
<?php
if ($_POST['action'] == 'update_price') {
parse_str($_POST['form_data'], $my_form_data);
$id = $my_form_data['id'];
$cost = $my_form_data['cost'];
$profit_rate = $my_form_data['profit_rate'];
$currency_rate = $my_form_data['currency_rate'];
$pprice = $my_form_data['pprice'];
$sql = $query = $finalquery = $sqlresult = '';
if ($cost){
$sql.="cost='$cost',";
}
if ($profit_rate){
$sql.="profit_rate='$profit_rate',";
}
if ($currency_rate){
$sql.="currency_rate='$currency_rate',";
}
if ($pprice){
$sql.="pprice='$pprice',";
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
}
I am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});
im try render a html table via ajax with Backbone.js.
The Ajax request works fine, returns the JSON data, but appear the json not match with the model.
Im using, Symfony and Serialize Bundle.
This is my Backbone model and collection:
var Auditoria = Backbone.Model.extend({
defaults:{
id: 'undefined',
user_id: 'undefined',
user_str: 'undefined',
user_agent: 'undefined',
login_from: 'undefined',
login_date: 'undefined'
}
});
var AuditoriaList = Backbone.Collection.extend({
model: Auditoria,
url: $("#ajax-call").val()
});
var sesiones = new AuditoriaList();
sesiones.fetch({
async: false
});
The Ajax response (write on Symfony) do:
public function getSesionesAction(){
$em = $this->getDoctrine()->getManager();
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();
$serializer = $this->get('jms_serializer');
// Prepara la respuesta
$response = new Response();
$response->setContent($serializer->serialize($sesiones_registradas,'json'));
$response->headers->set('Content-Type', 'text/json');
// Retorna la respuesta
return $response;
}
The JSON data returned is:
[{"id":4,"user_id":1046,"user_str":"Meyra, Ariel
Germ\u00e1n","login_date":"2013-11-11
10:24:12","user_agent":"","login_from":""} ... ]
But in the table, print "undefined" in the cells.
Any ideas ?.
UPDATE
Thanks for replies. The HTML view is the next:
<table id="table-session" class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th># Usuario</th>
<th>Usuario</th>
<th>Navegador</th>
<th>Desde</th>
<th>Fecha</th>
</tr>
</thead>
<tbody id="sessions">
</tbody> </table>
And the render Backnone is:
var AuditoriaView = Backbone.View.extend({
tagName: 'tr',
initialize: function(){
// Cada vez que el modelo cambie, vuelve a renderizar
this.listenTo(this.model, 'change', this.render);
},
render: function(){
this.$el.html("<td>" + this.model.get('id') + "</td>" + "<td>" + this.model.get('user_id') + "</td>"
+ "<td>" + this.model.get('user_str') + "</td>" + "<td>" + this.model.get('user_agent') + "</td>"
+ "<td>" + this.model.get('login_from') + "</td>" + "<td>" + this.model.get('login_date') + "</td>"
);
return this;
}
});
// The main view of the application
var App = Backbone.View.extend({
// Base the view on an existing element
el: $('#table-sessions'),
initialize: function(){
this.list = $('#sessions');
this.listenTo(sesiones, 'change', this.render);
sesiones.each(function(sesion){
var view = new AuditoriaView({ model: sesion });
this.list.append(view.render().el);
}, this);
},
render: function(){
return this;
}
});
new App();
I suspect that the problem is that you are trying to print the model's attributes before they are fetched from the server. Try this:
var App = Backbone.View.extend({
// Base the view on an existing element
el: $('#table-sessions'),
initialize: function(){
this.list = $('#sessions');
this.collection = new AuditoriaList
var that = this;
this.collection.fetch({
success: function(collection) {
collection.each(function(sesion) {
var view = new AuditoriaView({ model: sesion });
that.list.append(view.render().el);
});
}
});
this.listenTo(this.collection, 'change', this.render);
},
render: function(){
return this;
}
});
I'm trying to draw an organizational chart (http://goo.gl/wgftfO) from JSON (php - mysql) but it doen'st display well.
Here is my HTML code:
<script type="text/javascript">
google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback(drawChart);
function json(){
$.ajax({
type: "POST",
url: "function/ver.php",
success: function(datos){
datos = eval(datos);
for (var i=0;i<datos.length;i++){
var id = datos[i].id;
var nombre = datos[i].nombre;
var jefe = datos[i].jefe;
alert(id);
drawChart(id, nombre);
function drawChart(id, nombre) {
//alert("Id: " + id + " | Nombre: " + nombre);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
data.addRows([
[nombre, jefe, id]
]);
var chart = new google.visualization.OrgChart(document.getElementById('contenido'));
chart.draw(data, {allowHtml:true});
}
}
},
error: function(error){
alert(error);
}
});
}
</script>
</head>
<body onLoad="json()">
<div id="contenido"></div>
</body>
JSON result:
[
{
"id":"1",
"nombre":"Andrey",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-G1-icon.png",
"jefe":""
},
{
"id":"2",
"nombre":"Enrique",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Andrey"
},
{
"id":"3",
"nombre":"Chero",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-E4-icon.png",
"jefe":"Andrey"
},
{
"id":"4",
"nombre":"Ricardo",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Chero"
},
{
"id":"5",
"nombre":"Jhon",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-H1-icon.png",
"jefe":"Enrique"
}
]
This displays like:
And, if i remove the alert(id) form the HTML code (in ajax), just shows the last object of the JSON:
How can i fix this?
or, is there any other option to do this chart?
Thank your for answers
The bellow code worked for me
index.html
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "ajax/organization.php",
success: function(result){
var result = JSON.parse(result);
if ((emp_count = result.length) > 0) {
console.log(result);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addRows(emp_count);
for (i = 0; i < emp_count; i++) {
data.setCell(i, 0, result[i].emp);
data.setCell(i, 1, result[i].manager);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
}
});
}
</script>
organization.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
$query=mysql_query("select emp, manager from employees") or die(mysql_error());
# Collect the results
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>