Ajax. How to unappend on second click? - php

I have the following ajax script
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass");
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
alert(data);
$(this).closest('.form-group').next('.userInfo').append(data);
}
});
});
})
Its posting data in this html code
<?php if($usuarios[$i]["IdRol"] == '2'){ ?>
<tr>
<td colspan="2">
<!-- -->
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-dnipass="<?= $dni?>" class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
</div>
</div>
<table id ="<?= $i?>" class="table userInfo" data-formpost="<?= $dni?>"></table>
</td>
</tr>
<?php } ?>
How do I make that on second click it deletes the data? , and then on third it posts it again, on fourth deletes.... and so..
EDIT: Progress using ramraider code
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass");
state = $(this).closest('.form-group').next('.userInfo').data("state"); //always picking 0, instead of the new generated 1
console.log(state);
state = 1-parseInt(state);
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
switch( state ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
$(this).closest('.form-group').next('.userInfo').attr("data-state","1");
break;
case 0:
$(this).closest('.form-group').next('.userInfo').remove();
$(this).closest('.form-group').next('.userInfo').attr("data-state","0");
break;
}
}
});
This is how my data-state tag looks on no click
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="0"></table>
And this is how it looks on first click
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="1"></table>
And this is how it looks from second click and all of the next ones
<table id="0" class="table userInfo" data-formpost="12345678B" data-state="1"></table>
It basically stops changing, but im not sure why, seems that state = $(this).closest('.form-group').next('.userInfo').data("state"); start to always pick 0, instead the new generated 1
EDIT 2:
Ramraiders suggested answer works properly, I was missing that the data-state was moved to button

You can set a dataset attribute ( on the button ) that you toggle between 1 and 0 - the value can then be used to fork the logic in your ajax function. For example, set data-state=0 and then toggle it's value in the click handler and test that value in the callback
<button data-dnipass='<?php echo $dni;?>' data-state=0 class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
<!-- note the data-state attribute that will be toggled! -->
$(document).ready(function(){
$( ".ver" ).click( function(event){
event.preventDefault();
event.target.dataset.state = 1 - event.target.dataset.state;
var pulsado = $(this).data("dnipass");
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:pulsado
},
success: (data) => {
switch( parseInt( event.target.dataset.state ) ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
break;
case 0:
/* delete */
break;
}
}
});
});
})
I don't use jQuery so I am not familiar at all with its syntax or intricacies but this appears to do what you want. I have put it together into a working demo - obviously some of the code you see is mickey mouse but should give the idea.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
echo "gigantic mouse strangles elephant";
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>jQuery-toggle append/delete</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(document).ready(function(){
$( ".ver" ).click( function(event){
event.preventDefault();
event.target.dataset.state = 1 - event.target.dataset.state;
var pulsado = $(this).data("dnipass");
$.ajax({
type: 'POST',
url: location.href, //'adminVerLineas.php',
data: {
dni:pulsado
},
success: (data) => {
switch( parseInt( event.target.dataset.state ) ){
case 1:
$(this).closest('.form-group').next('.userInfo').append( data );
break;
case 0:
/* delete */
$(this).closest('.form-group').next('.userInfo').text('');
/* or, slightly better IMO */
// $(this).closest('.form-group').next('.userInfo').html('<tr><td></td></tr>');
break;
}
}
});
});
})
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-state=0 data-dnipass="BANANA APPLE ORANGE STRAWBERRY" class="ver" name="ver" class="btn btn-primary">Ver líneas</button>
</div>
</div>
<table id ="XYZABC123" class="table userInfo" data-formpost="BANANA APPLE ORANGE STRAWBERRY"></table>
</td>
</tr>
</table>
</body>
</html>

