Closing ajax popup doesn't work - javascript

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>

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);
}
});
});

Why Jquery-ui autocomplete is not working in codeigniter?

I am building a blog application. I have a search box which will suggest the categories as user types. So I use jquery-ui autocomplete. But not sure why its not working. I am new to it and spend a whole day. please help. Here is my code.
Model:
public function getCategoriesJson ($keyword) {
$this->db->select('cat_name');
$this->db->from('categories');
$this->db->like('cat_name', $keyword);
$data = $this->db->get()->result_array();
$output = array();
if ($data) {
foreach ($data as $d) {
array_push($output, $d['cat_name']);
}
}
echo json_encode($output);
}
view:
Controller:
public function getCatJson () {
$this->Category_model->getCategoriesJson($this->input->get('query'));
}
Script:
$('#search').autocomplete({
source: '<?php echo base_url(); ?>categories/getCatJson?query=' + $('#search').val(),
minLength: 1
});
Finally, I have got a solution. I changed my model function code and my script like below and it works.
Model:
public function getCategoriesJson($keyword)
{
$this->db->select('cat_name');
$this->db->from('categories');
$this->db->like('cat_name', $keyword);
$data = $this->db->get()->result_array();
$output = array();
if($data)
{
foreach($data as $d)
{
array_push($output, ['label' => $d['cat_name']]);
}
}
echo json_encode($output);
}
Script:
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: '<?php echo base_url(); ?>categories/getCatJson',
type:'GET',
dataType: "json",
data: {
query: request.term
},
success: function (data) {
response(data);
},
error: function (message) {
response([{'label': 'Not found!'}]);
}
});
},
minLength: 2
});

getting the value of a array from controller to view with ajax in codeigniter

I am creating a status update system where i need to upload a image as well as show it when it uploads all using ajax but when i send the image it goes to the database but i cannot access the image in the ajax return
here is the code
<div class="tab-pane fade" id="tabs-2">
<?php echo form_open_multipart('',["id"=>"formupload","name"=>"formupload"]); ?>
<p class="formUnit"> <i class="active_pic"></i>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<button class="uibutton" type="button" id="upload_pic" style="width: 230px; height: 150px;">Upload Picture</button><span id="status"></span>
<?php echo form_upload(["name"=>"imagefile","id"=>"upload_pic" ]); ?>
<ol class="controls clearfix">
<?php echo form_submit(['name'=>'submit','value'=>'Submit',"class"=>"btn btn-primary"]); ?>
</ol>
</p>
<p id="files"></p>
<?php echo form_close(); ?>
</div>
now ajax
jQuery('#formupload').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/postData_image"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
console.log(data);
$('#output_post').attr('src',data);
},
error: function(data){
//error function
}
});
});
now controller
public function postData_image()
{
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 10000000000000,
'max_width' => 1024000000,
'max_height' => 7680000000,
];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$imagefile="imagefile";
if(!$this->upload->do_upload($imagefile))
{
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/profile',compact('upload_error'));
}
else
{
$post = $this->input->post();
//print_r($post);
unset($post['submit']);
$upload_data = $this->upload->data();
$file_name=$_FILES['imagefile'];
$this->load->model('Pmodel');
$post_data=$this->Pmodel->post_data_image($post,$file_name);
$post['data']=$post_data;
echo $image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
return $post;
}
}
model
public function post_data_image($arr,$arra)
{
$id=$arr['id'];
$image=$arra['name'];
$data=array('image'=>$image);
$query=$this->db->insert('post_status',['user_id'=>$id,'image'=>$image]);
return $query;
}
but how to return the value that is generated after insert in the database using ajax
You want to output your post as json so jquery can interpret it.
echo json_encode($post);
To your ajax function add:
dataType: 'json'
And then data will be an array you can use.
Thanx to #Callombert i got the answer for what i was looking i wanted to return the value and 'echo json_encode('$image_path) or $post would return the value in the json form thus you cacn access it in your view
for someone else looking for an answer just add echo json_encode($image_path);
To your ajax function add:
dataType: 'json'
this would get you working.

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);
}
});

Reload a script jquery

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...

Categories

Resources