Refresh div with jquery in ajax call - javascript

I have a div that has foreach's in them like so:
<div id="conversation">
<?php foreach($singles as $question): ?>
<div class="well well-sm">
<h4><?php echo $question['question_title']; ?></h4>
</div>
<div class="bubble bubble--alt">
<?php echo $question['question_text']; ?>
</div>
<?php endforeach; ?>
<?php foreach($information as $answer): ?>
<div class="bubble">
<?php echo $answer['answer_text']; ?>
</div>
<?php endforeach; ?>
</div>
And I also have a form to put in a new answer:
<form method="post" style="padding-bottom:15px;" id="answerForm">
<input type="hidden" id="user_id" value="<?php echo $_SESSION['user_id']; ?>" name="user_id" />
<input type="hidden" id="question_id" value="<?php echo $_GET['id']; ?>" name="question_id" />
<div class="row">
<div class="col-lg-10">
<textarea class="form-control" name="answer" id="answer" placeholder="<?php if($_SESSION['loggedIn'] != 'true'): ?>You must be logged in to answer a question <?php else: ?>Place your answer here <?php endif; ?>" placeholder="Place your answer here" <?php if($_SESSION['loggedIn'] != 'true'): ?>disabled <?php endif; ?>></textarea>
</div>
<div class="col-lg-2">
<?php if($_SESSION['loggedIn'] != 'true'): ?>
<?php else: ?>
<input type="submit" value="Send" id="newAnswer" class="btn btn-primary btn-block" style="height:58px;" />
<?php endif; ?>
</div>
</div>
</form>
I am submitting the form via ajax and would like the div #conversation to refresh and reload the for each every time the user submits an answer to the question. Right now I have the following ajax code:
<script type="text/javascript">
$("#newAnswer").click(function() {
var answer = $("#answer").val();
if(answer == ''){
$.growl({ title: "Success!", message: "You must enter an answer before sending!" });
return false;
}
var user_id = $("input#user_id").val();
var question_id = $("input#question_id").val();
var dataString = 'answer='+ answer + '&user_id=' + user_id + '&question_id=' + question_id;
$.ajax({
type: "POST",
url: "config/accountActions.php?action=newanswer",
data: dataString,
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
});
return false;
});
</script>
You will notice that I have tried $("#conversation").hide().html(data).fadeIn('fast'); but it did not successfully do the job. It only reloaded the information that was passed through ajax into the div instead of just reloading the foreach.
How can I refresh the div or the <?php foreach(); ?> in the success function of the ajax call?

