I am quite new to JS and JQ so I am ask this basic question. I have code like this:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('1500', function() {$(this).remove();
$('#messages').fadeOut('1000');
});
}
});
return false;
});
For now it is working like it should. But I want to add something more. Div with id #messages contains all messages, and I wish that upon deleting message it fadeout(it is working) and then load new data and present all messages again without the deleted one.
Also, there is a counter that counts unread messages, and I created separate page for ajax purpose, but I don't know how to go on from fadeOut.
This is the code from the seperate page:
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
I edited code a bit, but still nothing.
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>").show().fadeIn('1000');
});
});
}
});
return false;
});
When I look page source I can see that the content has been changed, but it is not displayed.
I didn't quite understand what you are trying to do but if this is what you mean by saying but I don't know how to go on from fadeOut you can put a callback function to fadeOut
$('#messages').fadeOut('1000', function () {
// Do something here
);
Related
i am using codigniter .when i am inserting or updating data in mysqldb data is inserting.my form is in popup.then alert is getting but redirecting was not working..issue is redirected is displaying in popup not to page .can you please tell the alternate solution ..i am using ajax update to my form
This is my code of controller
$testid=$this->objTests->updateTest();
echo "<script> alert('sucessfully updated');</script>"
redirect(base_url().'tests');
this is my following code of model:
$testData = array('simulationId' => $this->input- >post('simulationId'),
'testTitle' => $this->input->post('testTitle'),
'description ' => $this->input->post('description')
);
$this->db->where('id',$this->input->post('tid'));
$this->db->update('tests',$testData);
return $this->input->post('tid');
$(function(){
$( "#frmActiontest" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#frmActiontest").serialize(),
type: $(this).attr('method')
}).done(function(data) {
//window.location.href="http://neuronguru.com/MedAdmin/tests/";
window.location.reload();
/*$('#result').html(data);
$('#frmActiontest')[0].reset();*/
});
event.preventDefault();
});
$( ".test" ).on("click",function(event) {
var url = $(this).data('url');
var actionUrl = $(this).data('actionurl');
console.log(actionUrl);
$("#frmActiontest").attr('action',actionUrl);
$.ajax({
url: url,
type: "GET",
dataType: 'json'
}).done(function(data) {
data=data[0];
$("#myModalTestLabel").html("Update Test");
$("#simulationId").val(data.simulationId);
$("#testTitle").val(data.testTitle);
$("#description").val(data.description);
//$("#contents").val(data.contents);
$("#tid").val(data.id);
$("#testModal").trigger("click");
console.log(data);
});
event.preventDefault();
});
});
this is my ajax function for the above question
Im trying to use ajax to sent request. I have CartsController and a method add. Please help!
<?php
echo $this->Html->link('Add', array('controller'=>'carts',
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4',
'data-product-id'=>$product['Product']['id']));
?>
$('a.btn').on('click', function(e){
var this = $(this);
var product_id = this.data('product-id');
this.html('Item Added');
$.ajax({
url: '/cartphp_cart/carts/add/',
type: 'POST',
data: {product_id: product_id},
success: function(count) {
$('#number-of-items').text(' ' + count);
console.log(count);
}
});
e.preventDefault();
});
If the ajax request is OK, than in your add method of CartsController
you can get it by
if ($this->request->is('post') || $this->request->is('put')) {
debug($this->request->data['product_id'])
}
You should be able to access the data you've put in your ajax request by
if( $this->request->is('ajax') ) {
pr($this->request->data['product_id']);
// Or try printing the whole $this->request->data if you need other items.
}
I need to upload image with ajax call. But POST field with image always is empty. Part of my form:
<div class="col-lg-6">
<?php echo CHtml::activeFileField($model, 'logo'); ?>
<?php echo CHtml::textField('test', 'test'); ?>
<?php echo CHtml::submitButton('Upload'); ?>
<?php echo CHtml::ajaxSubmitButton('Upload ajax', '#');?>
</div>
If i click submitButton, then i have both test and logo fields - image uploaded.
And if i click ajaxSubmitButton, then i have only test field, logo is empty. What is the solution?
PS: i need non-extension solution.
You cannot upload files with ajaxSubmitButton by default. Use simple submit or some uploader.
If you want to upload image via ajax, here's example:
<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"js:upload_file(this)"));?>
In your js:
function upload_file(){
var fd = new FormData();
var e = document.getElementById("Model_logo");
fd.append( "Model[logo]", $(e)[0].files[0]);
$.ajax({
url: 'upload',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
alert("ERROR in upload");
}
});
}
Change Model to your model name and this will work. Also now you can append any data to FormData and it will be passed in $_POST and your file in $_FILES.
Be carefull, this way doesn't work on ie7 and ie8 as i remember.
Based on ineersa's answer, I made some improvements:
<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"upload_file()")); ?>
In your js:
function upload_file(){
var fd = new FormData($('#model-form')[0]);
$.ajax({
url: 'upload',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
alert("ERROR in upload");
}
});
}
This way you don't have to append each form field manually. All form data will be read automatically (including files). Just make sure that #model-form is changed according to your form id.
A way you don't need to call $.ajax(...) by yourself.
$(document).on('ajaxBeforeSend', 'form.my-form', function (event, jqXHR, settings) {
if ((settings.url.indexOf("js_skip") == -1) && $("form.my-form input[type=file]")[0].files.length) {
jqXHR.abort();
settings.cache = false;
settings.contentType = false;
settings.processData = false;
settings.data = new FormData(this);
settings.url = settings.url + "&js_skip=1";
jqXHR = $.ajax(settings);
}
});
Trying to use the built in AJAX functions with the Wordpress Admin. I've been following this tutorial, but when I run the jQuery script, the data isn't being saved to the user meta.
<?php
add_action( 'admin_footer', 'ring_jquery' );
function ring_jquery() {
?>
<script type="text/javascript">
jQuery('.ring-submit').on('click', function(){
var u = jQuery(this).attr('user'),
c = jQuery('.agt_ringc[user="'+u+'"]').val(),
x = jQuery('.agt_ringx[user="'+u+'"]').val(),
formData = 'ringu='+u+'&ringc='+c+'&ringx='+x;
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: formData,
success: function(e){
jQuery('.success[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
},
error: function(){
jQuery('.fail[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
}
});
});
</script>
<?php
} //End ring_jquery()
add_action('wp_ajax_my_action', 'ring_callback');
function ring_callback() {
global $wpdb; // this is how you get access to the database
$ringu = $_POST['ringu'];
$ringc = $_POST['ringc'];
$ringx = $_POST['ringx'];
update_user_meta($ringu,'agt_ringc',$ringc);
update_user_meta($ringu,'agt_ringx',$ringx);
die(); // this is required to return a proper result
}
?>
You will need to have action : my_action in the data string , or as per codex :
var data = {
action: 'my_action',
whatever: 1234
};
Issue was, as #ObmerkKronen pointed out was that I was missing an action definition in the data string (which tells the AJAX page which function to run).
formData = 'action=ring_callback&ringu='+u+'&ringc='+c+'&ringx='+x;
I also changed the name of the action hook to match the name of the function. I don't know if this was necessary, but some other things I found did it and I wanted to fit in.
add_action('wp_ajax_ring_callback', 'ring_callback');
I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>
Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.