accordion not working after load - php

I just encountered a problem with jquery accordion. What I am doing is loading new content from a php page "jobsload.php". After updating the page with new content, accordion doesnot work. I have tried the destroy property too but in vain.
here is the code
$('#postjob').click(function () {
//Get the data from all the fields
var title = $('#jobtitle');
var date = $('#jobdate');
var status = $('#status');
var desc = $('#jobdesc');
//Simple validation to make sure user entered something
//If error found, add error-highlight class to the text field
if (title.val()=='') {
title.addClass('error-highlight');
return false;
} else title.removeClass('error-highlight');
if (date.val()=='') {
date.addClass('error-highlight');
return false;
}
else date.removeClass('error-highlight');
if (desc.val()=='') {
desc.addClass('error-highlight');
return false;
}
else desc.removeClass('error-highlight');
var data;
if($("#jobid").val()=="")
{
data = 'title=' + title.val() + '&date=' + date.val() + '&status=' + status.val() + '&desc=' + desc.val();
}
else
data = 'id=' + $("#jobid").val() + '&title=' + title.val() + '&date=' + date.val() + '&status=' + status.val() + '&desc=' + desc.val();
//organize the data properly
// Disable fields
//$('.text-label, .textarea-label').attr('disabled','true');
//show the loading sign
$('.loading-contact').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "postjob.php",
//GET method is used
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
//show the success message
$('.loading-contact').fadeOut('slow');
//show the success message
$('.success-message').slideDown('slow');
$('.success-message').delay(1000).slideUp('slow');
$('#jobsload').load("jobsload.php");
// Disable send button
//$('#send').attr('disabled',true);
//if process.php returned 0/false (send mail failed)
} else
{
$('.loading-contact').fadeOut('slow')
alert('Sorry, unexpected error. Please try again later.');
}
}
});
//cancel the submit button default behaviours
$('#accordion').accordion('destroy').accordion({ heightstyle: "content" });
return false;
});
HTML CODE
<div id="jobsload" style="clear:both">
<div class="panel">
<div class="panel-heading"><center>Available Positions</center></div>
<div class="row">
<?php
$sql = "SELECT * FROM jobs where valid='YES'";
$res = mysql_query($sql) or die(mysql_error());
?>
<div class="personalInfo" id="accordion">
<?php while ($row = mysql_fetch_array($res))
{ ?>
<h6 class="media-heading historyHeading">
<span style="width:80%;"><?php echo $row['title'];?></span>
<span style="width:20%;">(<?php echo $row['date'];?>)</span>
</h6>
<div>
<p><?php echo $row['description'];?></p>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="panel">
<div class="panel-heading"><center>Positions Filled</center></div>
<div class="row">
<?php
$sql = "SELECT * FROM jobs where valid='NO'";
$res = mysql_query($sql) or die(mysql_error());
?>
<ul class="personalInfo">
<?php $mycount=1; while ($row = mysql_fetch_array($res))
{ ?>
<li>
<span>
<div style="width:100%; border:thin #666666">
<div style="float:left; width:5%">
<p style="margin-left:10px; margin-top:5px" >
<?php echo $mycount; $mycount++; ?>
</p>
</div>
<div style="float:left; width:85%">
<h6 class="media-heading historyHeading">
<?php echo $row['title'];?>
</h6>
</div>
<div style="float:right; width:10%">
<h6 class="media-heading historyHeading">
<?php echo $row['date'];?>
</h6>
</div>
</div>
</span>
<div class="clearfix"></div>
</li>
<?php } ?>
</ul>
<!-- add this line to add small portfolio -->
</div>
thank you for your help.

If i'm correct the following code loads your new content:
$('#jobsload').load("jobsload.php");
and not the post call.
You need to re-initialize ajaxloaded content, because it's not in the dom, when jquery is initialized.
In the answer Kuma, the accordion is triggered at the same time as the load is being called. Not after the success of the code.
See code beneath to use the success function of the jobsload
$('#jobsload').load("jobsload.php", function( response, status, xhr ) {
if (status == "success") {
// Place reload the accordion code here
}
if ( status == "error" ) {
// optional: place error code here.
// if you don't place this, user will not receive notification of failure.
}
});

You should apply the accordion inside your success function.
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
//show the success message
$('.loading-contact').fadeOut('slow');
//show the success message
$('.success-message').slideDown('slow');
$('.success-message').delay(1000).slideUp('slow');
$('#jobsload').load("jobsload.php");
// Disable send button
//$('#send').attr('disabled',true);
//if process.php returned 0/false (send mail failed)
//cancel the submit button default behaviours
$('#accordion').accordion('destroy').accordion({ heightstyle: "content" });
return false;
} else
{
$('.loading-contact').fadeOut('slow')
alert('Sorry, unexpected error. Please try again later.');
}
}

