How to make this Media Button work after AJAX - javascript

i have simple editor with TinyMCE loaded by AJAX jQuery. Editor loaded successful but the 'Media Button' not working.
This code for AJAX PHP, find the code from here: https://developer.wordpress.org/reference/functions/wp_editor/#comment-2273
// leave comment
function ajax_leave_comment() {
global $wpdb, $bbp;
$reply_id = esc_attr( $_POST['reply_id'] );
$topic_id = bbp_get_reply_topic_id( $reply_id );
$temp = '';
$temp .= bbp_get_the_content( array( 'context' => 'reply-' . $reply_id ) );
$temp .= \_WP_Editors::enqueue_scripts();
$temp .= print_footer_scripts();
$temp .= \_WP_Editors::editor_js();
echo $temp;
}
jQuery AJAX.
// leave comment
$( document ).on( 'click', 'button[class*="leave-comment-"]', function(e) {
var button_comment = $( this );
var reply_id = button_comment.attr( 'reply-id' );
var comment_data = {
action: 'ajax_leave_comment',
reply_id: reply_id,
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: comment_data,
dataType: 'html',
beforeSend: function ( xhr ) {
button_comment.text( 'Loading...' );
},
success: function( response, result, xhr ) {
button_comment.hide();
button_comment.after( response );
}
});
});
Loaded editor screenshot
And this error on console log if "Media Button" clicked,
Please explain how to make Media Button working. Thank you.

Related

Why are there no problems with Ajax on the desktop, but have on the phone?

