I have a small snippet which is a comment system. I am trying to make it so when I press submit, the form itself will refresh and so will the comments.
I have tried using AJAX but I can't see anything actually initiating when I press "Submit".
My frontpage.php includes each element of the player.
and here is the core for the player_comments.php:
<script>
$(document).ready(function() {
var options = {
url: '',
target: '#comment-text', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
});
</script>
<?
}
if(isset($userId)) {
/* logged in only */
}
$iComments = 0;
$qComments = $db->query("
SELECT songs_comments.*, user.id AS uId, user.username AS uName, user.avatar AS uAvatar
FROM songs_comments LEFT JOIN user ON songs_comments.userid_from = user.id
WHERE songs_comments.songid = '".$rSong->id."' ORDER BY songs_comments.id DESC");
while ($rComments = $qComments->fetch_object()) {
$showComments .= '
<img src="../'.makeAvatar($rComments->uId,$rComments->uAvatar,50).'" class="avatar float-left" alt>
<div class="comment">
<div class="comment-text">'.$rComments->text.'</div>
<div class="comment-footer">
'.$rComments->uName.' on '.dateStamp($rComments->time).'
</div>
<br style="clear:both;">
</div>
';
$iComments++;
} ?>
<div id="player-song-comments-wrap">
<div id="player-song-comments-heading"><img src="template/images/icons/comments.png" alt> Comments</div>
<div id="player-song-comments-sub-heading">
<?=isset($userId)?'Add comment':'Add comment'?>
<span id="song-comments-num"><?=$iComments?></span> comments for "<span id="song-comments-title"><?=$rSong->title?></span>"
by <span id="song-comments-artist"><?=$rSong->artist?></span>
</div>
<hr>
<form id="song-comment-form">
<input type="hidden" value="<?=$rSong->id?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments">
<?=$showComments?>
</div>
</div>
How do I make it so that when I click submit, everything inside this include is reloaded?
here your ajax call code
<script>
$(document).ready(function(){
$("#submit_data").on('click',function(e){
$.ajax({
type:'POST',
url:"player_comments.php",
success:function(data){
console.log(data);
$("#player-song-comments-wrap").html(data)
}
});
});
});
</script>
<form id="song-comment-form">
<input type="hidden" value="<?php echo $rSong->id ?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit" id="submit_data"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments-wrap">
</div>
here your player_comments.php code which call in ajax url
<?php
if(isset($userId)) {
/* logged in only */
}
$iComments = 0;
$qComments = $db->query("
SELECT songs_comments.*, user.id AS uId, user.username AS uName, user.avatar AS uAvatar
FROM songs_comments LEFT JOIN user ON songs_comments.userid_from = user.id
WHERE songs_comments.songid = '".$rSong->id."' ORDER BY songs_comments.id DESC");
while ($rComments = $qComments->fetch_object()) {
$showComments .= '
<img src="../'.makeAvatar($rComments->uId,$rComments->uAvatar,50).'" class="avatar float-left" alt>
<div class="comment">
<div class="comment-text">'.$rComments->text.'</div>
<div class="comment-footer">
'.$rComments->uName.' on '.dateStamp($rComments->time).'
</div>
<br style="clear:both;">
</div>
';
$iComments++;
}
?>
Related
Here is screen shot of my problemI am using codeigniter and ajax.When keyup function is call on search bar then data is shown in suggestion box but when i click on link which is shown on suggestion box then this click is not working.No error of any script file.
Here is code of my view file:
<div class="container-fluid my_searchbar">
<div class="container my_searchbar_container">
<div class="nav nav-justified navbar-search navbar-nav">
<form class="search navbar-search" method="post" action="index.html" >
<div class="input-group">
<input type="text" name="search_area" id="search_area" placeholder="Search Area" class="form-control input-lg">
<div class="input-group-btn">
</div>
<input type="text" name="search_pro" id="search_pro" placeholder="Search Professional Category" class="form-control input-lg">
<ul id="show_search_pro" class="results" >
</ul>
<div class="input-group-btn">
Search
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Here is my ajax code in view file.
$('#search_pro').keyup(function(){
// alert($(this).val());
var location_field = $('#search_area');
var search_cal_field = $(this);
$.ajax({
type: 'POST',
url: 'http://localhost/JustClick/User/search_professional',
cache : false,
dataType : 'html',
data :{location_id:location_field.val(), category_id:search_cal_field.val()},
success:function(data)
{
$('#show_search_pro').html(data);
}
});
});
Here is code of my controller through using ajax i get data on view page:
public function search_professional()
{
if($this->input->is_ajax_request())
{
$professional = $this->UserModel->search_professional($this->input->post('location_id',true),$this->input->post('category_id',true));
foreach ($professional as $row)
{
echo '
<li>
<a class="s_pro" href="'.base_url('Professional/show_professional_detail/'.$row->pro_id).'">'.$row->firstname.' '.$row->lastname.'<br /><span>Description...</span></a></li>';
}
}
else
{
show_404();
}
}
Help me how i solve this problem.
On my website I have a form that allows you to send select a vote and after that the choice of the vote allows you to send (optional) a comment or photo or audio, this button allows you to send everything.
The form of the vote appears after searching for a specific location.
Now I would like to change the functionality, I wish that after clicking on the vote is saved directly right away, and afterwards appear as always the ability to send comments and photos.
This is my form:
<script type="text/javascript">
$(".sinButtonVote > img").click(function(e){
$(this).parents("div.sinWebQuestion").addClass("voteChosen");
$("#sendVoteButton").removeClass("hidden");
$("#sendOpinion").removeClass("hidden");
});
$("div.sinBottomVoteButton").click(function(e){
$("#sendVoteButton").removeClass("hidden");
});
function afterOpinionSent() {
$("#wsCompany").val("Select Location").change();
}
</script>
<form th:action="#{/opinion/vote}"
enctype="multipart/form-data" method="post"
data-successHandler="afterOpinionSent"
class="s_ajaxForm">
<input type="hidden" name="webLocationId" th:value="${webLocation.id}" th:if="${webLocation!=null}"/>
<div th:each="webQuestion : ${webQuestions}" class="row WebQuestion">
<div class="col-sm-6">
<div th:text="${webQuestion.question}" class="sinButtonVoteLabel">Question?</div>
</div>
<div class="col-sm-6">
<label th:each="vote : ${ {3, 2, 1, 0} }" class="radio-inline ButtonVote">
<input type="radio" th:name="|questionVote[${webQuestion.id}]|" th:value="${vote}"/>
<img yada:src="#{|/res/img/question/${webQuestion.iconName+vote}.png|}" th:alt-title="|Voto ${vote}|">
</label>
</div>
</div>
<div style="text-align: center; margin-top: 15px;" id="sendOpinion" class="s_ajaxForm hidden">
<div style="float: left; width: 35%;" class="BottomVoteButton">
<label class="btn btn-default" data-toggle="collapse" data-target="#voteComment">
<img yada:src="#{/res/img/question/comment.png}" title="Comment">
<span>Opinion</span>
</label>
</div>
<div style="float: left; width: 30%;" class="BottomVoteButton">
<label class="btn btn-default btn-file">
<img yada:src="#{/res/img/question/photo.png}" height="35px" title="Photo"><br />
<span>Photo</span>
<input type="file" accept="image/*" capture="camera" class="hidden" name="photo">
</label>
</div>
<div style="overflow: hidden; width: auto;" class="BottomVoteButton">
<label class="btn btn-default btn-file">
<img yada:src="#{/res/img/question/Audio.png}" title="Audio">
<span>Audio</span>
<input type="file" accept="audio/*" capture="microphone" class="hidden" name="audio">
</label>
</div>
<div id="voteComment" class="collapse" th:if="${webLocation!=null}">
<div class="form-group">
<textarea class="form-control" rows="5" maxlength="1024" name="comment" placeholder="Comment..."></textarea>
</div>
</div>
</div>
<button id="sendVoteButton" type="submit" class="s_ajaxForm btn btn-default btn-block hidden">Send</button>
</form>
And this is my opinionController.java:
#RequestMapping("/vote") // Ajax
public String voto(FormOpinioni formOpinioni, HttpServletRequest request, HttpServletResponse response, Model model) {
WebLocation webLocation = null;
if (formOpinioni.getWebLocationId() != null) {
webLocation = webLocationRepository.findOne(formOpinioni.getWebLocationId());
}
if (webLocation==null) {
return "/yada/ajaxError";
}
YadaBrowserId yadaBrowserId = yadaBrowserIdDao.ensureYadaBrowserId(COOKIE_UUIDNAME, COOKIE_EXPIRATIONSEC, request, response);
// Save WebResult
String ipAddress = request.getRemoteAddr();
for (Map.Entry<Long,String> idAndVote : formOpinioni.getQuestionVote().entrySet()) {
long questionId = idAndVote.getKey();
int vote = Integer.parseInt(idAndVote.getValue());
boolean stored = webResultDao.storeResult(questionId, vote, yadaBrowserId, ipAddress);
}
// Save il comment
String commento = formOpinioni.getCommento();
if (!StringUtils.isBlank(comment) && webLocation.isEnabled()) {
boolean stored = webAttachmentDao.storeAttachment(WebAttachment.TYPE_COMMENT, comment, ipAddress, webLocation, yadaBrowserId);
}
// Save photo
saveUpload(WebAttachment.TYPE_IMAGE, formOpinioni.getPhoto(), webLocation, yadaBrowserId, ipAddress, response, model);
// Save audio
saveUpload(WebAttachment.TYPE_AUDIO, formOpinioni.getAudio(), webLocation, yadaBrowserId, ipAddress, response, model);
return thanksForOpinion("Registered opiniono", model);
}
private String thanksForOpinion(String title, Model model) {
return YadaNotify.instance(model)
.yadaOk().yadaAutoclose(2000)
.yadaTitle(title)
.yadaMessage("<p style='text-align:center; min-height:60px;'>Thanks You for opinion</p>")
.yadaSave();
}
How do I change the code?
You have to make following changes
<script th:inline="javascript">
$(".sinButtonVote > img").click(function(e){
$(this).parents("div.sinWebQuestion").addClass("voteChosen");
$("#sendVoteButton").removeClass("hidden");
$("#sendOpinion").removeClass("hidden");
});
$("div.sinBottomVoteButton").click(function(e){
$("#sendVoteButton").removeClass("hidden");
});
function afterOpinionSent() {
$("#wsCompany").val("Select Location").change();
}
$(document).ready(function(){
$("input[#name='YOUR_RADIO_INPUTNAME']").click(function(){
$("#YOUR_FORM_ID").ajaxSubmit({url: '/vote', type: 'post'});
});
});
</script>
Make a Action method which will can process only vote entry .
Note: this is a jQuery coding exercise and I am not allowed to use plugins or other modules.
I have a typical signup form. When the user completes registration and everything is valid I want to fade in a sign in element that the user can use to sign in right away.
Note: I am using the Skeleton framework
HTML:
<div class="container">
<form id="myForm" action="validate_signup.php" method="post">
<div class="row">
<div class="twelve columns">
<h3 class="center">Sign Up</h3>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="email" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="six columns offset-by-four">
<input class="button-primary" type="submit" value="Submit" name="signup">
</div>
</div><!--end row-->
</form>
<div class="row">
<div class="twelve columns">
<p id="response" class="center no-display"></p>
</div>
</div>
</div><!--end container-->
<script src="../js/jquery.js"></script>
<script src="../js/signup.js"></script>
jQuery:
// jQuery form validation
$(document).ready(function(){
// field mapping
var form_fields = {
'email' : 'email',
'pword' : 'password',
'fname' : 'first name',
'lname' : 'last name'
};
// ajax data
var ajaxData = {};
// make sure form fields were entered
$('#myForm').on('submit', function() {
for (var field in form_fields) {
if (!$('#' + field).val()) {
$('#' + field).next().addClass('error_show');
} else if ($('#' + field).val()) {
$('#' + field).next().removeClass('error_show');
ajaxData[field] = $('#' + field).val();
}
}
// 'signup' post field to indicate to php a submission was made
ajaxData['signup'] = 'Submit';
// send data if it is all there
if (Object.keys(ajaxData).length === 5) {
$('#response').hide().empty();
var request = $.ajax({
url : 'validate_signup.php',
method : 'POST',
data : ajaxData,
dataType : 'html'
});
request.done(function(response) {
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}
$('#response').html(response).fadeIn();
$("input[name=email], input[name=pword], input[name=fname], input[name=lname]").val('');
});
request.fail(function() {
alert('Your request could not be processed.');
});
}
return false;
});
});
I am not going to post the php as it is a big piece of code. Just know that if all user data is valid and a successful registration is made PHP outputs, Sign up complete. That is the response.
The main line in question is:
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}
First I tested this condition with console.log('response was Sign up complete) in place of $('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn(); to make sure the condition worked, which it did. But, the fading in of a signin.php link does not work. Instead I am only seeing,
Sign up complete.
change this line
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}
$('#response').html(response).fadeIn();
to
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}else{
$('#response').html(response).fadeIn();
}
Your can also change the div style to see the fadein effect. example:
<div id="response" style="display:none">
Use time parameter to see the real effect.
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn(1000);
My brain is exploding - can't figure out what the issue is with Safari. All browsers work just fine, but Safari simply doesn't read my JavaScript. Not even a simple ol' 'alert()'. Any clues?
============HTML===============
</div>
<div class="container top">
<h1 class="text">Weather Dashboard</h1>
<h3 class="text">Enter the city to get a 3-day forecast</h3>
<form id="cityForm" class="form-group">
<div class="container-fixed">
<div class="form-horizontal">
<div class="input-group inpWid">
<div class="input-group-addon">
<span class="glyphicon glyphicon-home"></span>
</div>
<input type="text" class="form-control" id="city"
name="city" placeholder="Enter the City">
</div>
<button type="submit" class="btn btn-primary btn-success">Weather Me!</button>
</div>
</div>
</form>
<div class="container-fixed" id="weatherBox">
</div>
</div>
============JQuery/JavaScript===============
$("#cityForm").submit(function(e) {
e.preventDefault();
alert("safari");
var url = "scraper.php"; // the script where you handle the form input.
var city1 = $("#city").val();
var city = city1.replace(/\s+/g, '');
$.ajax({
type: "POST",
url: url,
cache:false,
data: {city, city1},
success: function(data){
$("#weatherBox").html(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
============PHP===============
$city = $_POST["city"];
$city1 = $_POST["city1"];
$url="http://www.weather-forecast.com/locations/$city/forecasts/latest";
$content = file_get_contents($url);
preg_match('/3 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day1);
preg_match('/7 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day2);
preg_match('/10 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day3);
for ($i=1; $i<=3; $i++) {
${d.$i} = '<img src="sun.gif" alt="sun" height="42" width="42">';
$wCon = ${day.$i}[1];
preg_match("/dry/i", $wCon, ${weather.$i});
if (${weather.$i}[0]!="dry"){
${d.$i} = '<img src="rain.png" alt="rain" height="42" width="42">';
};
unset(${weather.$i}[0]);
};
============Website===============
http://alexanderii.net/cover/
you have syntax error:-
change data: {city, city1}, to data:{'city':city,'city1':city1}
try this code:-
$.ajax({
type: "POST",
url: url,
cache:false,
data:{'city':city,'city1':city1},
success: function(data){
$("#weatherBox").html(data); // show response from the php script.
}
});
I want to save the edited data into DB and also display in frond-end on clicking save button in the form .. i did the first part but i struggling to show this in frond end with out refreshing the page
<div class="leftbar_menu">
<div class="short_res_header">
<h3 style="margin-top: 10px;">
<span style="float:left;">About</span>
<span style="font-size:small;float: right;"><a data-edit-id="40322" data-clickmode="edit" class="pers" data-id="40322" style="display: inline;">edit</a></span><span style="font-size:small;float: right;"><a class="pers" data-close-id="40322" data-clickmode="close" data-id="40322" style="display: none;">close</a></span> </h3>
</div>
<div class="leftbar_content">
<div data-id="40322" style="display: none;" class="about_toggle formarea">
<script type="text/javascript">
window.onLoad = imageRefreshBig();
$(document).ready(function(){
$('#profileshortresume').attr('maxlength','250');
$("#profileshortresume").css({
"max-width": "350px"
});
});
</script>
<div class="ajaxfiy_edit_profile">
<form enctype="multipart/form-data" method="post" action="http://10.0.1.21/firstplanet/dev/action/profile/edit/" onsubmit="return validateForm()" style="margin-left: 10px;" id="profile_edit_form" class="profile_edit_form_40322" name="profile_edit_form" novalidate="novalidate">
<div style="float:left;width:100%;" id="mypage_about" class=""><dl class="profileshortresume"><dt>About you<font style="color:#FF1800;font-size: 11px;padding-left: 3px;"> *</font><br></dt><dd>
<textarea title="" required="" id="profileshortresume" name="profileshortresume" class="input-textarea" maxlength="250" style="max-width: 350px;">good</textarea></dd></dl></div><input type="hidden" value="90d0e928746b45b9886292d1d0e08d5e" name="__elgg_token"><input type="hidden" value="1396426813" name="__elgg_ts"><input type="hidden" value="40322" name="cat_id"><input type="hidden" value="39242" name="custom_profile_type"><input type="hidden" value="job_1394777243" name="username">
<div class="subt_butt">
<a class="buttonS"><span><input type="button" value="Save" class="edit_save_button" style="text-align:center;"></span></a>
</div>
<br>
</form>
</div>
</div>
<div style="padding-right: 6px; display: block;" class="short_res" data-content-id="40322">
good
</div>
</div>
</div>
// Below script will open the form when edit is clicked
<script type="text/javascript">
$('a.pers').click(function(){
var formid = $(this).attr('data-id');
var clickmode = $(this).attr('data-clickmode');
/*Closing All Open Div */
$('div.short_res').show();
$('div.formarea').hide();
if(clickmode == 'edit') {
$('a[data-clickmode=create]').show();
$('a[data-clickmode=edit]').show();
$('a[data-clickmode=close]').hide();
$('a[data-create-id='+formid+']').show();
$('a[data-close-id='+formid+']').show();
$('a[data-edit-id='+formid+']').hide();
$('div[data-id='+formid+']').show();
$('div[data-content-id='+formid+']').hide();
}
if(clickmode == 'close') {
$('a[data-create-id='+formid+']').show();
$('a[data-edit-id='+formid+']').show();
$('a[data-close-id='+formid+']').hide();
$('div[data-id='+formid+']').hide();
$('div[data-content-id='+formid+']').show();
}
if(clickmode == 'create') {
$('a[data-clickmode=close]').hide();
$('a[data-clickmode=edit]').show();
$('a[data-close-id='+formid+']').show();
$('a[data-create-id='+formid+']').hide();
$('div[data-id='+formid+']').show();
$('div[data-content-id='+formid+']').hide();
}
});
// am using below script for update the data in db and display in front end
$(".edit_save_button").click(function(){
var formid = $(this).parent().parent().parent().parent().attr("class");
var url = $("form."+formid).attr('action');
var data = $("form."+formid).serialize();
$(".thewire_previous_img").show();
var details = $(this).parent().parent().parent().parent().parent().parent().next().attr("class");
$.ajax({
type: "POST",
url: url,
data: data,
context: details ,
success: function(data){
$(".formarea").hide();
$('div.short_res').show();
$('a[data-clickmode=close]').hide();
$('a[data-clickmode=edit]').show();
$(".thewire_previous_img").hide();
}
});
});
That's simple if you not want the page to refresh just not use <form> element and button as <input>,
Just get the elements value with JQuery .val() and get click event of a <button type="button"> element.
When you send a form the navigator automatically always will refresh the page or redirect you to the page that is referenced in the form.