Related

how can i send and get messages from database using AJAX JQUERY

I'm building a website using PHP and AJAX JQUERY. And inside this website, there is texting system, like whatsapp, telegram ...etc.
and I'm wanna get all the messages from the database after the user send a message, using jQuery AJAX. so far I have been able to send the text to the database successfully but I fail when I try to get the messages.
I Have this following code when first the page is loaded:
<div class="messaging-frame">
<div class="Title-in-message">
<h4 class="title-message"><?php echo $index['Title'] ?></h4>
</div>
<div class="messaging-box" id="messages">
<?php
// THE MESSAGE FROM MESSAGE TABLE
foreach ($messages as $key => $value) {
if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='sent'>
<p id='send-bubble'> <?php
echo $value['Message'] ?> </p>
</div>
</div>
</div>
<?php
} else { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='recived' id="recieved-bubble">
<p id='recived-bubble'><?php echo $value['Message'] ?></p>
</div>
</div>
</div><?php
}
}
?>
</div>\
Than this code in AJAX jQuery get executed when ever the user send a new message in messaging box:
$(document).ready(function() {
$('#sending_text').click(function() {
var report = $('#report_num').val()
var reportInt = parseInt(report);
var text = $('#text_sent').val();
var encodeText = encodeURIComponent(text);
$.ajax({
url: "<?php echo base_url() . 'DisplayTicket/sendNewText' ?> ",
type: "POST",
data: {
text: text,
reportNum: reportInt
},
success: function() {
$('#messages').load("<?php echo base_url() . 'DisplayTicket/getNewMessages' ?>", {reportNum: reportInt}, function() {
var texts = " <?php foreach ($messages as $k => $val) { if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='sent'>";
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>";
texts += "<?php } else { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='recived' id='recieved-bubble'>"
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>"
texts += "<?php }
} ?>";
texts += "</div>";
$('#messages').html(texts);
})
},
});
});
})
Keep in mind that the $('#messages').html(texts);
is actually get executed but the newest messages in not added
I see you are using .load() method to fill the #messages .
Normally the first argument to this method is the response you wanna insert,and the this is just a callback after success, and you are using a php variable $messages instead of using the response from the request.
I see already 2 ways of doing this:
1 - remove the callback from load() and make sure the response is well written in html as youy want
2 - get rid of load() function, and call another ajax inside success of the first ajax to accomplish so.
The second method is just to make you understand what is wrong. So the best way to do it is to fix load() method accordingly

How to make ajax load more content, using button pagination work

