Reload a script jquery - javascript

I have a problem
I have a script in my page that do some stuff like deleting a row from a table, add a row
in a table by jquery ajax.
But when I add with ajax a new row/s this row/s don't work.
So there is a method that I can re-load this script every N second ?!?
<script>
.... some stuff ....
setInterval(function() {
#reload script or something like that
},2000);
</script>
For example this function on click open a message...
HTML
<table>
<tr class='MessageList' id='a_1'><td>1</td></tr>
<tr class='MessageList' id='a_2'><td>2</td></tr>
<tr class='MessageList' id='a_3'><td>3</td></tr>
</table>
JS
$('.MessageList').click(function(){
var id=this.id;
if(openMessage)
{
if($('#read-message').attr('message')==$('#'+id).attr('data'))
{
$('#message-list').addClass('hide');
$('#read-message').removeClass('hide');
}
else
{
var readMsg=true;
if($('#'+id).hasClass('not_viewed'))
{
readMsg=false;
jQuery.ajax({
type: "POST",
url: "<?php echo AJAX_RE;?>/nvinbox/",
data: "b=" + $('#'+id).attr('view') + "&a=<?php echo $_SESSION['registrar']['inbox'] ?>",
cache: true,
async: false,
error: function(){
wAlert({ title: "<?php echo $this->languages["PLEASE_TRY_LATER"] ?>",description: "<?php echo $this->languages["SOMETHING_WRONG"] ?>",redirect:'<?php echo USER_REGISTRAR_PAGE?>inbox/'});
},
success: function (response) {
if(response!='No direct script access allowed')
{
var arr = id.split("_");
$('#message_'+arr[1]).addClass('viewed').removeClass('not_viewed');
readMsg=true;
}
else wAlert({ title: "<?php echo $this->languages["PLEASE_TRY_LATER"] ?>",description: "<?php echo $this->languages["SOMETHING_WRONG"] ?>"});
}
});
}
if(readMsg)
{
jQuery.ajax({type: "POST",url: "<?php echo AJAX_RE;?>/upinbox/",dataType : "json",
success: function (response) {
$('#notifMessage').remove();
$('#messageInbox').append(response[0]);
if(response[1]!=0){}
}});
$('#read-message').remove();
jQuery.ajax({
type: "POST",
url: "<?php echo AJAX_RE;?>/vinbox/",
data: "c="+id+"&b=" + $('#'+id).attr('data') + "&a=<?php echo $_SESSION['registrar']['inbox'] ?>",
cache: true,
async: false,
error: function(){
wAlert({ title: "<?php echo $this->languages["PLEASE_TRY_LATER"] ?>",description: "<?php echo $this->languages["SOMETHING_WRONG"] ?>",redirect:'<?php echo USER_REGISTRAR_PAGE?>inbox/'});
},
success: function (response) {
if(response!='No direct script access allowed')
{
var arr = id.split("_");
$('.email-content').append(response);
$('#message-list').addClass("hide");
$('#read-message').removeClass("hide");
}
else wAlert({ title: "<?php echo $this->languages["PLEASE_TRY_LATER"] ?>",description: "<?php echo $this->languages["SOMETHING_WRONG"] ?>"});
}
});
}
}
}
else openMessage=true;
});
When i ADD a new row in the table
<table>
<!-- new row HERE -> <tr class='MessageList' id='a_1456'><td>1456</td></tr>
<tr class='MessageList' id='a_1'><td>1</td></tr>
<tr class='MessageList' id='a_2'><td>2</td></tr>
<tr class='MessageList' id='a_3'><td>3</td></tr>
</table>
If I click new row tr don't work...but the other work fine...

Related

calling function in codeigniter controller using ajax not working

