Jquery, ajax and problem with load - php

This is the HTML part:
div id="messages">
<div class="messages">
<?php if(isset ($unread)) { ?>
<p>You have <?php echo $unread?> unread messages.</p>
<?php } ?>
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
<?php } ?>
<?php } ?><!-------- end of if $message-------->
</div><!------ end of div .messages--------->
</div><!------ end of div #messages--------->
and JQ:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>");
});
});
}
});
return false;
});
Code is working, but when it comes to the load nothing is being shown. I did
load("<?php echo site_url('messages/show') ?>", function() {
alert('Load was performed.');
});
and there was an alert, and when I look page source I can see that the content has been changed, but it is not displayed.

When you view the source of a page that has been loaded via AJAX, it will never update. You will need to inspect the DOM in order to see what has changed.
The reason is because the content is not actually on the page and is being dynamically added to the page.

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;
} });}); });

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 get the output using ajax when the Double outputs displayed one for PHP Echo and another for Ajax request?

I successfully fetch the data from the database. The problem is that, I want to display the results using Ajax request. The results/Output which displayed twice, I mean the *first output which displayed through Ajax (#the bottom of index.php), and the Second output displayed through PHP ECHO (**#**the bottom of the page). What can I do to get a single output through Ajax without adding another file and without refreshing the page?
index.php
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="javas.js"></script>
</head>
<body>
<div id="table_content"></div>
<?php
include ("db.php");
error_reporting(~E_NOTICE);
function ShowForm($AnswerCommentId) {
echo '<form id="myForm">';
echo '<input id="user" name="user" />';
echo '<textarea id="text" name="text"></textarea>';
echo sprintf('<input id="ParentId" name="ParentId" type="hidden" value="%s"/>', ($AnswerCommentId));
echo '<button type="button" OnClick=SendComment()>Comment</button>';
echo '</form>';
}
$query="SELECT * FROM `comm` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId'])) $AnswerId = $_REQUEST['AnswerId'];
else $AnswerId = 0;
$i=0;
while ($mytablerow = mysqli_fetch_row($result)){ $mytable[$i] = $mytablerow; $i++; }
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
foreach($treeArray as $item){
if ($item[1] == $pid){
echo sprintf('<div class="CommentWithReplyDiv" style="margin-left:%spx;">',$level*60);
echo sprintf('<p>%s</p>', $item[2]);
echo sprintf('<div>%s</div>', $item[3]);
if ($level<=2) echo sprintf('Reply', $item[0]);
if ($AnswerId == $item[0]) echo sprintf('<div id="InnerDiv">%s</div>', ShowForm($AnswerId));
echo '</div><br/>';
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable,0,0);
?>
Comment
<div id="MainAnswerForm" style="display:none;width:40%; margin:0 auto;"><?php ShowForm(0); ?></div>
<div id="AfterMainAnswerForm"></div>
<script>
$(document).ready(function(){
$("#Link").click(function () {
$("#InnerDiv").remove();
$("#MainAnswerForm").slideToggle("normal");
return false;
});
});
</script>
</body>
Page.php
<?php
include ("db.php");
$user = $_POST['user'];
$text = $_POST['text'];
$ParentId = $_POST['ParentId'];
$action = $_POST['action'];
if ($action=="add") $query= mysqli_query($conn,"INSERT into `comm` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())");
?>
Javas.js
function show_messages(){
$.ajax({
url: "index.php",
cache: false,
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "page.php",
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
show_messages();
}
});
return false;
}
OK I think its more simple than you think
while you're using .html() it should change all the content of your div but while you're using <div id="table_content"></div> then the <?php ?> your code will show both - one appended to the div and under it the one which echoed by php ... so instead of using
<div id="table_content"></div>
<?php ?>
just wrap the <?php ?> inside the div
<div id="table_content">
<?php ?>
</div>
Alternative way: by using jquery wrapAll() but while Id must be unique you'll need to .remove() the #table_content element first then wrap all your code inside a new #table_content div .. see the example below
$(document).ready(function(){
$('#table_content').remove();
$('.CommentWithReplyDiv').wrapAll('<div id="table_content"></div>');
});
#table_content{
margin : 50px;
background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_content"></div>
<div class="CommentWithReplyDiv">1</div>
<div class="CommentWithReplyDiv">2</div>
<div class="CommentWithReplyDiv">3</div>
<div class="CommentWithReplyDiv">4</div>

ajax a href onclick get php variable and execute php file

Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>

Reload Specific <div> of page during ajax call

I got stuck on the following issue. the issue is, I want to reload particular div of my page that also contain PHP script. My javaScript function is
function select_dayoff() {
jQuery('#loader').css('display','block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"+"fschedules/dayoff";
jQuery.ajax({
type: "POST",
url: site,
data: "&fulldate="+MyDayoff.dayof,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
and DIV is:
<span id="fill_available_time">
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile">
<?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?>
</div>
<?php $form->end(null); ?>
</span>
I want to refresh this DIV during above Ajax call.
Thanks in advance for any help.
create a html file xyz.html and add the html code
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile"><?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?></div>
<?php $form->end(null); ?>
function select_dayoff() {
jQuery('#loader').css('display', 'block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"
+ "fschedules/dayoff";
jQuery.ajax( {
type :"POST",
url :site,
data :"&fulldate=" + MyDayoff.dayof,
success : function(msg) {
jQuery('#loader').css('display', 'none');
$('#fill_available_time').load('xyz.html')
}
});
}

Categories