Mitch, I'm looking at this part:
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
See the expression ".html(data)"??? Where is "data" being declared? The code above will never work. Now, look at the lines below. Particularly the first one. See my change?
success: function(data) {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
Once you make this change, you need to use a debugger (chrome's or otherwise) to examine that what's coming back from your ajax call (which we don't have here) is what you need. But first, fix the bug.
Good luck.

jQuery .load() method (http://api.jquery.com/load/) can fetch and update single block from webpage. It will reload whole webpage in background, so some overhead is generated..
Change your ajax success to something like below:
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#conversation").load("config/accountActions.php #conversation >*");
}
This should load your conversation block and all it's childs and replace current(old) conversation block.

Related

Unable to get button value/attribute in jquery using php loop

I'm working on "like" and "dislike" module in jQuery with PHP,And I'm facing these two problems:
Right now unable to get id of button (like=1, dislike=0)
Query showing correct result but how to display ajax response under "like dislike" section ?
Here is my code, following code inside foreach loop:
<?php foreach // ?>
<form class="form-horizontals1" method="post" >
<input type="hidden" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
<button class="likebutn_r" id="show<?php echo "1";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<label class="lilkcount">10(dynamic) </label>
<button class="likebutn_r" id="shows<?php echo "0";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumbdown.png" height="24" width="24"></button>
<label class="lilkcount">5(dynamic)</label>
<div id="counter"></div>
</form>
<?php end foreach // ?>
<script type="text/javascript">
$(document).ready(function(){
//likebutn_r
$('.form-horizontals1').submit(function(e){
var ids = $(this).attr('ids');
console.log(ids);
alert($(this).attr("id"));
e.preventDefault();
$.ajax({
url:'<?php echo base_url();?>main/AddVote',
type:"post",
data:new FormData(this),
//dataType: 'json',
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
console.log(data);
alert(data);
$('#counter').html(data);
}
});
});
});
</script>
Here is my controller code, please tell me how I can get "like dislike" value in script and how I can show result in views ?
function AddVote()
{
$ReviewId=$_POST['ReviewId'];
$vote=$_POST['vote'];
echo $result['TotalUpVotes'] = $this->M_main->CountSubmittedCoinVote($ReviewId,$vote);
echo $result['TotalDownVotes'] = $this->M_main->CountSubmittedDownVotes($ReviewId,$vote);
}
First, move the form ouside the loop.
<form class="form-horizontals1" method="post" >
<?php foreach // ?>
<div class="my-rev-container js-rev-container">
...
</div>
<?php end foreach // ?>
</form>
Add a class to the inputs, you whould access with
<input type="hidden" class="js-form__rev" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
Finaly access them
$('.form-horizontals1').submit(function(e){
var ids = $(this).find(".js-form__rev");
console.log(ids);

Email input is not taking email address as valid input in newsletter subscribe box

I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.

jQuery openPopup modal doesn't close after submit

I've put a modal popup box for getting inputs and then stores via ajax. It's inserted values succesfully.. but the popup stills after submittion. i've try everything like window.close(); ... ('#modalname').hide(); but nothing works for me. please help me to fix this bug.
Here's my part of working code,
<!--css for display subject in row (starts)-->
<span class="b-messages__subject">
<span>
<a href="index.php?subject=<?php echo $results[$result]['subject']; ?>&username=<?php echo $results[$result]['username']; ?>#openModal" onclick="fetch_select(<?php echo $results[$result]["id"]; ?>);">
<?php echo "Reply"; ?>
</a>
</span>
</span>
<!--css for display subject in row (ends)-->
and then modal div is,
<!--Modal box starts-->
<div id="openModal" class="modalDialog" align="center">
<div>
X
<h2><strong>Reply Message</strong></h2>
<br>
<label><strong>Enter Your Message Here</strong></label>
<br>
<label><b>From:</b> <?php echo $user; ?></label>
<span id="content-info" class="info"></span>
<br/>
<!--set session username for hidden-->
<input type="hidden" name="username" id="username" value="<?php echo $user; ?>">
<textarea name="content" id="content" class="demoInputBox"></textarea>
<!--send fusername with hidden-->
<input type="text" name="fusername" id="fusername" value="<?php echo $_GET["username"] ?>">
<!--send subject with hidden-->
<input type="text" name="subject" id="subject" value="<?php echo $_GET["subject"] ?>">
<!--status init="0"-->
<input type="hidden" name="status" id="status" value="0">
<!--time-->
<input type="hidden" name="created" id="created" value='<?php echo date("Y-m-d H:i:s"); ?>'>
<br><br>
<input type="button" name="submit" id="but-sub" value="Send Message" onClick="add();" />
</div>
</div>
<!--Modal box ends-->
My js file contains:
function add() {
/*initialize valid and assign to function validate()*/
var valid = validate();
//alert(valid); returns true
//if function validate() returns valid.. then go away
if (valid){
$.ajax({
url: "add.php",
type: "POST",
data: {
username: $("#username").val(),
fusername: $("#fusername").val(),
subject: $("#subject").val(),
content: $("#content").val(),
status: $("#status").val(),
created: $("#created").val()}
});
}
}
I am not sure if you are using JSON, but you should definitely be checking the response for pass or fail. Try adding success after your data like this (doesn't include check for pass or fail, but should close modal upon success response of the AJAX):
$.ajax({
url: "add.php",
type: "POST",
data: {
username: $("#username").val(),
fusername: $("#fusername").val(),
subject: $("#subject").val(),
content: $("#content").val(),
status: $("#status").val(),
created: $("#created").val()
},
success: function (returndata) {
//try this first
$("#openModal").modal('hide');
//try this second and uncomment if you aren't using jquery/bootstrap modal
//$("#openModal").hide();
}
});
Put your form elements in a <form></form>.
The modal should close if form is submited.

Ajax call successful, but can't get radio values from $_POST

My site is fully asynchronus, most of the html gets created and destroyed on button presses and every one of them prevents navigation.
At this part I produce a form with a "rate 1 to 10" array of radioboxes, post it using jQuery.ajax() and send it to process where it's either echoed back (for now) or echo "nothing was selected.".
This is the form,
<?php
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">';
for ($i = 0; $i <= 10; $i++) {
echo '
<span class="lead form-options">' .'</span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio'. $i .'" value="'. $i .'">'. $i.'
</label>';
}
echo '
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
?>
This is the javascript:
$('body').on('click', '.surveyForm', function(){
console.log("Clicked on .surveyForm-btn");
var data = $('#surveyForm').serialize();
console.log( data );
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log("Ajax call to processSurvey success");
$("#surveyForm").clearForm();
console.log(result);
console.log( data );
}
});
return false;
});
And this is the process php:
<?php
if (isset($_POST['sabor'])) // if ANY of the options was checked
echo $_POST['sabor']; // echo the choice
else
echo "nothing was selected.";
print_r($_POST);
?>
This is the console after clicking submit WITH a selected radiobox:
Clicked on #surveyForm
[EMPTY LINE]
Ajax call to processSurvey success
nothing was selected.
[EMPTY LINE]
This means the submit is successful, but the form data is empty. I've been trying to find the problem since yesterday, I'm pretty sure I'm passing the data wrong but can't find anything in google that I haven't tried.
EDIT: Added most sugestions, problem persists. Maybe the html structure is wrong? The form and the submit don't seem to be connected.
EDIT 2: I found something very strange, on the final code there seems to be an extra closing tag, like this
<form id="surveyForm" action="processSurvey.php" method="post"></form>
<h3>Alimentos</h3>
<h4>Sabor</h4>
I have no idea where is that coming from, but is defenitely the problem.
there are a lot of notes here
1- you will get confused with form id='surveyForm' and button class='surveyForm' so its better to change it a little bit to button class='surveyForm_btn'
2- I think you should serialize the form not the button
var data = $('#surveyForm').serialize(); // not .surveyForm
3- IDs must be unique
4- $("#surveyForm").clearForm(); // not .surveyForm
finally check all comments
and Its better to use
$('body').on('submit', '#surveyForm', function(){});
Edited answer:
1- please check everything after each step
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
in js
$('body').on('submit', '#surveyForm', function(){
var data = $(this).serialize();
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log(result);
}
});
return false;
});
in php
<?php
echo 'Connected successfully';
?>
this code will output Connected successfully in console .. if this work add your for loop and make a check again
Try to write your htm like that :
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<?php
for ($i = 0; $i <= 10; $i++) {
?>
<span class="lead form-options"></span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio<?=$i ?>" value="<?= $i ?>" /><?= $i?>
</label>
<?php
} ?>
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>