Create two click handler such as:
$(".ver-post").click(function(event) {...}
and
$(".ver-delete").click(function(event) {...}
in the success of each replace the class.
success: (data) => {
...
$(this).addClass('ver-delete').removeClass('ver-post');
}
Haven't tested it yet but something like this should work.

Like #urfusion mention it, counter is probably the easiest solution:
$(document).ready(function(){
count_click = 0; // new row counter
$(".ver").click(function(event){
count_click += 1; // new row update counter
var pulsado = $(this).data("dnipass");
alert(pulsado);
event.preventDefault();
var prueba ;
$.ajax({
type: 'POST',
url: 'adminVerLineas.php',
data: {
dni:$(this).data("dnipass"),
},
success: (data) => {
alert(data);
if (count_click % 2 == 0) { // second, fourth, sixth...
// TO DO - delete data
} else { // first, third...
// TO DO - add data
}
$(this).closest('.form-group').next('.userInfo').append(data);
}
});
});
})

Related

I am using laravel5.5 Ajax paging. When I click on page second, It will output data in JSON format

I'm using laravel5.5 Ajax paging. I am the HTML part assembled in the controller. When I clicked on page second, I jumped to this method. How to make the compiled HTML code continue to display on the page?
After clicking on the second page, a string of JSON data is returned. This is a problem. How can we make the data on the second page continue to display in the original page?
PHP
//Screen video, playback volume and key points.
public function accept(Request $ request){
$id=$_GET['id'];
$summer=$_GET['key'];
$name=DB::table('vd_category')->where('address',$summer)->value('name');
if($id=='1'){
$video=DB::table('vd_video_'.$summer)->orderBy('state','desc')->paginate(25);
}else if($id=='2'){
$video=DB::table('vd_video_'.$summer)->orderBy('thumbs','desc')-
>paginate(25);
}
$data='';
foreach($video as $list){
$data.='<div class="col-md-1-5 col-sm-4 col-xs-6" style="padding:0
5px;"><div class="movie-item">';
$data.="<a style='position:relative;display:block;' title='$list-
>video_name' target='_blank' href='details?id=$list->id&key =$summer'>";
$data.="<img alt='$list->video_name' title='$list->video_name'
src=\"uploads/$list->image_address\" height=\"230px\" width='100%'>";
$data.="<button class='bdtag'></button>";
$data.="</a>";
$data.="<div class=\"meta\"><div
style=\"width:100%;overflow:hidden;height:20px;\">";
$data.="<a href='/details?id='$list->id'&key='$summer'
target='_blank' title='$list->video_name' class=\"movie-name\">$list-
>video_name</a>";
$data.="<span class=\"otherinfo\"> 5.0分</span></div><div
class=\"otherinfo\">类型:$name</div></div></div></div>";
}
$datav['1']=$data;
$datav['2']="<div>"."{$video->appends(['id' =>
$id,'key'=>$summer,'name'=>'page'])->links()}"."</div>";
return json_encode($datav);
}
HTML
<div id="data">
#foreach($video as $list)
<div class="col-md-1-5 col-sm-4 col-xs-6" style="padding:0 5px;">
<div class="movie-item">
<a style="position:relative;display:block;" title="{{$list-
>video_name}}" target="_blank" href="/details?id={{$list->id}}&key=
{{$status}}">
<img alt="{{$list->video_name}}" title="{{$list-
>video_name}}" src="{{asset('uploads')}}/{{$list->image_address}}"
height="230"
width="100%">
<button class="bdtag"></button>
</a>
<div class="meta">
<div style="width:100%;overflow:hidden;height:20px;"><a
href="/details?id={{$list->id}}&key={{$status}}" target="_blank" title="
{{$list-
>video_name}}" class="movie-name">{{$list->video_name}}</a><span
class="otherinfo"> 5.0分</span></div>
<div class="otherinfo">类型:{{$namme}}</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
<div id="datav" style="background:#FFF;padding-left:15px;">
{{$video->appends(['id' => $page,'name'=>'page'])->links()}}
</div>
JavaScript
<select name="" required id="where_id" style="float: right;padding-
left:10px;border-left:8px;width: 90px;height: 30px;">
<option value="">Click screening</option>
<option value="1">Sort by play volume</option>
<option value="2">Ranking by points</option>
</select>
<input type="hidden" id="summer" value="{{$status}}">
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
}
});
});
</script>
It has been solved.js has been modified.
That is, the parameters carried by the URL through the Ajax request to the
back-end again, and then the back-end returned JSON data inserted into the
specified location again, probably this is the solution, my English is not
very good, please forgive me.
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#where_id").change(function () {
fun();
});
function fun() {
var id=$("#where_id").val();
var summer=$("#summer").val();
$.ajax({
type:"get",
url:"accept",
dataType:'json',
data:{id:id,key:summer},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
});
}
function pagedata(){
$(".page-item a").click(function (){
var href=this.href;
this.href="javascript:void(0);";
var id=getQueryVariable('page',href);
var key=getQueryVariable('key',href);
var page=getQueryVariable('page',href);
$.ajax({
type: "get",
url: "accept",
dataType: 'json',
data: {id: id, key: key,page:page},
success:function (event){
$("#data").html(event[1]);
$("#datav").html(event[2]);
pagedata();
}
})
})
}
// Intercept the parameter values carried by URL, such as page parameters
//and some custom parameters.
function getQueryVariable(name,url) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var data=url.slice(url.indexOf('?'));
var r =data.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
</script>

how to combine an id div and a php id

