How to get div value dynamically with jquery and php - 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

Related

how to built ajax tabs in wordpress?

I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.
You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.
can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });

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 can i post data in Codeigniter using Ajax

How can i post data in Codeigniter using Ajax, am so confused this is the first time i do ajax and Codeigniter together
here is my ajax code
i tried to send the data to the controller method ;
This is my ajax
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url: baseURL+"admin/Products/add_product",
type:'post',
data:{productData:postData},
success:function(data){
}
});
});
});
this is my form
<?php $attribute = array( 'id'=>'register_form','form-horizontal'); ?>
<?php echo form_open('admin/products/add_product',$attribute); ?>
<?php echo form_label('product title'); ?>
<?php echo form_input($data_product_title); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product description'); ?>
<?php echo form_textarea($data_product_description); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product price'); ?>
<?php echo form_input($data_product_price); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product quantity'); ?>
<?php echo form_input($data_product_quantity); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_submit($data_3); ?>
<?php echo form_close(); ?>
Hope this will help you :
Your ajax script should be like this : , make sure your URL is correct
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url : baseURL+"admin/Products/add_product",
type:'post',
data: postData,
success:function(data)
{
console.log(data);
}
});
evt.preventDefault();
});
});
In your add_product method get post values like this :
public function add_product()
{
print_r($this->input->post()); // to print all post values
exit;
}
For more : https://www.codeigniter.com/user_guide/libraries/input.html
`$('#add').click(function() {
var form_data = {
subject_name: $('#subject_name').val(),
section: $('#section').val(),
grade: $('#grade').val()enter code here
};
$.ajax({
url:"<?php echo site_url('ViewCourses/SavingData');?>",
type:'POST',
data: form_data,
success: function(msg) {
if (msg == 'Yes')
document.location.reload(true);
else if (msg == 'No')
document.location.reload(true);
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg+'</div>');
}
});
return false;
});`
add Its Button Id Pe Use Of Onclick Function For Submit values With Ajax
form_data All Form Fields Of the Form

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>

Jquery UI sortable, write order into a MySql database

I'm currently using JQuery UI Dragabble, Droppable and sortable. I have two div sections at top and bottom of my php file were i'm dragging and dropping contents from bottom to top div sections.
In top div section i'm performing Sortable JQUery opertions my next requirment is when i perform sorting operation in top section its order should be automatically updated in my MYSQL DB i gotta stuck like how to pass the sorted order to my MySQL db via ajax and php file. Can somebody suggest some help in Achieving it!
Thanks!
Html/PHP code
<div class="drop_list">
<ol id="sortable" style="list-style:decimal;"></ol>
</div>
<div class="sort_list">
<ul id="draggable">
<?php
for($i=1;$i<=5;$i++)
{
?>
<li data-id='article_<?php echo $i;?>' class="draggable_li qitem" >
<div class="main_div">
<div class="secondary_div">
<div class="form_div">
<form>
<input style="width:15px;" type="checkbox" class="hello"/>
</form>
</div>
<label class="item_div">
<span class="item">Item = <?php echo $i; ?></span>
</label>
</div>
<button class="hello btn btn-success add_top">
Add to Top Stories
</button>
<span class="AH_section" style="display:none;float:right;">
<input type="checkbox"/>Home Section
<input type="checkbox"/>App Home Section
</span>
</div>
</li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
JQuery code
$(document).ready(function() {
$("#sortable").sortable({
revert: true,
refreshPositions: true ,
helper : 'clone',
cursor: "move",
delay: 1,
tolerance: 'pointer',
revert: 50
/*stop:function(event,ui){
var data = $(this).sortable('serialize');
}*/
}).serialize();
$("ol li").disableSelection();
$(".sort_list li").draggable({
//containment : "#container",
tolerance:"pointer",
helper : 'clone',
refreshPositions: true ,
revert : 'invalid',
opacity:.4,
});
$(".drop_list ol").droppable({
revert:true,
//hoverClass : 'ui-state-highlight',
greedy: true,
refreshPositions: true,
drop : function(ev, ui)
{
$(ui.draggable).clone().appendTo(this);
if($(this)[0].id === "sortable")
{
console.log($(this).closest("button").find('.hello'));
$(this).find('.hello').hide();
$(this).find('.AH_section').show();
//$(ui.draggable).draggable( 'disable' ); //this will not append dragged list at top of the container
ui.draggable.draggable( 'disable' ).closest('li').prependTo(ui.draggable.closest('ul')); //this will append dragged list at top of the container
return true;
}
}
});
});
change data-id='article_<?php echo $i;?>' to id='<?php echo $i;?>'
add this to your sortable(),
update: function (event, ui) {
var serial=$(this).sortable('serialize');
save_sortable(serial);
}
so here on update, you are calling save_sortable() function, from ajax , update your db in the order returned from sortable()
function save_sortable(serial)
{
$.ajax({
url: "path to your file to update in db.",
type: 'POST',
data: serial,
success: function (data) {
//alert(data);
}
});
}
You can add some id attribute to li, in my case will be get_id.
and then call below function onDropSendSort(); when you want, ie after drop.
<li data-id='article_<?php echo $i;?>' get_id="<?php echo $object_id; ?>" class="draggable_li qitem" >
function onDropSendSort() {
var data = [];
$('#draggable li').each(function() {
var id = $(this).attr('get_id');
data.push(id);
});
// data = [id_1, id_3, id_n];
$.ajax({
url: 'some_url',
type: 'POST',
data: {sort: data},
complete: function(res) {
console.info(res);
}
});
}

Categories