POST method in wordpress - javascript

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

Related

How to handling validation with ajax request for woocommerce form

I am creating my custom form-edit-account.php template. This contains a form that allows users to change their name, surname, password and other info. Originally the form does not perform ajax requests, you click the save changes button, the data is saved and the page is reloaded. The required fields and their validity are managed by the file https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.218
What I did was create ajax request for the form in order to save the fields without the page refresh. The fields are edited and updated correctly, so it works. However, handling validation not working.
Somehow I need field handling validation but I don't know how to proceed I'm stuck at this point. I have two ideas I could work on:
Try somehow to make the original handling validation work.
Create a custom handling validation with js or php separately from the original file, but I don't know if this is correct.
How could I handle field validation? I hope someone can help me understand how I could do this, I appreciate any help and thank you for any replies.
Example of My-Form
<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
<!-- Save Settings -->
<p style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</p>
</div>
</form>
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) { //form onsubmit ecent
e.preventDefault(); // the preventDefault function stop default form action
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success: function(data) {
alert('Form Inviato');
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
add_action('woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
// A default response holder, which will have data for sending back to our js file
$response = array(
'error' => false,
);
// Example for creating an response with error information (This not working)
if (trim($_POST['account_first_name']) == '') {
$response['error'] = true;
$response['error_message'] = 'Name is required';
if (trim($_POST['account_first_name']) == '') {
$response['status'] = false;
$response['message'] = 'Name is required';
}else{
$response['status'] = true;
$response['message'] = 'success';
}
// Exit here, for not processing further because of the error
echo json_encode($response);
exit();
}
exit(json_encode($response));
}
Thanks to the intervention of Martin Mirchev in the comments I was able to solve the problem.Here is the solution for anyone who is in the same conditions.
(The form remained the same)
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
//jQuery('.woocommerce-notices-wrapper').append(response);
jQuery('.woocommerce-notices-wrapper').prepend(response);
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$response = wc_print_notices();
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}

I cannot figure out why my ajax is not sending the data to my php file

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;

Get id for each element

I have blog post list and that post have comments. Posts and comments i loop with foreach from database.So i have problem when i want to create new comment via ajax. I have form and one hidden field for holding post id.
When from jquery i try to access to that element post_id is all time the some. I try on submit to debug with alert to see witch post_id will be returned. All time return 270. And when i click to other post comment submit id is not changed.
Posts and comments
<?php foreach($posts as $post): ?>
<h1><?= $post->title; ?></h1>
<p><?= $post->text; ?></p>
<?= if($comments = postComments($post->id): ?>
<?= foraech($comments as $comment): ?>
<form id="post_add">
<input type="text" placeholder="Say somthing..." name="comment">
<input type="hidden" name="pid" class="pid" value="<?= $post->id">
<input type="submit">
</form>
<?= endforeach; ?>
<?= endif; ?>
<?= endforeach; ?>
submiteComment: function() {
var comment_form = $("#comment_add");
var comment_text = $(".comment_text");
var pid = $(".pid"); // post id
$("body").on("submit", comment_form, function(e) {
e.preventDefault();
alert(pid.val()); // debug all time return 270 for all comments
if($.trim(comment_text).length) {
$.ajax({
type: 'post',
url: baseurl + '/comment/create',
data: {item_id: post_id.val(), comment_text: comment_text.val()},
success: function(data) {
alert('success');
},
error: function(t, r, j) {
alert(r.responseText);
}
})
}
});
Because you are giving each of the post id fields in the form the same name and class, when you access it like this:
var pid = $(".pid");
You will receive all three of the pid elements for your comments into the variable pid. When you do pid.val() it will just return the value of the first one, which is why you will always be seeing the same pid no matter which comment you submit.

Posting html form data to php and accessing that through javascript

I'm trying to post some data to an html form, then that form sends the data to php, and finally javascript takes the data from that php.
This is my html form:
<form action="search.php" method='POST'>
<input id="movie_name" name="movie_name" type="text">
<input name="myBtn" type="submit" value="Submit Data">
</form>
This is my php file which is called search.php:
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo '<script>', 'hello();', 'var movie = '$movie_name';', '</script>';
}
?>
Finally my js script which is in the same file as the php one:
function hello(){
console.log('<?php echo $movie_name?;>');
}
What happens when I load this is that my html redirects ok and then for some in search.php nothing happens, the page goes white and the only thing the console says is "Resource interpreted as Script but transferred with MIME type text/html..."
What exactly you want is not clear. But i suggest you to use jQuery ajax like this:
<input id="movie_name" name="movie_name" type="text">
<input id="myBtn" name="myBtn" type="button" value="Submit Data">
$('#myBtn').click(function(e){
var movie_name = $('#movie_name').val();
$.ajax({
url: "search.php",
type: "POST",
data: {
'movie_name': movie_name
},
beforeSend : function() {
},
success : function(response) {
console.log(response);
},
error : function()
{
},
complete : function() {
}
});
});
in your search.php
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo $movie_name;
}
?>
This is better way from my point of view.
This should work:
<?php
if (isset($_POST['movie_name'])){
$movie_name = $_POST['movie_name'];
}
?>
<script type="text/javascript">
function hello(){
console.log('<?php echo $movie_name; ?>');
}
</script>
<?php
echo '<script> alert("'.$movie_name.'"); hello(); </script>';
?>

Ajax delete data from database function not working

I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>&nbsp&nbsp<input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span> &nbsp&nbsp<input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}

Categories

Resources