I don't know the specifications of PHP and an ID DIV. Here's my question :
Can I put in the same time an ID DIV named #modal and an ID PHP RETURN ?
while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo'
<div class="row print">
<div class="col s12 m4">
<div class="card">
<div class="card-image">
<img data-tags="print" class="activator" src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '">
<i class="material-icons">add</i>
</div>
<div class="card-content">
<span class="card-title">'.$contents_print['nom_projet'].'</span>
<p>'.$contents_print['detail_projet'].'</p>
</div>
</div>
</div>
</div>';
}
This is my jquery ajax code :
$(document).ready(function(){
$('.materialboxed').materialbox();
});
$( document ).ready( function () {
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id=3',
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
}
} );
// the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
$( '.modal' ).modal();
} );
In my ajax code : the line url: 'core/libs/contents-services.php?action=getFilterContent&id=3', I have to use the id from the php/mysql request
I would like to make a link like this :
url: 'core/libs/contents-services.php?action=getFilterContent&id='.$_GET['id'].',
I hope I'am clear
Thanks for your help
http://portfolio.rabahbook.fr to see my working's site
As I understand you get an Id from response and trying to assign it to ajax href. If this is your case, you can do something as below(please note the url_id variable.):
var url_id =3;
$( document ).ready( function () {
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
url_id = response.url_id;/// get url id from response and assign it to
//your href
}
});
// the "href" attribute of the modal trigger must specify the modal ID
//that wants to be triggered
$( '.modal' ).modal();
} );
</script>
$('.post .modal-action').click(function(e){
e.preventDefault();
var id_projet= $(this).data('id_projet');
var $hidennDiv = $('#' +id_projet);
// do your ajax and whatever you want to do with the hidden div
$.ajax( {
url: 'core/libs/contents-services.php?action=getFilterContent&id='+id_projet,
type: "get",
dataType: "html",
success: function ( reponse ) {
$( '#modal' ).html( reponse );
id_projet = reponse.id_projet;
}
} );
$( '.modal' ).modal();
});
This works for me
Thanks all to taking time to anwser to me !

How to create load more data in blog in jQuery AJAX and PHP from database

I need help with a button for loading more data from the database. I've found examples, but too bad ones. Here is what I have so far:
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
});
});
You can follow below technique to load more data with just replacing morebox html.
blog.php
<div class="tutorial_list">
<!-- LOAD YOUR PHP BLOG DATA -->
<div class="loading"><img src="fb-load.gif"/></div>
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
</div>
<script>
$(document).on('click', '.show_more', function() {
{
var ID = $(this).attr("id");
if (ID) {
$('.morebox').hide();
$('.loding').show();
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastpost=" + ID,
cache: false,
success: function(html) {
$('.loading').hide();
$('.tutorial_list').append(html);
$("#show_more" + ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End'); // no results
}
return false;
});
</script>
ajax_more.php
<!-- LOAD YOUR PHP BLOG DATA WITH lastpost ID and remember to add below code for load more -->
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>

Nivo Slider dose not load the Ajax response from PHP file

I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.

How to get div value dynamically with jquery and php

I have to get the value of something when I press an accordion div. This div=" accordion" has this structure:
<div class="accordion">
<? if ($_SESSION[SITE]['user']['id'] == $message['yp_from']) { ?> <div class="row"><span class="bold">From: </span> <span>Me</span>
<span class="grey9"> <?= $this->tools_lib->date_format($message['yp_time']); ?></span>
<? } else { if ($message['yp_state_from'] == 0) {?>
<div class="row"><span class="bold">From: </span><span><?= $this->tools_lib->name_separate($message['yp_name']) ?></span>
<div id="idMens<?= $message['id'] ?>" style="display:none;" class="showNew"><?= $message['id'] ?></div></span>
<h5 id="new"> New </h5>
<?} else { ?>
<div class="row"><span class="bold">From: </span><span><?= $this->tools_lib->name_separate($mensaje['yp_name']) ?></span>
<? }
} ?>
</div>
<p><?= $message['yp_message'] ?><p>
</div>
I want to get · $mensaje['id'] · value from the "div id="idMens"". I was trying to do it with jquery. but I have problems to get the correct value, it always take the first item value, I mean the last dinamically typed.
Im trying to use this jquery code. but I think is not well formed code..
<script>
$(document).ready(function(){
$('.accordion').find('div').click(function(){
$(this).next().slideToggle();
$('.showNew').on('click', function() {
var idm =this.id;
});
var form_data = {
to: $('#',idm).html()
}
$.ajax({
url: _baseurl+""+_lang+"/messages/updateState/", // ruta del controlador y accion
type: 'POST',
data: form_data,
success: function(data){
$('#new').hide();
}
});
}).next().hide();
});
</script>
Thank you!
Finally I did it. I'm fool... it was so easy. I was in the wrong way.
I did it creating other function:
function changeState(id){
var form_data = {
to: id
}
$.ajax({
url: _baseurl+""+_lang+"/messages/updateState/", // ruta del controlador y accion
type: 'POST',
data: form_data,
success: function(data){
$('#new').hide();
}
});
}
And calling it in the first div. with onclick. I pass the dinamic id as a parameter and therefore I can use it well.
Thank you

Categories