I intend to load more videos into a div/page using load more button pagination with ajax, xhr status shows status as ok(200) but no video content is loaded.
videos.php:
<div id="videosline " class="col-md-3 content-grid ">
<?php //code to get first 3 videos working ?>
</div>
<button id="loadvideos" class="btn ">Load More</button>
//ajax jquery code to load in more three videos at every button click
$(document).ready(function(){
var videoscount = 3;
$("#loadvideos").click(function(){
videoscount = videoscount + 3;
$.ajax({
type:"GET",
url:"loadmore.php",
data:{
'videosnewcount':videoscount
},
sucess: function(data){
$('videosline').append(data);
}
});
loadmore.php:
<?php
include 'master.php';//some php config and db config
$videosnewcount = 3;
$condition = [];
array_push($condition,['mediatype = ' => ['video/mp4','AND']]);
$data = find('files',$condition,["ORDER BY " => "id DESC","LIMIT" => $videosnewcount ]); //php function for mysql query
foreach($data as $video) { ?>
<?php if($video['mediatype'] == 'video/mp4') { ?>
<?php include('cards/video.php'); ?>
}
}
?>
cards/video.php:
<?php if(explode('/',$video['mediatype'])[0] == 'video') { ?>
<a href="mediafile.php?id=<?= $video['id']?>&medianame=<?= $video['filename']?>"><div style=" height:;">
<video controlslist="nodownload" oncontextmenu="return false;" poster="member/<?= $video['poster'] ?>" style="height:250px; width:100%; " type="video/mp4" class="pr100" src="member/<?= $video['path'] ?>" > </video</div></a><?php } ?>
I don't know if it matters but in loadmore.php, you are not getting the GET parameter from the Ajax call so I don't know why you are sending it.
What do matters, is that loadmore.php is not echoing any data so your Ajax response should be empty. Also, I can't see that your sending any query to your database. Where is the "SELECT from table WHERE..."?

How to make only two div clickable among multiple divs and send their content to php file

I have this php file which is fetch data from my database and place it into divs. this div created by while loop I want tow div only to be select then send the content to php file using Ajax.
The code execute with no problem but there is no result!!
Any help advance and I completely lost of mind !!!
while($row=mysqli_fetch_array($result)){
$so=$row[0];
$s=$row[1];
$m=$row[2];
$a=$row[3];
$b=$row[5];
$c=$row[8];
?>
<body>
<div id="all"> //start all
<div class="r"> //start r
<div id="e"><?php echo"{$s}"; ?></div>
<div id="b"><?php echo"{$m}"; ?></div>
<div id="a"><?php echo"{$a}"; ?></div>
<div id="b"><?php echo"{$b}"; ?></div>
</div> //end r
</div> //end all
<?php
} //end while
?>
<div id="show"></div>
script code
$(document).ready(function(){
$(".r").click(function(){
$data = $(this).text();
alert($data); //it work well
$.ajax({
url: "view.php",
type: "post",
data: {
you: $data
},
success:function(response){
$('#show').html(response);
}
});
});
});
view.php
<?php
if(isset($_post['you'])){
printf("ok"); //just to check
}
?>
First of all
IDs on a page should be unique
Now coming to your code, maintain a global variable to have select count and call the below function to allow selection of maximum 2 divs
var selectCount = 0;
$('.r div').click(function() {
if(!$(this).hasClass('active') && selectCount < 2) {
$(this).addClass('active');
selectCount++;
}
else if($(this).hasClass('active')) {
$(this).removeClass('active');
selectCount--;
}
else {
alert("ony 2 allowed");
}
});
To send the data to your call you can
$('button').click(function() {
var result = [];
$('.active').each(function(val){
result.push(val);
});
});
You may change the data format accordingly.

Delete function using AJAX in CodeIgniter

PROBLEM SOLVED.. I update my code accordingly.. Thanks all
Intro: My code display array of message traces (each message display in grey-panel). User can delete unwanted message by click on delete button, the message will be deleted in both DB and disappear from screen.
Seems my delete function is not working.. Appreciate for advice.. I don't know AJAX.. this is my first try. Thanks in advance.
The following are my code:
ajax code:
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var $btn = $(this),
$li = $btn.closest('li');
var traceId = $li.data('trace-id');
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
data: { 'traceId': traceId },
success: function (res) {
if (res === '1') {
$btn.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
part of view code:
<ul id="responds">
<?php foreach ($line as $dataName => $contents){ ?>
<li data-trace-id="<?php echo $contents->trace_id; ?>">
<div class="grey-panel" style="text-align:right">
<div class="del_wrapper" id="<?php echo $contents->trace_id; ?>">
<a href="#" class="del_button" id="<?php echo $contents->trace_id; ?>" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id; ?>" >
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php print $contents->trace_hdr.'<br />';
print $contents->trace_src.'<br />';
print $contents->trace_dest.'<br />';
// some other things ?>
</div>
</div>
</li>
<?php } ?>
</ul>
controller code:
public function traceDelete($traceID) {
if ($traceId = $this->input->post('traceId')) {
return $this->model_general->deleteTrace($traceId);
}
return false;
}
model code:
public function deleteTrace($id) {
$this->db->where('trace_id', $id);
$this->db->delete('trace_tbl');
return $this->db->affected_rows() > 1 ? true:false;
}
First, you are using the id attributes wrong. They are meant to be unique as in appear on one element and not multiple as you have done. (As well, id attributes cannot start with a digit.) There's really no need to put it on multiple containing elements as you can easily traverse to the parents or children with jQuery's .find(), .parent(), .closest(), and other traversing methods. However, this should not be the cause of your problem.
Now, what I do think is the cause of your problem is that you are passing the 2nd character of your id attribute into your AJAX request.
$(document).ready(function(){
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
// assign the ID e.g. "abc" to clickedID
var clickedID = this.id;
// problem: assign the second character of your ID i.e. "b" into DbNumberID
var DbNumberID = clickedID[1];
// assign the same value to myData (which is redundant)
var myData = DbNumberID;
$(this).hide();
jQuery.ajax({
type: "POST",
url: 'traceDelete',
dataType:"text",
// sending "myData=b"
data: { myData: myData },
success:function(traceDelete){
alert("Deleted");
$(DbNumberID).fadeOut();
},
error:function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
I am not too familiar with CodeIgniter anymore, but you need to get value from the $_REQUEST or $_POST array or use their built-in function.
$myData = $this->input->post('myData'); // because you are sending myData
EDIT
This is untested but here's how I would do it.
HTML
First, let's use HTML5 data attribute call it data-trace-id. This will be used instead of your numerous improper usages of id attributes.
<ul id="responds">
<?php foreach ($line as $dataName => $contents) : ?>
<li data-trace-id="<?php echo $contents->trace_id ?>">
<div class="grey-panel" style="text-align: right">
<div class="del_wrapper">
<a href="#" class="del_button" data-hover="tooltip" title="Delete this message <?php echo $contents->trace_id ?>">
<i class="fa fa-times"></i>
</a>
</div>
<div class="col-sm-12 col-xs-12">
<?php echo $contents->trace_hdr ?><br />
<?php echo $contents->trace_src ?><br />
<?php echo $contents->trace_dest ?><br />
<!-- etc -->
</div>
</div>
</li>
<?php endforeach ?>
</ul>
JavaScript
Next, let's simplify your JavaScript. I'll use the dreaded alert() for debugging purposes -- but it's usually better to use console.log().
$(function() {
$("#responds").on("click", ".del_button", function (e) {
e.preventDefault();
// keyword 'this' refers to the button that you clicked;
// $(this) make a jQuery object out of the button;
// always good idea to cache elements that you will re-using;
var $li = $(this).closest('li');
// get the associated trace ID from the list-item element;
var traceId = $li.data('trace-id');
alert('trace ID ' + traceId);
// assuming you only want to hide the message only if it has been been successfully deleted from the DB?
// if that is the case, then you have to wait for the AJAX response to tell you whether it was
jQuery.ajax({
type: 'post',
url: 'traceDelete',
dataType: 'text',
// notice how I am using 'traceId'? on the server-side, the data will accessible by using $_POST['traceId'] or $this->input->post('traceId')
data: { 'traceId': traceId },
// look at the response sent to you;
// if I am not mistaken (boolean) true and false get sent back as (strings) 1 or 0, respectively;
// so if the response is 1, then it was successfully deleted
success: function (res) {
alert('AJAX response ' + res);
if (res === '1') {
alert('hiding button');
// hide the message
$li.fadeOut();
}
},
error: function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
PHP
Lastly, we take the value from the $_POST array. Check whether there is a value: if so, delete the item; otherwise ignore it.
public function traceDelete()
{
if ($traceId = $this->input->post('traceId')) {
echo $this->model_general->deleteTrace($traceId) ? '1' : '0';
}
echo '0';
}
remove var DbNumberID = clickedID[1]; var myData = DbNumberID;, as its not needed. Directly assign data: { myData: clickedID },. Also get value of myData in controller via POST.
public function traceDelete() {
$traceID = $this->input->post('myData');
if($traceID)
return $this->model_general->deleteTrace($traceID);
return false;
}

Loading Content using Ajax with PHP Include

I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.

Categories