CKEditor data truncates when sending through AJAX - javascript

I am using CKEditor version 4 and posting data from editor through ajax call however sometimes all the data post successfully and sometimes it just truncates it. As far I know the reason behind this is when editing the data it adds " " which cause this to truncate. Any help how to completely resolve this issue ?
My code
<script type="text/javascript">
var editor = CKEDITOR.replace('message');
function checkSubmit() {
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances['message'].updateElement();
}
var dataString = "action=<?php echo $_REQUEST['action']; ?>" +
"&id_user=<?php echo $_REQUEST['id_user']; ?>" +
"&sub_id=<?php echo $_REQUEST['subject_id']; ?>" +
"&subject_id=<?php echo $_REQUEST['actual_subject_id']; ?>" +
"&message="+ CKEDITOR.instances['message'].getData()+
"&subject_name="+$("#subject").text() +
"&occurence_name="+$("#occurency").text();
$.ajax({
type: "POST",
url: "data/user-student-data.php",
data: dataString,
success: function(data) {
// close window
parent.closeDistributeModal( 1, "<?php echo $_REQUEST['action']; ?>", <?php echo $_REQUEST['id_user']; ?>,<?php echo $_REQUEST['subject_id']; ?> );
}
});
}
</script>

That is a very difficult way to gather up the data. Try this instead:
var data = {};
data.subject_id = '<?php echo $_REQUEST['actual_subject_id']; ?>';
data.id_user = '<?php echo $_REQUEST['id_user']; ?>';
data.action = '<?php echo $_REQUEST['action']; ?>';
data.sub_id = '<?php echo $_REQUEST['subject_id']; ?>';
data.occurence_name = $("#occurency").text();
data.subject_name = $("#subject").text();
data.message = CKEDITOR.instances['message'].getData();
$.ajax({
type: "POST",
url: "data/user-student-data.php",
data: data,
success: function(returnedData) {
// whatever you had here
}
});
Also
// You can remove the for completely.. THIS:
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances['message'].updateElement();
}
// Is the same as this (you don't use the instanceName variable at all)
CKEDITOR.instances['message'].updateElement();

Related

Making a html alert using ajax, sql and php

I am trying to make some code where a click of a SQL html button can display a different SQL table as a popup. I have already gotten the variable from the table to pass through using this:
echo "<td><a class='btn-floating btn-large waves-effect waves-light black' onclick='partSearch(".$product.")' value='display'><i class='material-icons'>search</i></a></td>";
The 'part search' code is as follows:
<script type="text/javascript">
function partSearch() {
$.ajax({
url: 'serv.php?id=<?php echo $product ?>',
type: 'GET',
success: function(result){
var obj = jQuery.parseJSON(result)
alert(obj)
}
})
}
</script>
Even though the variable is passed through to 'serv.php', I can't manage to get the sql data to be returned as a popup using alert. All I get is either nothing or [object, Object]. This is the SQL/php code:
<?php
include 'includes/dbh.inc.php';
$id = $_GET['id'];
$result = mysqli_query($conn,"SELECT * FROM pr WHERE product_ID='".$id."'");// test this
$rows = array();
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
Any help is appriciated
<script type="text/javascript">
function partSearch() {
var product_id = "<?php echo $product; ?>";
$.ajax({
url: 'serv.php?id=product_id',
type: 'GET',
success: function(result){
alert(result);
}
})
}
</script>

'Unexpected token ;' when trying to pass PHP variable in jQuery AJAX request

So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";

Getting CSRF token in external js file

