Ajax call within a 'for' loop - javascript

Is it possible to using ajax call in a loop?
Here I want, when I single click on button then the ajax call will called 10 times. below is my code. Don't know is it good practice or not.
But I need this type of solution. How can I do it? thank you.
HTML:
<button>Click</button>
AJAX :
$(document).ready(function(e) {
$('button').click(function(){
for(var i=1;i<=10;i++){ //is it possible ?
$.ajax({
type:'POST',
url : "a.php",
data:'a='+$('.div1').text(),
success: function(result){
$('.div1').html(result);
}
});
}
});
});
a.php :
<?php
if(!isset($_POST['a']) || $_POST['a'] == ""){
$a = 0;
}
else{
$a = $_POST['a'] + 1;
}
echo $a;
exit();
?>

try this:
$(document).ready(function(e) {
var ajaxCalled=0;
$('button').click(function(){
$.ajax({
type:'POST',
url : "a.php",
data:'a='+$('.div1').text(),
success: function(result){
$('.div1').html(result);
ajaxCalled++;
if(ajaxCalled<=10){
$('button').trigger('click');
}
else{
ajaxCalled=0;
return false;
}
}
});
});
});

Related

Ajax not getting only json output data (it print whole loaded view code.).? codeigntier

Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)

Getting a post variable inside a function

I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>

use javascript variable in php in jquery function

I want to use javascript variable in php function.. my code is as below
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
alert('<?php echo getYoutubeDurationV3("<script>document.write(video_val);</script>"); ?>');
});
});
I want to use video_val variable in php function.. how can i do that ?
You can use Ajax for this solution. When you place your PHP getYoutubeDurationV3 function in a .php file.
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
$.ajax({
url: 'yourphpscript.php',
data: {duration: video_val},
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
And in your PHP file you can get the value like this:
<?php
$duration = $_POST['video_val'];
//rest of your logic, in your case your function
//return your response back to your webpage.
return $response;
?>
yes, u can do that by ajax post method..
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
$.ajax({
url: 'ajax_file.php',
data: {duration: video_val},
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
And in ajax_file.php write below code..
<?php
$duration = $_POST['video_val'];
return $duration ;
?>

ajax hide load more button on no more data

I have implemented the load more functionality using ajax in yii. This is what I am doing in my script:
$(document).ready(function() {
$(document).on('click', '.discover-more', function() {
$('.discover-more').hide();
$('.loading').show();
var lastId = $('ul#ulscroller li:last').attr('id');
$.ajax({
cache: false,
type: 'POST',
url: '<?php echo $host . $url . '/index.php?r=site/LoadMore&lastid=' ?>' + lastId,
success: function(data) {
$('#ulscroller').append(data);
$('.discover-more').show();
$('.loading').hide();
if (data.length() == 0) {
$('.discover-more').hide();
$('.nomore').show();
}
}
});
});
});
Now, what i have to do is to hide discover more button when there are no more images to show. I have tried a couple of methods in the success call back, like if(data.length() == 0) and if(data.size() < 1) but both do not seem to work? any ideas?
Try this,
if($.trim(data).length == 0)
hope this will work !
.length without (), it is a property and not a method.
if (data == "") {
$('.discover-more').hide();
$('.nomore').show();
}

How to delete a record from database through AJAX using php and also when link is clicked

How to delete a record from database through AJAX using php and also when link is clicked it returns to same page and new list is updated when a link is clicked and id passes through this link ? I am new to AJAX and php
<a class="delete_data" id="<?php echo $row['id']; ?>">Delete</a>
ajax
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // Sucess
} else { // Error }
}
});
});
});
delete.php
$id = $_POST['delete_id'];
$query = "delete from TABLE NAME where ID = $id";
#TOORPIZZZ You can add this to remove the row from the display without refreshing
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
var parent = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { parent.slideUp(300,function() {
parent.remove();
} else { // Error }
}
});
});
});
Make sure you don't have } in a comment by //Error. It took a while until I discovered this.
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
var parent = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { parent.slideUp(300,function() {
parent.remove();
} else { // Error } <----------------
}
});
});
});

Categories

Resources