There is a button on the site, when you click on that button, new posts are loaded.Everything works fine on the desktop, but it breaks down on the phone.
XHR failed loading: POST "https://test-5.vbbn.in/wp-admin/admin-ajax.php".
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
n. # jquery.js?ver=1.12.4-wp:4
(anonymous) # (index):1732
dispatch # jquery.js?ver=1.12.4-wp:3
r.handle # jquery.js?ver=1.12.4-wp:3
add_action( 'wp_footer', 'my_action_javascript' );
function my_action_javascript() { ?>
<script>
jQuery(document).ready(function($) {
var page = 2;
var post_count = jQuery('#posts').data('count');
var ajaxurl = "<?php echo admin_url('admin-ajax.php');?>"
jQuery('#load_more').click(function () {
var data = {
'action': 'my_action',
'page': page
};
jQuery.post(ajaxurl, data, function(response) {
jQuery('#posts').append(response);
if (post_count == page){
jQuery('#load_more').hide();
}
page++;
});
});
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
$args = array(
'post_type' => 'post',
'category_name'=> 'nouvelles',
'paged' => $_POST['page'],
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
Tried to add e.preventDefault, to avoid rebooting that does not write the POST then pass event to the function, but it shows that e.preventDefault is not a function.
Website - https://test-5.vbbn.in/
Hope for any help. thanks
You are trying to hit an url using admin ajax. but url is not returning 200 as response. It is returning 400(not found) . I just tested the url by clicking button. Please see the screenshot below that I attached.
Now fix the issue and be confirm that your action is available for admin-ajax

How to execute AJAX on button click in php?

I'm developing a WordPress plugin and I have added some elements on admin settings using php file. Now I want to execute a php function on button click and after searching on internet, AJAX seemed like a way to go. But I don't know AJAX at all. So here is some code I put together.
And I know this code may seem messed up but please take a look.
echo"<form method='POST' action='temp.php'>";
function slideyglidey_settings_section_callback() {
esc_html_e( 'Plugin settings section description', 'slideyglidey' );
}
function slideyglidey_settings_input_file_callback() {
$options = get_option( 'slideyglidey_settings' );
$file_input = '';
if( isset( $options[ 'file_input' ] ) ) {
$file_input = esc_html( $options['file_input'] );
}
echo '<input type="file" id="slideyglidey_fileinput"
name="slideyglidey_settings[file_input]" value="' . $file_input . '"
onchange="onFileSelected(event)" />';
}
function slideyglidey_settings_img_src_callback() {
$options = get_option( 'slideyglidey_settings' );
$img_src = '';
if( isset( $options[ 'img_src' ] ) ) {
$img_src = esc_html( $options['img_src'] );
}
echo '<img src="" id="slideyglidey_imgsrc"
name="slideyglidey_settings[img_src]" value="' . $img_src . '" width="350"
height="200"/>';
}
function slideyglidey_settings_upload_btn_callback() {
$options = get_option( 'slideyglidey_settings' );
$upload_btn = '';
if( isset( $options[ 'upload_btn' ] ) ) {
$upload_btn = esc_html( $options['upload_btn'] );
}
echo '<input type="button" id="slideyglidey_uploadbtn"
name="slideyglidey_settings[upload_btn]" value="Upload"/>';
}
echo"</form>";
?>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var $checkboxes = $( "form input:file" )
$checkboxes.on("change", function(){
var st="helloHOWAREYOU";
$.ajax({
type: "POST",
url: "temp.php",
cache: false,
data: 'name=' + st,
success: function(res){
$('#result').html(res);
}
});
})
</script>
temp.php
<?php
$name = $_POST['name'];
echo '<script>console.log($name)</script>';
?>
When I execute this code, I get no errors but I don't get the message in console log as well.
Any help is appreciated.
Thanks!
You can use this way to pass data
$.ajax({
...
data : {name : 'helloHOWAREYOU'},
...
});
Assuming this is your button:
echo <button id="handler">click me</button>
Then put the following code in a <script> tag:
document.getElementById('handler').addEventListener('click', AJAX);
function AJAX() {
const req = new XMLHttpRequest();
req.addEventListener("load", (data) => console.dir(data.target.response));
req.open("GET", "https://reqres.in/api/users?page=2");
req.send();
}
<button id="handler">click me</button>
Note I now perform the AJAX request to a website which offers some dummy data. Of course you have to change this to your own requirements.

JSON error even if PHP script works

My JavaScript always returns an error, even if PHP did what it should.
No matter if I write dataType: "JSON" or "JSONP" or delete it completely.
When I remove echo json_encode(... it works as it should. I see the alert for success.
But I want to make two or three success messages appear in-line in html.
Here is my JS code:
jQuery(document).ready(function($){
$('#przypinanie').click(function() {
var data_cat = $('select#cat').val();
var data_post_id = $('input#przypinanie-post-id').val() ;
var przypinanie = $('input#przypinanie').val();
$.ajax({
url: ajaxurl,
data: {
cat_id: data_cat,
post_id: data_post_id,
przypinanie_usuwanie: przypinanie,
action: "przypinanie_php"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
},
});
});
My PHP code:
if ( $przypinanie == "PRZYPNIJ" ) {
$validate = $wpdb->get_var("SELECT przypieta_cat_id FROM polecane_przypinane WHERE przypiety_post_id = '$post_id'");
if ( isset($validate) ){
$msg = 'Wpis jest już przypięty do kategorii '. $validate ;
}else{
$wpdb->insert( 'polecane_przypinane',
array(
'przypiety_post_id' => $post_id,
'przypieta_cat_id' => $cat_id,
)
);
$msg = 'Wpis został przypięty do kategorii '. $validate ;
}
$responce = $msg;
}
header('Content-type: application/json');
echo json_encode($responce);
OK. Thank You for answers.
I resigned from JSON and I just did echo $responce; at the end of function.
Pleased to solwed my first question here.

wordpress plugin jquery ajax call to function not working

JQuery Code:
jQuery("#dmhsc-form").on("submit", function () {
var form = this;
if (jQuery("input[name='url']", form).val() == "") {
jQuery("div[id='results']", form).html('<div class="not-available">Please, Enter site address.</div>');
return false;
}
var url = jQuery("input[name='url']", form).val();
jQuery("div[id='results']", form).css('display', 'none');
jQuery("div[id='results']", form).html('');
jQuery("div[id='loading']", form).css('display', 'inline');
var data = {
'action': 'dmhsc_show',
'url': url,
'security': badnc_ajax.dmhsc_nonce
};
jQuery.post(badnc_ajax.ajaxurl, data, function (response) {
var x = JSON.parse(response);
if (x.status >= 0) {
display = x.text;
} else {
display = "Error occured." + x;
}
jQuery("div[id='results']", form).css('display', 'block');
jQuery("div[id='loading']", form).css('display', 'none');
jQuery("div[id='results']", form).html(unescape(display));
});
return false;
});
Plugin File
function badnc_load_styles() {
wp_enqueue_script( 'badnc-script', plugins_url( 'script.js', __FILE__ ), array('jquery')); // script.js contains jquery code
wp_localize_script( 'badnc-script', 'badnc_ajax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'dmhsc_nonce' => wp_create_nonce( 'dmhsc_nonce' ))
);
}
add_action( 'wp_loaded', 'badnc_load_styles' );
add_action( 'admin_enqueue_scripts', 'badnc_load_styles' );
function dmhsc_show() {
check_ajax_referer( 'dmhsc_nonce', 'security' );
if(isset($_POST['url']))
{
$url = sanitize_text_field($_POST['url']);
if(!$url || !is_string($url) || ! preg_match('/^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$/i', $url)) {
$result = array('status'=>0,'url'=>$url, 'text'=> '<div class="not-available">Please, Enter valid domain name.</div>');
echo json_encode($result);
} else {
/*$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$url.'</div>');
echo json_encode($result);*/ //It display the message without calling to fucntion
check_https($url); //function call
}
}
die();
}
add_action('wp_ajax_dmhsc_show','dmhsc_show');
add_action('wp_ajax_nopriv_dmhsc_show','dmhsc_show');
function check_https($host) {
$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$host.'</div>');
echo json_encode($result);
}
Problem
I want to show "Domain: domain name" when I submit the form. Form contains url field and submit button.
but I don't know it is not displaying the message written in check_https() function.
I am also getting error in console:
Uncaught SyntaxError: Unexpected token { in JSON at position 74
at JSON.parse (<anonymous>)
If I display the message without calling to function check_https(), it works.
What should be the problem.

Ajax runs my insert query twice

I am working in WordPress and I run a function to insert a row in database with ajax. Ajax runs but for some reason insert operation is performed twice.
Below is my code
Ajax
jQuery(function ($) {
$(document).on("submit","#myvoteform", function(e) {
//form is intercepted
e.preventDefault();
//serialize the form which contains secretcode
var sentdata = $(this).serializeArray();
//Add the additional param to the data
sentdata.push({
name: 'action',
value: 'votes'
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
//$("#myresult").append(res.l);
// $("#myresult").html("");
$("#myresult").html(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
}); //vote function ends here
PHP code
Insert function
add_action( 'wp_ajax_votes', 'votes' );
add_action( 'wp_ajax_nopriv_votes', 'votes');
add_shortcode('sketchfamvotes','voteus');
function voteus(){
// register & enqueue a javascript file called globals.js
wp_register_script( 'votess', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) );
wp_enqueue_script( 'votess' );
// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'votess', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function votes ()
{//echo json_encode("pakistan zindabad"); die();
$cat =$_POST['category'];
$comp = $_POST['competition'];
$uid= $_POST['uid'];
global $wpdb;
$userid = $_POST['userid'];
$myvote = 1;
if($wpdb->insert(
'votes',
array(
'votes' => 1,
'competition' => $comp,
'uid' => $uid
)
) == false) {wp_die(json_encode('Database Insertion failed')); die();} else {echo json_encode('your vote was successfully recorded');die();}
}
Below is my form which is the result of another ajax call. I'm not pasting the full ajax php function but just showing how my form looks like.
if( is_array($results) && count($results) > 0 ) {
$form = "";
foreach( $results as $result ) {
$form .= '<form id="myvoteform" action="" method="post">';
$form .= "<input name='category' type='hidden' value='$result->category'>";
$form .= "<img src='$result->path' width='150' height='150' >" . '<br><br>';
$form .= "<input name='uid' type='text' value='$result->uid'>";
$form .= "<input name='competition' type='hidden' value='$result->competition'>";
$form .= "<input name='userid' value'$result->uid' type='text'>".'<br>';
$form .= $result->category.'<br>';
$form .= $result->uid.'<br>';
$form .= $result->votessum.'<br>';
$form .= "<input style='margin-bottom:30px;' id='votebutton' value='vote' name='submit' type='submit'/></form>";
Try with this modified code - jquery .off()
jQuery(function ($) {
$(document).off().on("submit","#myvoteform", function(e) {
//form is intercepted
e.preventDefault();
//serialize the form which contains secretcode
var sentdata = $(this).serializeArray();
//Add the additional param to the data
sentdata.push({
name: 'action',
value: 'votes'
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
//$("#myresult").append(res.l);
// $("#myresult").html("");
$("#myresult").html(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
}); //vote function ends here

Categories