I have a single page website, I have the insert working correctly, but I cannot seem to update the #results div after submit. The values are being inserted into the database just fine and if I hard refresh they are appearing. But not with the jQuery AJAX refresh. I am new to Ajax, so any help would be really appreciated, and any comments on code structure or bad habits, please comment as I am trying to learn the proper way to program.
Here is my code:
$(document).ready(function(){
$("form#addTodo").submit(function(){
alert('hello world'); // ensure function is running
var post_title = $('input#post_title').val(); // take values from inputs
var post_content = $('input#post_content').val();
$.ajax({
type: "POST",
url: "add.php",
data: "post_title=" + post_title + "&post_content=" + post_content,
success: function() {
// alert('success'); // ensure success
$('#results').fadeOut('slow').load('include/results.php').fadeIn('slow');
}
});
$('input#post_title').val(''); // clear form fields
$('input#post_content').val('');
return false;
});
});
Here is the results.php file:
<?php
$sql = $db->query('SELECT id, post_title, post_content FROM posts ORDER BY post_title ASC');
$results = $sql->fetchALL(PDO::FETCH_OBJ);
$count_posts = count($results);
?>
<?php if ( have_posts() == true) : ?>
<div class="accordion" id="accordion_main">
<?php foreach($results as $entry): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_main" href="#collapse-<?php echo $entry->id; ?>">
<?php echo $entry->post_title; ?>
</a>
</div>
<div id="collapse-<?php echo $entry->id; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<p class="target"><?php echo $entry->post_content; ?></p>
<p>Edit Delete</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<h3>There are no posts to display at this time.</h3>
<?php endif; ?>
This works fine when it is included by the index.php, I just can't get it to refresh after posting the data to the DB.
<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';
?>
<?php get_header(); ?>
<div id="results">
<?php include_once 'includes/results.php'; ?>
</div>
<hr />
<p>Add New Post</p>
<form id="addTodo" action="">
<div>
<label for="post_title">Post Title</label>
<input id="post_title" name="post_title">
</div>
<div>
<label for="post_content">Post Content</label>
<input id="post_content" name="post_content">
</div>
<div>
<button id="submit" type="submit">
Save
</button>
</div>
</form>
<?php get_footer(); ?>
I should mention that I haven't put in form validation yet. Any help is greatly appreciated, thanks.
Why not just return the data from success? and use that to make your html input
success:function(returnedData) {
if (returnedData.status = 'successful') {
//use javascript to append the data for example like
//returnedData.message to make html and insert into your current html
}
}
Note: returnedData has to be pushed out by your php in an json format.
you can find a similar answer to your request if you read this thread that I had recently answered : Jquery Mobile Post to PHP (same page)
But you must make some adaptation for you context ;-) !!
I think that is the unique solution if you're using unique file script
To insert data returned from php file just use $("element id or class").html() function to insert the data or html to specific area of your document
Related
I am trying to fade out headers of a jQuery accordion that do not contain the search terms I input (hiding/fading the header is enough to make the "pop-up" divs not show using jQuery accordions, as the header cannot be clicked and the divs will never be set to "active") but I am clearly doing something wrong as the dinamically generated headers are not being faded out as I expect to. For example, if I search for a term contained only in the last div being generated, the previous headers and divs will not be faded out. This leads me to think that the problem is clearly in the $this.closest(".infoDiv").next(".header").fadeIn(); especially the "next" part, but as I am very inexperienced with jQuery, I have no idea how to target only the headers of divs not containing my search term. I am sure its something trivial but I cannot figure it out so I would appreciate some help.
This is the form that I use to input my search term.
<div class="search-container">
<form class="form-search">
<input type="text" class="search-query" placeholder="Search in events...">
<button type="submit" class="btn">Search</button>
</form>
</div>
This is the dinamically generated header and div:
<?php if(!empty($results)) {foreach ($results as $row) {?>
<h3 class = "header"><?php echo $row['society_name']; ?> - <?php echo $row['event_name']; ?> - <?php echo $row['event_date']; ?></h3>
<div class = "infoDiv">
<p style ="display:none;"><span class = "data"> <?php echo $row['society_name']; ?> - <?php echo $row['event_name']; ?> - <?php echo $row['event_date']; ?> </span></p>
<p><img src="addressHere"></p>
<p><b>Description:</b><span class = "data"><?php echo $row['description']; ?> </span></p>
<p><b>Schedule:</b><span class = "data"><?php echo $row['schedule']; ?> </span></p>
<p><b>Location:</b><span class = "data"><?php echo $row['location']; ?> </span></p>
<p><b>Frequency:</b><span class = "data"><?php echo $row['frequency']; ?> </span></p>
<p><b>Event Tags:</b><span class = "data"><?php echo $row["GROUP_CONCAT(c.event_tag SEPARATOR ', ')"]; ?> </span></p>
<span style="display:none;" class="eventId"> <?php echo $row['event_id'] ?> </span>
<button class="addToList"> Add to My Events List </button>
</div>
<?php }} ?>
And this is the jQuery script that I wrote:
$('.form-search').on('submit',function(){
return false;
});
$('.form-search .btn').on('click', function(){
var query = $.trim($(this).prevAll('.search-query').val()).toLowerCase();
$('div.infoDiv .data').each(function(){
var $this = $(this);
if($this.text().toLowerCase().indexOf(query) === -1) {
$this.closest(".infoDiv").next(".header").fadeOut();
} else {
$this.closest(".infoDiv").next(".header").fadeIn();
}
});
});
*EDIT: this is an example of what is being generated in the DOM https://imgur.com/a4XXeWF
I am new in Yii framework. I am using Chtml form to send data from view to controller and want to print the result and insert it to database. But in my case its showing an empty array. I couldn't able to understand where I am doing wrong. So please help me regarding this.
in controller
public function actionTest1()
{
$obj = new Pad;
if(isset($_POST))
print_r($_POST);// to check the desired result
if(isset($_POST['Pad']))
{
$obj->attributes=$_POST['Pad'];
if($obj->save()) // insert the data
$this->redirect(array('view','id'=>$obj->id));
}
}
in view
<?php echo CHtml::beginForm('','post',array('id'=>'step1Form')); ?>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'Stop Pad after goal is reached'));
?>
</div>
<div class="currencyText padTop4 floatLeft">Stop Pad after goal is reached</div>
<div class="clearBoth"></div>
</div>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'No limites'));
?>
</div>
<div class="currencyText padTop4 floatLeft">No limites</div>
<div class="clearBoth"></div>
</div>
<div class="nextText">
<?php echo CHtml::link('Next >',array('pad/test1'));?>
</div>
<?php echo CHtml::endForm(); ?>
Please help. Thanks in advance!
You are not submitting your form and of course $_POST will be empty. Line below is just a link:
<?php echo CHtml::link('Next >',array('pad/test1'));?>
You must change it to :
<?php echo CHtml::submitButton('Next >');?>
And also add an action to your form.
Updating the question with the changes I have done. Its redirect me to pad/test1 showing array() as result.
in controller
public function actionTest1()
{
$obj = new Pad;
if(isset($_POST))
CVarDumper::dump($_POST);// to check the desired result
if(isset($_POST['Pad']))
{
$obj->attributes=$_POST['Pad'];
if($obj->save()) // insert the data
echo "=====";
}
}
in view
<?php echo CHtml::beginForm( '','post'); ?>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'Stop Pad after goal is reached'));
?>
</div>
<div class="currencyText padTop4 floatLeft">Stop Pad after goal is reached</div>
<div class="clearBoth"></div>
</div>
<div class="stopPad">
<div class="floatLeft padTop5 marRight5">
<?php
echo CHtml::radioButton('stoppad',false,array('value'=>'No limites'));
?>
</div>
<div class="currencyText padTop4 floatLeft">No limites</div>
<div class="clearBoth"></div>
</div>
<div class="nextText">
<?php echo CHtml::button('Next >', array('submit' => array('pad/test1'))); ?>
</div>
<?php echo CHtml::endForm(); ?>
A common source of confusion among new Yii users is how the 'safe' validator works, how it works with other validators, and why it's necessary in the first place. This article means to clear up this confusion, as well as explain the notion of Massive Assignment.
http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/
I've created a form for a comment box that I'm going to use on a couple of different pages. It sends the data to a table called "comments" in my database that has columns "id" "author" "body" "created" and "page_name". I'm new to php and I'm trying to figure out how to just display the comments that have the same "page_name" value as the current page.
To get the "page_name", I used this code in the form:
<input type="hidden" name="page_name" value="<?=$_SERVER['REQUEST_URI']?>" />
This is the code I'm building to display the comments:
<div id="comments">
<?php foreach($comments as $comment): ?>
<div class="comment" style="margin-bottom: 2em;">
<div class="author">
<b><?php echo htmlentities($comment->author); ?>:</b>
</div>
<div class="meta-info" style="font-size: 0.8em;">
<?php echo datetime_to_text($comment->created); ?>
</div>
<div class="body">
<?php echo strip_tags($comment->body, '<strong><em><p>'); ?>
</div>
</div>
<?php endforeach; ?>
<?php if(empty($comments)) { echo "No Comments."; } ?>
</div>
I'm just not sure how to tell the page to display only the comments that have the same "page_name" value as the page the user is on. Any help would be appreciated!
You have to query the data corresponding to the url like.
For database connection use the code below:
<?php
// Create connection
$db_con=mysql_connect('servername','db username','dbpassword');
if (!$db_con)
{
die('Could not connect: ' . mysql_error());
}
$connection_string=mysql_select_db('db name',$db_con);
?>
For query use the code:
$url=$_SERVER['REQUEST_URI'];
$query=mysql_query("select * from comments where page_name='".$url."'");
while($result=mysql_fetch_row($query))
{
echo $result[0]."<br>".$result[1]."<br>"; // echo all values that are needed for displaying. You can do the coding for displaying formatted values inside this loop.
}
I have this While loop in my php code where I echo rows inside one div that acts like a button and when I press that "button" I want to hide/show the connected div with the jQuery function "toggle". I only get it to work so that when I click any of the "buttons" it opens all divs and not just that one that's connected.
<script>
$(document).ready(function(){
$(".scorec").click(function(){
$(".scorematcho").slideToggle('slow');
});
});
</script>
That's the jQuery I'm using at the moment.
<?php $RM = mysql_query("SELECT * FROM score ORDER BY ScoreID DESC LIMIT 3");
while ($ScoreD = mysql_fetch_assoc($RM)) {
$a = $ScoreD["ScoreOne"]; $b = $ScoreD["ScoreTwo"];?>
<div class="scorec" >
<?php if($a>$b){;?><font color="green"><?php }else{?><font color="red"><?php }?>
<div class="scorel"><img src="flags/<?php echo $ScoreD["FlagOne"]; ?>.png" style="float:left;">
<?php echo $ScoreD["TeamOne"]; ?> | <?php echo $ScoreD["ScoreOne"]; ?></div>
<div class="scorem">-</div>
<div class="scorer"><?php echo $ScoreD["ScoreTwo"]; ?> | <?php echo $ScoreD["TeamTwo"]; ?>
<img src="flags/<?php echo $ScoreD["FlagTwo"]; ?>.png" style="float:right;"></div></font>
</div>
<div class="scorematcho" >
<div class="scorematch">
de_dust2
16-2
</div>
<div class="scorematch">
de_nuke
16-2
</div>
<div class="scorematch">
de_dust
16-2
</div>
</div>
<?PHP } session_destroy()?>
That's the HTML/PHP I'm using. The div "scorec" is the "button" and "scorematcho" is the div I wan't to toggle.The text inside "scorematcho" shall be PHP also, just haven't changed it yet. I have searched and tested some things but can't get anything to work properly, I have noticed that some put all their PHP code inside an "echo", why is that and could that be the problem? Hope that's enough information, please tell if not. Also, if you have some other improvements you think I should make to the code, please tell.
I have added this jfiddle Hope it helps!! http://jsfiddle.net/H77yf/
$(".scorec").click(function(){
$(this).next().slideToggle('slow');
});
I have the following code in .php (code is edited for easier understanding).
while($row = mysql_fetch_array($biznis)){
<div id='listItem'>
<div id='listPic'>
<img src='../../social/images/avatar/empty_avatar_full.jpg'></img>
</div>
<div id='listCont'>
<span>abcde<i>(request pending)</i></span>
</div>
<div id="listInfo">
<span id='info'>More info</span>
</div>
<div style='clear:both;'></div>
<div id='moreInfo'>
<span>Invitation sent: xx-yy-zzzz</span>
</div>
</div>
<div style='clear:both;'></div>
}
So the code is nothing special, I just get all records from the table lined up.
So now, here is the problem, as you can see, I use the same ids for the same elements.
Jquery code
$(document).ready(function () {
$("#moreInfo").hide();
$("#info").click(function(){
$("#moreInfo").slideToggle();
});
});
OK so here are now the problems. Only first div (#moreinfo) is hidden, all the others are shown. And only first span (#info) is toggling the slider.
I tried with putting the counter for ids, and jquery each function, but nothing realy worked as i imagined.
Ty, Sebastian
Element IDs should be unique identifiers for that element. Use classnames for generic selectors:
<? while($row = mysql_fetch_array($biznis)): ?>
<div class="listItem">
<div class="listPic">
<img src="../../social/images/avatar/empty_avatar_full.jpg"></img>
</div>
<div class="listCont">
<span>abcde<i>(request pending)</i></span>
</div>
<div class="listInfo">
<span class="info">More info</span>
</div>
<div style="clear:both;"></div>
<div class="moreInfo">
<span>Invitation sent: xx-yy-zzzz</span>
</div>
</div>
<div style="clear:both;"></div>
<? endwhile; ?>
And change your jQuery to:
$(function() {
$('.moreInfo').hide();
$('.info').click(function() {
$('.moreInfo').slideToggle();
});
});
Edit
$('.info').click(function() {
$(this).parent().siblings('.moreInfo').slideToggle();
});
use class and not ids because you're in a while loop. An id exists only once.
And update your JS.