I am trying to clear form fields after submitting via ajax but it does not work. Someone please help check my codes and give me some good suggestions. Below is my code:
jQuery(document).on('click', '.um-message-send:not(.disabled)',function(e){
e.preventDefault();
jQuery('.um-message-send:visible').addClass('disabled');
var message_to = jQuery('.um-message-body:visible').attr('data-message_to');
var content = jQuery('.um-message-textarea textarea:visible').val();
jQuery.ajax({
url: um_scripts.ajaxurl,
type: 'post',
dataType: 'json',
data: { action: 'um_messaging_send', message_to: message_to, content: content },
success: function(data){
jQuery('.um-message-textarea textarea:visible').val('');
jQuery('.um-message-body:visible').find('.um-message-ajax:visible').html( data.messages );
if ( data.limit_hit ) {
jQuery('.um-message-footer:visible').html( jQuery('.um-message-footer:visible').attr('data-limit_hit') );
}
jQuery('.um-popup-autogrow:visible').mCustomScrollbar('update').mCustomScrollbar("scrollTo", "bottom",{ scrollInertia:0});
}
});
return false;
});
Html
<div class="um-message-textarea">
<?php echo $this->emoji(); ?>
<textarea name="um_message_text" id="um_message_text" data-maxchar="<?php echo $limit; ?>" placeholder="<?php _e('Type your message...','um-messaging'); ?>"></textarea>
</div>
<div class="um-message-buttons">
<span class="um-message-limit"><?php echo $limit; ?></span>
<i class="um-faicon-envelope-o"></i><?php _e('Send message','um-messaging'); ?>
</div>
The answer was simply to replace success with complete as such...
success: function(data) {
// [...]
=>
complete: function(data) {
// [...]
Related
I am working with ajax with php,I have following buttons in loop,I just want to
show/fetch data(number) on correct place/div using "attr" in jquery but not working in my side
Here is my button in loop
<?php
foreach //
<button class="btn likebutn_r" data-datac="1" data-datacw="<?php echo $WalletAddress; ?>" data-datacr="<?php echo $rev->id; ?>" data-datacoin="<?php echo $rev->coin_id; ?>" data-datasymbol="<?php echo $rev->symbol; ?>" id="show<?php echo "1";?>" value="1" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<div id="<?php echo $rev->id; ?>">12(dynamic)</div>
endforeach//
Here is my ajax code,How can i get data using custom attribute (via pass ReviewId)? Thanks in advance
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function (e) {
var vote = $(this).data('datac');
var review = $(this).data('datacr');
var CoinId = $(this).data('datacoin');
var symbol = $(this).data('datasymbol');
var WalletAddress = $(this).data('datacw');
var datacrp = $(this).data('datacrp');
$('#' + review).hide();
e.preventDefault();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>main/AddVote',
data: {
vote: vote,
review: review,
CoinId: CoinId,
symbol: symbol,
WalletAddress: WalletAddress
},
success: function (data) {
alert(data);
$('#' + review).html(data);
}
});
});
});
</script>
Hope this code help you.
*Reminder the js code below have to implement inside the php file so the Post url ajax will get the value.
$('body').on('click', '.btn', function(e){
var allData = {
"vote": $(this).data('datac'),
"review": $(this).data('datacr'),
"CoinId": $(this).data('datacoin'),
"symbol": $(this).data('datasymbol'),
"WalletAddress": $(this).data('walletaddress'),
}
e.preventDefault();
$.ajax({
type: 'POST',
url:'test.com',
data: allData,
success: function(data) {
$(this).attr('data-datac', data['vote']);
$(this).attr('data-datacr', data['review']);
$(this).attr('datacoin', data['CoinId']);
$(this).attr('data-datasymbol', data['review']);
$(this).attr('data-datacoin', data['review']);
$(this).attr('data-datasymbol', data['symbol']);
$(this).attr('data-walletaddress', data['WalletAddress']);
}
});
});
<button
class="btn likebutn_r"
data-datac="1"
data-datacw="teste"
data-datacr="asdfasf"
data-datacoin="asdfasdf"
data-datasymbol="asdfasdf"
data-datacrp="asfsa"
id="31"
data-walletaddress="dsaf"
value="1"
type="submit">Hello</button>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
I trying to make opening WP posts in popup.
Firts part of code its form in posts loop where I get query of posts what should be opened
<form id="postForm" method="POST">
<input id="postQuery" style="display: none" name="postQuery" value="<?php echo get_the_ID() ?>">
<input id="sendQueryBtn" data-toggle="modal" data-target="#exampleModalLong" type="submit" value="<?php the_title(); ?>">
</form>
Next is my JS, where I do query check by alert
$(document).ready(function () {
$("form").submit(function () {
let xuinya = $(this).serialize();
$.ajax({
type: "POST",
url: '.../footer.php',
data: xuinya,
success: function (data) {
alert(xuinya)
},
error: function (jqXHR, text, error) {
$('#modalBody').html(error);
}
});
return false;
});});
And I final, here is part of HTML with modal, where I try to use POST
<div id="modalBody" class="modal-body">
<?php
echo $_POST["postQuery"];
echo apply_filters( 'the_content', get_post( $_POST["postQuery"] )->post_content );
?>
</div>
My problem is because when I check query in JS - qet alert message with correct value, but in php I always qet simple "1".
I don't get why you posting to footer.php, I think its should be admin-ajax.php
just simply add to youfooter.php
<script>
var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
</script>
Change url value in js to ajax_url, make sure hat with data you posting variable action and then create function in functions.php, something like this(if you sending action value as 'get_pop_posts')
add_action( 'wp_ajax_get_pop_posts', 'get_pop_posts_init' );
add_action( 'wp_ajax_nopriv_get_pop_posts', 'get_pop_posts_init' );
function get_pop_posts_init() {
$data = $_POST;
print_r($data);
die();
}
I'm having a problem with my Ajax. It seems to not be sending the data to my php file even though it worked properly 2 days ago. HTML:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button type='submit'>Comment</button>
</form>
My ajax code:
$('#comment').submit(function(event) {
var form = $(this);
var method = form.attr('method');
var url = form.attr('action');
info = {
comment: $('textarea').val()
};
console.log(method);
console.log(url);
console.log(info);
$.ajax({
type: method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
event.preventDefault();
});
I'm doing this for a friend and I'm using this exact same Ajax code (slightly modified) on my website and it's working flawlessly.
I think the biggest red flag here is that in my php file I have an if-else that should send an alert in case the textarea is empty but for some reason it's not doing that here even though nothing is getting through. I used console.log on all the variables to see if their values are correct and they are. The alert(data) just returns an empty alert box.
EDIT: As requested, PHP code from process.php
<?php
session_start();
include_once 'db_connection.php';
date_default_timezone_set('Europe/Zagreb');
if(isset($_POST['comment'])){
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
$conn -> query($sql);
$conn -> close();
}
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
SQLInsert($id, $date, $komentar, $conn);
} else {
echo '<script>';
echo 'alert("Comment box is empty.");';
echo '</script>';
}
?>
EDIT: Problem solved, thanks for the help everyone.
You are no getting alert because you are no displaying anything as response in php file. Add the insert function out side the if condition too
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
if($conn -> query($sql)){
return true;
}else{
return false;
}
$conn -> close();
}
if(isset($_POST['comment'])){
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
$insert = SQLInsert($id, $date, $komentar, $conn);
//On based on insert display the response. After that you will get alert message in ajax
if($insert){
echo 'insert sucess';
die;
}else{
echo 'Error Message';
die;
}
}
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button id="submit_button">Comment</button>
</form>
starting from this html you have to trigger your function as:
$("#submit_button").click(function(e){
I have added an id to your button for simplicity and removed the type because it is useless in this case.
If you want to catch the submit event of the form you have to change your html as:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<input type='submit'>Comment</button>
</form>
and then you can keep the same javascript
This here is the issue. Have you tried providing a "method" ?
$.ajax({
**type: method,**
method : method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
Also if this doesn't solve it. show me the console output
<form name="fileInfoForm" id='comment' method="post" enctype="multipart/form-data">
<textarea id="textarea"></textarea>
<button type="submit"></button>
</form>
<script type="text/javascript">
$('#comment').submit(function (e) {
e.preventDefault();
var textarea=$('#textarea').val();
var form=document.getElementById('comment');
var fd=new FormData(form);
fd.append('textarea',textarea);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'action.php',
data: fd,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert(data);
}
})
});
</script>
in action.php
$textarea= $_POST['textarea'];
echo $textarea;
<script>
function addprescription() {
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
}
</script>
I have a function to submit the form. But ajax function alerts its as failure. But data base seems to be updated. when I click the button. I couldn't find the reason for the cause in the console.
this is the php file
<?php
echo "I'm in";
include "../../Adaptor/mysql_crud.php";
include ("Prescription.php");
$prescription=new Prescription();
if(isset($_POST)){
$Note=htmlspecialchars($_POST['Note']);
$Case_Histroy=htmlspecialchars($_POST['Case_Histroy']);
$medication = htmlspecialchars($_POST['Medication']);
$pname=$_POST['pname'];
$danme=$_POST['dname'];
$id=$_POST['id'];
$prescription->insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
<div class="alert alert-success" id="alert"><strong><?php echo "Submitted succesfully"; ?></strong></div>
<?php
}
?>
Try adding an else statement to your if:
insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
}
?>
Also, it's not necessary to stick the php in the middle of the <div> you can just use echo at the beginning since you're not introducing any variables to it:
echo '<div class="alert alert-success" id="alert"><strong>Submitted successfully</strong></div>';
Finally I got the answer for the Problem! Actual problem is button that fired up the AJAX request also reloaded the page interrupting AJAX inner workings. So the error message will be alerted.
I tried this code.
<script>
$(function() {
$("#button_Add_p").click(function(e){
e.preventDefault();
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
dataType: 'html',
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
});
});
</script>
Ok here is a strange little problem:
Here is a test page, which user clicks to open:
When user clicks view results I have 3 selectboxes inside the modal box.
box1 => populates =>Box 2 => populates Box 3
My problem
When user clicks submit, instead of results being displayed from the query based on selectbox selections, the test page opens again inside the modalbox... as you can see in below image
On submit
Any idea why when form is submitted current page opens inside modalbox?
Submit Form
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) { $('#resultForm').append(data); }
});
}
});
</script>
Populate Textboxes
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm" action="result.php">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
Display result
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
$sql="Select * FROM Multiple_Picks WHERE tournament ='$tour' AND round='$round' GROUP BY member_nr";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result)){
$memNr = $row['member_nr'];
$pick = $row['pick'];
$score = $row['score'];
?>
echo $memNr;
echo $pick;
echo $score;
}
}
?>
It would appear that:
success: function(data) { $('#resultForm').append(data); } you are telling it to put the ajax response in the resultForm, which appears to be inside your modal. Is that not what is happening. Hard to tell from your question and code what SHOULD be happening vs what IS happening now.