So I want to enable CSRF protection in my codeigniter app, but this means my js no longer works when its in an external file
function saveToDatabase(editableObj,field,id)
{
var pathArray = window.location.pathname.split( '/' );
var segment_3 = pathArray[3];
var save_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'field':field,
'editedValue':editableObj.innerHTML,
'id':id
};
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
$(editableObj).addClass('bg-success');
}
});
}
I tested by copy pasting it into the view file, and it works perfectly fine.
So the problem is that this line
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
wont work in an external file? Is there any way to get that working?
you can store this value to hidden input or any hidden element and then you can access it in external js file..
<input type ='hidden' name='what_you_want' id='whatever_you_like' value='<?php echo $this->security->get_csrf_token_name(); ?>'>
<input type ='hidden' name='what_you_want1' id='whatever_you_like1' value='<?php echo $this->security->get_csrf_hash(); ?>'>
and you can get it in js like this
var tmp = $('#whatever_you_like').val();
var tmp1 = $('#whatever_you_like1').val();
var save_data = {
tmp: tmp1,
'field':field,
'editedValue':editableObj.innerHTML,
'id':id
};
Define JS constant in header file like
var CSRF_NAME = '<?php echo $this->security->get_csrf_token_name(); ?>'
var CSRF_TOKEN = '<?php echo $this->security->get_csrf_hash(); ?>'
then just call CSRF_NAME or CSRF_TOKEN any where in external or inline JS.

jquery ajax send form.serialize, variable and array all as data

I have below jquery AJAX,
var reply_content = $('#summernote_1').code();
$.ajax({
type:"POST",
url: "<?php echo base_url();?>index.php/test/send_reply/"+<?php echo $testinfo->test_id;?>,
data: $("#test_fm").serialize()+'&file=' + file + '&test_subject=<?php echo $testinfo->testsubject;?>' +'&reply_content=' + reply_content,
});
i have file variable is array contains like below
array([0]=> a [1]=>b),
This was returned with other function which i am passing in AJAX,
How can i pass this in AJAX?
var reply_content = $('#summernote_1').code();
$.ajax({
type:"POST",
url: "<?php echo base_url();?>index.php/test/send_reply/"+<?php echo $testinfo->test_id;?>,
data: {$("#test_fm").serialize()+'&file=' + file + '&test_subject=<?php echo $testinfo->testsubject;?>' +'&reply_content=' + reply_content},
});
and you can use serilizeArray()
If you are trying it in php then you can try like this:
$url = urlencode(serialize($your_array))
append $url in the data
data: {$("#test_fm").serialize()+"&file=<?php echo $url; ?>&test_subject=<?php echo $testinfo->testsubject;?>" +"&reply_content=" + reply_content}
and to restore the variable you can use
$arrVar = unserialize(urldecode($_POST['file']))
You can use serializeArray() to create an object you can add too.
Its also a good idea to separate your php from you js where possible to aid readability:
var url = "<?php echo base_url() . 'index.php/test/send_reply/' . $testinfo->test_id;?>";
var test_subject = "<?php echo $testinfo->testsubject;?>";
var data = $("#test_fm").serializeArray();
data.push(
{
file: file,
test_subject: test_subject
}
);
$.ajax({
type:"POST",
url: url,
data: data
});

passing data from view to controller in cakephp

I have an javascript array variable in my view file , how can i send the array to different controller ?
this is html code:
<button id=<?php echo $key ?> onclick="movebutton(this)" class='li'><?php echo $officers['Officer']['name'] ?> </button>
and this is my javascript code:
function movebutton(elem){
var teamMember=new Array();
if( $(elem).parent().attr("class") == "officers_list" ){
$(elem).detach().appendTo('.add_member');
teamMember.push($(elem));
}
else{
$(elem).detach().appendTo('.officers_list');
teamMember.pop($(elem));
}
You can pass any data to controller using ajax -:
Get values you want to a javascript variable and check a sample ajax
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array(
'controller'=>'controller','action'=>'action'));?>',
data: ({type:variable-value }),
success: function (data){
return true;
// $("#div").html(data);
}
});
To pass data from view to controller:
You can use form but in form your data won't be sent as an array
Using ajax
.
var data = {
val1 = '<?php echo $string ?>';
val2 = '<?php echo $number ?>';
}
$.post( 'controller/action', data , function(response) {
if (response == true) {
// Do this
} else {
// Do that
}
});

Categories

Resources