I have a codeigniter website, where I have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, I did the following code in controller:
public function buy($id)
{
$color= $this->input->post('color');
$size=$this->input->post('size');
$product = $this->product->find($id);
$item = array(
'id' => $product->id,
'name' => $product->pname,
'quantity' => 1
);
if(!$this->session->has_userdata('cart')) {
$cart = array($item);
$this->session->set_userdata('cart', serialize($cart));
} else {
$index = $this->exists($id);
$cart = array_values(unserialize($this->session->userdata('cart')));
if($index == -1) {
array_push($cart, $item);
$this->session->set_userdata('cart', serialize($cart));
} else {
// $cart[$index]['quantity']++;
// $this->session->set_userdata('cart', serialize($cart));
$this->session->set_flashdata("Error","Product Already In Cart !");
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->session->set_flashdata("Success","Product Added To Cart Successfully !");
redirect($_SERVER['HTTP_REFERER']);
}
Now I am trying to call this function using ajax so that the product is added to cart without page reload. I did the following code:
$("#change").submit(function() {
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
<form action="" method="post" id="change">
<input type="hidden" value="<?php echo $product->id; ?>" id="prod">
<input type="submit" value="switch">
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
However it's not adding to cart, it simply reloads the page. Can anyone please tell me what is wrong in here?
Because the form is still submitting, you can use preventDefault();
$("#change").submit(function(e) {
e.preventDefault();
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});

Post value fail while checked the checkboxes using ajax

I tried to post values while checked the checkbox using ajax, but it fail, the code seems right to me.. on the url it's appear like this, that it shouldn't..
http://localhost/logsys/admin/roleaccess/%3C?%20$role[%27id%27];%20?%3E
I'm using codeigniter v 3.1.10, running on xampp v 7.3.0
<script>
$('.form-check-input').on('click', function() {
const menuId = $(this).data('menu');
const roleId = $(this).data('role');
$.ajax({
url: "<?= base_url('admin/changeaccess'); ?>",
type: 'post',
data: {
menuId: menuId,
roleId: roleId
},
success: function() {
document.location.href = "<?= base_url('admin/roleaccess/'); ?>" + roleId;
}
});
});
</script>
It should pass the value that allows user get access for some menu
<script>
$('.form-check-input').on('click', function() {
const menuId = $(this).data('menu');
const roleId = $(this).data('role'); // roleId = <? $role[‘id’] ?> so php did not echo role id here
$.ajax({
url: "<?= base_url('admin/changeaccess'); ?>",
type: 'post',
data: {
menuId: menuId,
roleId: roleId
},
success: function() {
document.location.href = "<?= base_url('admin/roleaccess/'); ?>" + roleId;
}
});
});
</script>
For solution change your form-check-input element
<... class=“form-check-input” data-role=“<?php echo $role[‘id’]; ?>” data-menu=“echo menu variable” ...>
If this doesn’t work to share your html of form-check-input button

Inline CKEditor save to MySQL using AJAX/PHP

I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'

Closing ajax popup doesn't work

I have an ajax popup box (pasted below) that works, but I don't know how to close it. I tried adding .dialog('close') to the success line like this - $('#dialog-ajax').html(data).dialog('close');
That didn't work. I also tried replacing that line with the following:
if (data.success) {
App.success(data.success);
$('#dialog-ajax').dialog('close');
}
Again, no go. Thanks for your help.
Here is the html code:
<?php if ($this->details['changeLink'] && !$this->header_part) { ?>
<label class="shipping">{{Tracking number}}:</label>
<input id="tracking" class="fleft small" type="text" value="<?php echo $this->details['purchase']->tracking ?>" />
<button id="change" class="small-button red-button fleft">{{Change}} </button>
<?php } ?>
Here is the javascript:
<script type="text/javascript">
$(document).ready(function() {
if ($.isFunction($.fn.selectbox)) {
$('select').selectbox();
}
<?php if ($this->details['changeLink']) { ?>
$('#change').click(function() {
$.ajax({
url: '<?php echo $this->details['changeLink'] ?>',
type: 'POST',
data: {
id: <?php echo $this->details['purchase']->id ?>,
status: $('#shipping-status').val(),
tracking: $('#tracking').val(),
company: $('#company').val()
},
beforeSend: function() {
loading.loadFancy($('#dialog-ajax'));
},
success: function(data) {
$('#dialog-ajax').html(data);
}
});
return false;
});
<?php if ($this->successfu_edite) { ?>
App.success('{{Purchase is successfully changed!}}');
<?php } ?>
<?php } ?>
});
</script>
well i'm not sure if it may work or not but logically it should
try this
if (data.success) {
/*when the user click outside the pop up*/
$("#dialog-ajax").dialog('destroy').remove();
}
Your ajax call has semantic errors. Add the dataType attribute and change method attribute and your $.ajax call to the following:
<script type="text/javascript">
$(document).ready(function() {
if ($.isFunction($.fn.selectbox)) {
$('select').selectbox();
}
<?php if ($this->details['changeLink']) { ?>
$('#change').click(function() {
$.ajax({
url: '<?php echo $this->details['changeLink'] ?>',
//change method and dataType to reflect the following
method: 'POST',
dataType: 'json',
data: {
id: <?php echo $this->details['purchase']->id ?>,
status: $('#shipping-status').val(),
tracking: $('#tracking').val(),
company: $('#company').val()
},
beforeSend: function() {
loading.loadFancy($('#dialog-ajax'));
},
success: function(data) {
if (data.success) {
$("#dialog-ajax").fadeOut(900,'swing',function(){
$(this).css("display","none");
});
}
}
});
return false;
});
<?php if ($this->successfu_edite) { ?>
App.success('{{Purchase is successfully changed!}}');
<?php } ?>
<?php } ?>
});
</script>

jquery ajax call in codeigniter

i have two function one is for delete and another for update . My delete function is working correctly but when i have written update function that is not working . Also update not working.
Here is the view
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$('table#delTable td button.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/delete');?>",
data:'id='+id,
cache: false,
success: function()
{
parent.fadeOut('slow', function()
{$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
function update(str){
var id=str;
var nm=$('#nm'+str).val();
var em=$('#em'+str).val();
var st=$('#st'+str).val();
var ph=$('#ph'+str).val();
var dp=$('#dp'+str).val();
var un=$('#un'+str).val();
var datas="id="+id+"&nm="+nm+"&em="+em+"&st="+st+"&ph="+ph+"&dp="+dp+"&un="+un;
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/update');?>,
data:datas,
cache: false,
success: function(msg) {
alert(msg);
}
});
}
</script>
<button type="button" class="delete>Delete</button>
<button type="button" onclick="update(<?php echo $row['id']; ?>)">Save</button>
Controller
public function update(){
$id=$_POST['id'];
$userName=$_POST['nm'];
$tokens=explode("",$userName);
$fName=$tokens[0];
$lName=$tokens[1];
$userEmail=$_POST['em'];
$userUni=$_POST['un'];
$userState=$_POST['st'];
$userDept=$_POST['dp'];
$userPh=$_POST['ph'];
$array = array(
'first_name' => $fName,
'last_name' => $lName ,
'email' => $userEmail,
'phone_number' => $userPh,
'varsity_name' => $userUni,
'state' => $userState,
'dept_name'=> $userDept,
);
$this->load->model('Prime_Model');
$result=$this->Prime_Model->updateProfile($id,$array);
if($result){
return "Data has updated";
}
else{
return "Nothing";
}
}
You miss double quote after ?> below:
$.ajax({
type: "POST",
url: "<?php echo base_url('Welcome/update');?>", // here
data: datas,
cache: false,
success: function(msg) {
alert(msg);
}
});

Categories

Resources