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.
Related
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>
I need help with returning values from jQuery/AJAX to html form inside index.php
index.php :
<script type="text/javascript">
$(document).ready(function () {
$('#display').ready(function () {
var pageid = '<?php echo $_GET[\'ID\'] ;?>';
var powiat = '<?php echo $row[\'powiat\'] ;?>'
$.ajax({ //create an ajax request to display.php
type: 'GET',
url: 'display.php?ID=' + pageid + '&powiat=' + powiat,
dataType: 'html', //expect html to be returned
success: function (response) {
$('#responsecontainer').html(response);
//alert(response);
}
});
});
});
(...)
echo "<form action=\"save.php\" method=\"GET\">";
echo "<tr><td>IP</td><td><div id=\"responsecontainer\"></td></tr>";
echo "<input type=\"submit\" value=\"Save\">" ;
echo "</table></form>
display.php file contains:
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
echo "<option value=\"".$disp_row_1['ip']."\">".$disp_row_1['ip']</option>";
}
In return I have filed html as expected but when I try submit form filed by jquery/ajax I have error
Notice: Undefined index: ip.
How can I handle with that?
Thanks.
Syntax error in your code when you are printing the option.
Updated code is as below.
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
?>
<option value="<?php echo $disp_row_1['ip'];?>" ><?php echo $disp_row_1['ip'];?></option>
<?php }
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
});
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();
I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>  <input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span>   <input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}