i have a div that list all the uploaded files
$i = 0;
echo '<div style="float: left;margin-left: 25px;" id="filecontainer">';
echo "<ul>";
foreach($editorderdata['uploadedfiles'] as $row){
echo '<li>';
echo '<a href="'.base_url().'images/userfiles/'.$row['filename'].'" target="_blank">';
echo 'file_'.++$i.'</a>';
echo '<a href="#" data-fileid="'.$row['filename'].'" title="Remove file" class="removefile">';
echo '<img class="cross" src="'.base_url().'images/cross.png">';
echo '</a></li>';
}
echo "</ul>";
echo "</div>";
and this is the code to delete the selected file on pressing the .removefile class element
$(document).ready(function() {
$(".removefile").click(function(e) {
e.preventDefault();
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
$(this).closest("li").remove();
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
return false;
});
});
the code is working fine but what i want is to delete the parent li on ajax success which is not working.. help?
The problem you have is that $(this) in your success handler is not equal to the element which was clicked on. Try this:
$(".removefile").click(function(e) {
e.preventDefault();
var $btn = $(this); // <- save the clicked button to a variable
var fileidvar = $btn.data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data: { fileid: fileidvar },
dataType: 'json',
success: function (data) {
if (data.value) {
alert(data.value);
$btn.closest("li").remove(); // <- use cached selector here
}
},
error: function() {
alert("Something went wrong, please try again.");
}
});
}
return false;
});
Try it like,
if (confirm("Are you sure you want to remove selected file?")) {
var self=this;// make a copy of this to self and use it in ajax function
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
$(self).closest("li").remove();// use self in place of this
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
Try like this.
$(".removefile").click(function(e) {
e.preventDefault();
var this = $(this);
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
this.closest("li").remove();
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
return false;
});
Hope this helps
Problem $(this) is not the element clicked .
so we cache the selector here var this1 = $(this);
$(".removefile").click(function (e) {
var this1 = $(this);
e.preventDefault();
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url: '<?php echo base_url() ?>signup/removefile',
data: {
fileid: fileidvar
},
dataType: 'json',
success: function (data) {
if (data.value) {
alert(data.value);
this1.closest("li").remove();
}
},
error: function () {
alert("Something went wrong, please try again.");
}
});
}
return false;
});
try changing:
$(this).closest("li").remove();
to
$(this).parent().remove();
Related
This is my ajax function
$(function(){
$("#myform").submit(function(){ //i want to get data from my form after submittingit
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
success: function(data){
alert(data);
}
});
return false;
});
});
this is my controller class function
function viewCustomerData(){
if($_POST){
$name = $_POST['name'];
return 'name';
}
else {
return false;
}
}
other thing is i tried to alert data string taken from form serialize, but it also empty. I want to return data set from database after sending key word from javascript file. i tried if the javascript file connect correctly with my controller function. so i tried to return some value and display it using alert box. but it gives empty result.
This is better way to submit a form with ajax
$(document).on("submit", "#myform", function(event)
{
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData"
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
alert(data);
},
error: function (xhr, desc, err)
{
}
});
});
try this
$(function(){
$("#myform").submit(function(){
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
cache: false,
datatype: 'json',
success: function(data){
alert(data.result);
}
});
});
});
in controller
function viewCustomerData(){
if($this->input->post('name'){
$result = $this->input->post('name');
} else {
$result = false;
}
header('Content-Type: application/json');
echo json_encode(array('result' => $result));
}
you cant alert $("#myform").serialize(); because this is an object instead of alert it try console.log($("#myform").serialize();)
then open browser console and see what is printed
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data);
}
});
i am having problems with $_POST["var"] on controller. It seems to be empty. How can i receive the string being typed on my textFiled?
View
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
<script type="text/javascript">
$(document).ready(function(){
$("#hhmm").change(function(){
$.ajax({
url: "<?php echo CController::createUrl('reqTest01Loading'); ?>",
data: $(this).serialize(),
type: "post",
dataType: "json",
success: function(data) {
if (data.status === 'failure') {
$('#impatto').val('Error request failed.');
} else {
$("#impatto").html(data.total);
}
}
});
});
});
</script>
Controller
public function actionReqTest01Loading() {
$result = array("total" => $_POST['hhmm'], "status"=>"OK");
echo CJSON::encode($result);
}
rules on Controller
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('reqTest01Loading','index','view','admin'),
'users'=>array('#'),
),
thanks in advance
This is because you dont tell ajax call to send parameters.
Try:
$.ajax({
url: "<?php echo CController::createUrl('reqTest01Loading'); ?>",
data: {data:$(this).serialize()},
type: "post",
dataType: "json",
success: function(data) {
if (data.status === 'failure') {
$('#impatto').val('Error request failed.');
} else {
$("#impatto").html(data.total);
}
}
});
And it controller:
public function actionReqTest01Loading() {
// var_dump(Yii::app()->request->getPost('data'));
$result = array("total" => Yii::app()->request->getPost('data'), "status"=>"OK");
echo CJSON::encode($result);
}
I have a simple application that calculates the total price of all the rows in a table.
New rows get added like this:
function add() {
[...data removed for readability...]
jQuery.ajax({
type: "POST",
data: {
a:'addadminprice',
id:<? echo $id; ?>,
priceid:el.attr('value'),
price:price
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
var initaddprice = 0;
var row="<tr class='pricedata' rel='"+result.id+"'>";
row+="<td class='drag'>::::</td>";
row+="<td>"+el.text()+"</td>";
row+="<td class='right'>"+price+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+price+"' /></td>";
row+="<td>"+(el.data('percent')=='1'?"%":"")+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+result.qty+"' /></td>";
row+="<td class='right'>"+initaddprice.toFixed(3)+"</td>";
row+="<td><a class='button' href='#' onclick='return removeprice(this,"+result.id+")'>remove</a></td>";
row+="</tr>";
var isfound=false;
$('.pricedata').last().after($(row));
el.remove();
changePrice();
recalcall();
setsort();
saveposition();
}
}
});
As you can see it adds the row - then recalculates the total based all the rows. So far so good, it works fine.
function recalcall() {
console.clear();
console.log('----start calculation----');
var total=0;
$('.pricedata').each(function(){
var price=parseFloat($(this).find('td').eq(6).text());
if (isNaN(price)) price=0;
total+=price;
console.log('+'+price+' = '+total);
});
console.log('----end calculation----');
$('#total').text(total.toFixed(3));
}
When I remove one row, it removes the element and will recalculate the total again. But unfortunately the row is still included in the calculation process? I'm at loss here. Once you remove an element, it should be taken in consideration, right?
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
}
});
}
recalcall();
}
In the removeprice function, move recalcall(); in to the success function
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
recalcall(); // call function here
}
do it like following
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
//have this here
recalcall();
}
});
}
}
I have a link that I want to use with ajax. Here is the link:
<a class="export_csv" href="ajax/createCSV.php?saleid=4"><img src="/img/record.csv.png"></a>
The ajax works fine but I can't pass through the GET variable. Here is the jquery:
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: $(e).data['saleid'],
success: function(results){
console.log('it worked');
}
});
});
Here is the target php page:
<?php
include('./includes/global.php');
//$cl = new Client();
//$cl->createCSV();
echo "This Works ";
$test = $_GET['saleid'];
echo $test;
echo "did work for me";
?>
try like this ,send data to php page using data option
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: "saleid=4",
success: function(results){
console.log('it worked');
}
});
})
or
$('.export_csv').on('click', function(e){
urls=$(this).attr('href');
e.preventDefault();
$.ajax({
url:urls,
type: 'GET',
success: function(results){
console.log('it worked');
}
});
}
You need to pass the data as JSON format like
data:{saleid:$(e).data['saleid']}
But actually dont know what is $(e).data['saleid']
$('#myDomSelectorId').data['saleid'] need to be JSON formated like this :
data : { saleid : $('#myDomSelectorId').data['saleid'] }
Or directly data : "saleid="+$('#myDomSelectorId').data['saleid']
Full example :
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: { saleid : $('#myDomSelectorId').data['saleid'] },
success: function(results){
console.log('it worked');
}
});
});
I need help with my code, how can I get the value bar into the .table (for example . thx
My php file foo.php
<?php
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
?>
My jQuery code
$(function () {
$('button#click').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'foo.php',
data: {data.foo},
dataType : 'json',
success : function (data) { $('.table').html("<p>"+data.foo+"</p>"); }
});
});
});
$(function () {
$('button#click').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'foo.php',
data: {},
dataType: 'json',
success: function (data) {
$('.table').html("<p>" + data.foo + "</p>");
}
});
});
});
You can use it another way
$(function () {
$('button#click').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'foo.php',
data: 'key1=val1&key2=val2',
success: function (data) {
result = eval('(' +data + ')')
$('.table').html("<p>" + result.foo + "</p>");
}
});
});
});
And php file :
<?php
echo json_encode(array('foo' => 'bar'));
?>