I am relatively new to jQuery and AJAX in particular. I have a small issue with the return value always being 0, though I think this is actually the success message and it’s not returning anything.
I have scoured the Google-verse and I have the die() function on the PHP callback and I believe the add_actions are correct.
I am working on a local host, though I doubt that affects it and this is all in the admin, not front end. I also checked that the js is enqueued and localised.
I get a 200 OK message in the chrome developer area.
I also tested out the basic AJAX from http://codex.wordpress.org/AJAX_in_Plugins and it also returned 0, which makes me wonder if it is something other than the code outlined below.
Right now I am just trying to make it send something back to the jQuery. Any help would be appreciated.
The jQuery
jQuery(document).ready(function(){
jQuery('.cl_link_buttons').val('id').click(function() {
var currentid = jQuery(this).attr('id');
//alert(currentid);
console.log(currentid);
jQuery.ajax ( data = {
action: 'cleanlinks_ajax_get_post_data',
url: ajaxurl,
type: 'POST',
dataType: 'text',
"currentid" : currentid
});
jQuery.post(ajaxurl, data, function(response) {
var dataz = response;
alert( dataz );
console.log (dataz); //show json in console
});
return false;
}); //end click event
}); //end doc ready
The PHP
add_action("wp_ajax_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");
add_action("wp_ajax_nopriv_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");
function cleanlinks_ajax_get_post_data() {
$from_ajax = $_POST['currentid'];
echo "do" . $from_ajax . "something";
die();
}
I am relatively new to jQuery and AJAX in particular. I have a small issue with the return value always being 0, though I think this is actually the success message and it’s not returning anything.
I have scoured the Google-verse and I have the die() function on the PHP callback and I believe the add_actions are correct.
I am working on a local host, though I doubt that affects it and this is all in the admin, not front end. I also checked that the js is enqueued and localised.
I get a 200 OK message in the chrome developer area.
I also tested out the basic AJAX from http://codex.wordpress.org/AJAX_in_Plugins and it also returned 0, which makes me wonder if it is something other than the code outlined below.
Right now I am just trying to make it send something back to the jQuery. Any help would be appreciated.
The jQuery
jQuery(document).ready(function(){
jQuery('.cl_link_buttons').val('id').click(function() {
var currentid = jQuery(this).attr('id');
//alert(currentid);
console.log(currentid);
jQuery.ajax ( data = {
action: 'cleanlinks_ajax_get_post_data',
url: ajaxurl,
type: 'POST',
dataType: 'text',
"currentid" : currentid
});
jQuery.post(ajaxurl, data, function(response) {
var dataz = response;
alert( dataz );
console.log (dataz); //show json in console
});
return false;
}); //end click event
}); //end doc ready
The PHP
add_action("wp_ajax_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");
add_action("wp_ajax_nopriv_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");
function cleanlinks_ajax_get_post_data() {
$from_ajax = $_POST['currentid'];
echo "do" . $from_ajax . "something";
die();
}
-
PHP
-
WordPress
Добрый вечер.
Есть вопрос, почему wp-admin/admin-ajax.php выдает 0 ?
Есть NEX-Forms форма обратного звонка, и при нажатии «ОТПРАВИТЬ» не срабатывает AJAX, и выдает 0
Помогите. Почему?
—
Вот эта ошибка отображается только на сайте на hoster.ru, на таймвебе все ок.
И не понимаю почему. Файлы ОДИН В ОДИН.
-
Вопрос задан
-
2469 просмотров
Комментировать
Решения вопроса 2
@wppanda5 Куратор тега WordPress
WordPress Mедведь
die(); в конец обработчика
И должен быть wp_ajax_nopriv_{action}
если юзер не залогинен
-
Везде пишут про «die();» не понимаю куда прописывать? Можете пример написать, и куда вписывать
-
WP Panda
@wppanda5 Куратор тега WordPress
Борис Белов: в самый конец обработчика перед закрывающей скобкой
function my_action_callback() {
// бла бла бла
die();
} -
спасибо за ответ.
я для обратной связи использую NEX-Forms
то есть я вставляю просто <?php echo do_shortcode(‘[NEXForms id=»1″]’) ?>
там то куда вставлять? -
Вопрос остался открытым…
-
-
WP Panda: я перенес один и тот же сайт, одну и ту же базу, одни и те же файлы, но разные хостинги. На том что не работает стоит ПХП 5.4, а писался сайт на хостинге с ПХП 5.3 возможна в этом загводзка?
-
WP Panda
@wppanda5 Куратор тега WordPress
Борис Белов: возможно,
смотрите логи сервера, тут не подскажу, обработчик вы писали не сами, форму вставляет шорткодом, что там и как под капотом я не в курсе, на этот вопрос ответит только автор плагина. -
WP Panda: перенесли сайт на хостинг с ПХП 5.3, и снова не работает. Хотя на таймвебе работает =(
-
Борис Белов: дело в том, что если ошибка в одном скрипте JS он затрагивает так же и другой, поэтому несколько плагинов и не работают. Сейчас посмотрел у Вас кажется два плагина установлено для форм.
В общем попробуйте так: удалите папку полностью с того сервера, где НЕ работате: /wp-content/plugins/nex-forms-express-wp-form-builder с того сервера, где работает скопируйте папку /wp-content/plugins/nex-forms/ туда, где НЕ работает. И соответственно включите плагин.
Без параметров он и будет выдавать 0.
Важны параметры — посмотрите что передаётся ему при аякс запросе формы и что в ответ.
-
-
В хроме консоль разработчика по ф12 на владке network
-
WP Panda
@wppanda5 Куратор тега WordPress
Pavel K: Не будет он 0 возвращать без параметров, он не вернет ничего.
-
WP Panda: будет он 0 возвращать, не верите — проверьте в исходниках.
-
Борис Белов: Посмотрел я Ваши ссылоки — нужно было сразу приводить. У Вас проблема в том, что nex-forms, а если точнее, то скрипт nexf-onload-ui.js использует старые методы из JQuery.
У Вас по одной ссылке он старый — по другой — исправленный.Решение простое:
скачайте файл по ссылочке: ipetmusic.tmweb.ru/wp-content/plugins/nex-forms-ex…и замените его у себя там, где не работает:
/wp-content/plugins/nex-forms-express-wp-form-builder/js/nexf-onload-ui.jsвот и всё.
-
-
Pavel K: неа, не хочет. Видать трабл в хостинге. Ибо файл у меня как я понимаю должен быть одинаковый, ибо я переносил с hoster.ru на timeweb.ru , и вот на тайме все работает, а на хостере — нет.
-
Борис Белов: нет, не в хостинге. У Вас сейчас вообще ничего не показывает.
-
Pavel K: знаю. Решил пока опробовать другие варианты. Спасибо за ответы!
-
Pavel K: восстановил отображение сайта, перекинул nexf-onload-ui.js и опять же не работает. Как думаете в чем еще может быть проблема? Ибо на самом деле проблема не в NEX а именно в AJAX. Ибо не работает так же, повторюсь, еще и другой плагин.
-
Борис Белов: дело в том, что если ошибка в одном скрипте JS он затрагивает так же и другой, поэтому несколько плагинов и не работают. Сейчас посмотрел у Вас кажется два плагина установлено для форм.
В общем попробуйте так: удалите папку полностью с того сервера, где НЕ работате: /wp-content/plugins/nex-forms-express-wp-form-builder с того сервера, где работает скопируйте папку /wp-content/plugins/nex-forms/ туда, где НЕ работает. И соответственно включите плагин. -
Pavel K: Так и сделал. Попробую еще раз чисто перенести сайт. Вот именно тот что на таймвебе.
-
Борис Белов: у Вас там вообще какая-то вакханалия твориться — некоторые скрипты вообще по 2 раза подключаются.
-
Pavel K: Ура. Получилось. Честно, что послужило причиной я без понятия. Но перепроверка, и перезаливка файлов помогла. Спасибо Всем!
-
WP Panda
@wppanda5 Куратор тега WordPress
Pavel K: А зачем смотреть исходники, я знаю API, и вернуть 0 или -1 обработчик может только в том случае если сделано не по API.
Типичная ошибка, когда возвращается 0
это отсутствие в конце обработчика любой из команд говорящей ему сдохнуть, или когда обработчику не определено срабатывание для не залогиненых юзерей
-
WP Panda: верно, просто понимаете, это странно, когда два одинаковых сайта работают не одинаково. Оказалось, что пока переносил с хостинга на хостинг, то может что-то до неподключилось, поэтому такая трабла была. Спасибо.
-
WP Panda: смотреть исходники за тем, что вы сомневались в том, что admin-ajax без параметров вернёт 0. в остальном почти согласен.
-
WP Panda
@wppanda5 Куратор тега WordPress
Pavel K: без каких параметров?
там обязательный ровно один ‘action’ и да если экшен задан не существующий то вернет 0, но это уже ошибка из разряда 1: 1000000 -
WP Panda: автор на скрине просто открыл admin-ajax и всё то есть как раз параметров (в том числе и action) он не задал в запросе.
Пригласить эксперта
Похожие вопросы
-
Показать ещё
Загружается…
21 сент. 2023, в 08:33
10000 руб./за проект
21 сент. 2023, в 08:28
47000 руб./за проект
21 сент. 2023, в 07:57
20000 руб./за проект
Минуточку внимания
Are currently developing a plugin that need ajax. Was thinking of doing it «correctly», so am trying to use admin-ajax.php. However I always get 0 as response, and somehow get the feeling that it never gets to my callback.
Here’s the code, have tried to keep simple.
Load js and setting admin-ajax.php outside admin
wp_enqueue_script('my-more-posts-ajax', SE_WP_MY_PLUGIN_URI . '/js/more-posts-ajax.js?' . rand(), array('jquery'));
wp_localize_script('my-more-posts-ajax', 'MyAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
Actions for callback
add_action('wp_ajax_nopriv_my_more_posts', array($this, 'load_more_posts_callback'));
add_action('wp_ajax_my_more_posts', array($this, 'load_more_posts_callback'));
PHP callback function
public function load_more_posts_callback() {
$response = json_encode(array('success' => TRUE));
header("Content-Type: application/json");
print $response;
exit;
}
js
jQuery(document).ready(function() {
jQuery('#my-show-more-form').submit(function(event) {
/* Prevent submitting normally */
event.preventDefault();
var data = {
action: 'my_more_posts',
offset: 8
};
jQuery.post(MyAjax.ajaxurl, data, function(response) {
alert('Response: ' + response);
});
});
});
Anyone got any ideas of what is wrong? Think I got all code for this.
I’m currently working on a WordPress contact form, which is created as a plugin. I need the form after submit to send an email without reloading the page. When it reloads everything is ok. The problem is when submit button is pressed and e.preventDefault() is active the browser shows me 500 (Internal Server Error) with admin-ajax.php = 0
P.S The post is edited
<?php
add_action( 'admin_footer', 'html_form_code' ); // Write our JS below here
//
function html_form_code() {
?>
<form action="<?php esc_url( $_SERVER['REQUEST_URI'] )?>" method="post" class="contact-form" id="contact-form" >
<div class=header-contact>
<p><h2>Contact Form</h2></p>
<hr>
</div>
<div class=input-containers>
<input type="text" id="name" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="" size="40" placeholder="Име и фамилия"/>
</div>
<div class=input-containers>
<input type="email" id="email" name="cf-email" value="" size="40" placeholder="Поща"/>
</div>
<div class=input-containers>
<input type="text" id="subject" name="cf-subject" pattern="[a-zA-Z ]+" value="" size="40" placeholder="Относно"/>
</div>
<div class=input-containers>
<textarea rows="10" id="message" cols="35" name="cf-message" placeholder="Текст"></textarea>
</div>
<div class=input-containers>
<input type="submit" name="cf-submitted" value="Send" id="submitForm">
</div>
<p id="verify" style="display:none;">Your message has been sent.<br /><br /></p>
</form>
<script>
jQuery('#contact-form').submit(function(e){
e.preventDefault();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var subject = jQuery('#subject').val();
var message = jQuery('#message').val();
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: "POST",
data:{
action: 'send_email',
name: name,
email: email,
subject: subject,
message: message,
},
success:function(res){
alert("Email Sent.");
}
});
});
</script>
<?php
}
add_action( 'wp_ajax_send_email', 'deliver_mail' );
add_action( 'wp_ajax_nopriv_send_email', 'deliver_mail' );
function deliver_mail() {
require_once "wp-includes/class-phpmailer.php";
if (isset($_POST["cf-submitted"])) {
// sanitize form values
$name = sanitize_text_field( $_POST["cf-name"] );
$email = sanitize_email( $_POST["cf-email"] );
$subject = sanitize_text_field( $_POST["cf-subject"] );
$message = esc_textarea( $_POST["cf-message"] );
// get the blog administrator's email address
//$to = "email@gmx.com";
$headers = "From: $name <$email>" . "\r\n";
// Localhost
$mail = new PHPMailer(true);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "mail.gmx.com"; // sets GMX as the SMTP server for example: mail.gmx.com
$mail->Port = 465; // set the SMTP port for the GMX server
$mail->Username = $email;
$mail->Password = 'pass';
$mail->SetFrom($email, $name);
$mail->AddAddress($email);
$mail->Subject = $subject;
$mail->MsgHTML($message);
$headers .= "Content-Type: text/html; charset=utf-8";
$headers .= "Content-Transfer-Encoding: 8bit";
try {
$mail->send();
$msg = "An email has been sent for verfication.";
$msgType = "success";
wp_safe_redirect( home_url(), 302 );
exit();
} catch (Exception $ex) {
$msg = $ex->getMessage();
$msgType = "warning";
wp_safe_redirect( home_url(), 302 );
exit();
}
add_action( 'init', function() {
if ( ! empty( $_POST['form_submitted'] ) ) {
deliver_mail();
}
});
function cf_shortcode() {
ob_start();
//deliver_mail();
html_form_code();
//ob_end_flush();
return ob_get_clean();
}
add_shortcode( 'contact_form_second', 'cf_shortcode' );