Ajax loaded comment not working

My php file loops out each blog post in my database and also creates the comments section. The blogs post great. When I comment on the most recent blog post, the comment does not appear but it seems to add a line as the space expands, just does not include the comment. When I comment on the first post, it works great and exactly as expected. I can't figure out how to correct it. I thought it was a matter of add a .closest to the comment-block selector but that didn't seem to do the trick.
I appreciate any help or feedback!
PHP/HTML
<?php // retrive post
include('php/config.php');
include ('php/function.php');
dbConnect();
$blog_query = mysql_query(
'SELECT *
FROM Blog
ORDER BY DATE DESC');
$date = date_create($row['DATE']);
while($row = mysql_fetch_array($blog_query)): ?>
<div class="post">
<h2><?php echo $row['TITLE']?></h2>
<h3><?php echo date_format($date, 'l, F j, Y')?></h3>
<p><?php echo $row['CONTENT']?></p>
</div>
<h2>Comments.....</h2>
<div class="comment-block">
<?php // retrieve comments with post id
$comment_query = mysql_query(
"SELECT *
FROM Comments
WHERE BID = {$row['ID']}
ORDER BY CID DESC
LIMIT 15") or die(mysql_error());
while($comment = mysql_fetch_array($comment_query)):?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $comment['UNAME'] ?> <span>said....</span></h3>
<p><?php echo $comment['COMMENT']?></p>
</div>
</div>
<?php endwhile?>
</div>
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<div>
<input type="hidden" name="BID" value="<?php echo $row['ID']?>">
<label> <span>Display Name: *</span>
<input id="uname" type="text" tabindex="1" name="commentName" required />
</label>
</div>
<div>
<label> <span>Comment: *</span>
<textarea id="textarea" placeholder="Enter your comment here..." tabindex="2" name="commentMessage" required></textarea>
</label>
</div>
<div>
<input type="submit" id="submit" value="Submit Comment">
</div>
</form>
<?php endwhile?>
</div>
Jquery/Ajax:
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'php/ajaxcomment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
ajajcomment.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include('config.php');
include('function.php');
dbConnect();
if (!empty($_POST['commentName']) AND !empty($_POST['commentMessage']) AND !empty($_POST ['BID'])) {
$name = mysql_real_escape_string($_POST['commentName']);
$comment = mysql_real_escape_string($_POST['commentMessage']);
$BID = mysql_real_escape_string($_POST['BID']);
mysql_query("
INSERT INTO Comments
(UNAME, BID, COMMENT)
VALUES('{$name}', '{$BID}', '{$comment}')");
}
?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $name ?> <span>said....</span></h3>
<p><?php echo $comment ?></p>
</div>
</div>
<?php
dbConnect(0);
endif?>
What does "php/ajaxcomment.php" return when you post a comment? Pure HTML?
I'd make the "php/ajaxcomment.php" return JSON, for example:
<?php
/*
here you do what ever you do now,
Insert the new comment to database, etc
*/
// Then you return the inserted data:
$data = array(
'UNAME' => $username,
'COMMENT' => $comment,
);
header('Content-Type: application/json');
print json_encode( $data );
?>
..and change the ajax:
...
...
success: function(data){
var commentItem = $('<div/>').addClass('comment-item');
var commentPost = $('<div/>').addClass('comment-post');
var user = $('<h3/>').html( data.UNAME +'<span>said...</span>' );
var comment = $('<p/>').html( data.COMMENT );
commentItem.html( commentPost.html( user + comment ) ).hide().fadeIn(800);
$('.comment-block').append(commentItem);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
...
...

Categories

Resources