I work with ajax in wordpress, I want to show what the user enters,
the success of ajax is sent to the server, but the POST array issues
an indefinite index in my index.php, why doesn't it work?
inc/send.php
<?php
add_action( 'wp_ajax_applican', 'applican');
add_action( 'wp_ajax_nopriv_applican', 'applican');
function applican(){
$v3 = $_POST['v3'];
};
?>
/js/custom.js
let arr = [];
btnNext.on('click', () => {
if(roomsRadio.is(':checked')) {
calc.slick('slickNext');
arr['version1'] = $('.rooms input[type="radio"]:checked').val();
console.log(arr['version1'])
}
if(versionRadio.is(':checked')) {
calc.slick('slickNext');
arr['version2'] = strip_html_tags($('.version input[type="radio"]:checked').val());
console.log(arr['version2'])
}
if(typeRadio.is(':checked')) {
calc.slick('slickNext');
arr['version3'] = strip_html_tags($('.type input[type="radio"]:checked').val());
console.log(arr['version3'])
$.ajax({
type: "POST",
dataType:'json',
url: "/wp-admin/admin-ajax.php",
data: {"action": "applican", "v3": arr['version3'], "v2": arr['version2'], "v1": arr['version1']},
success: function(msg) {
alert( "Data Saved: " + msg );
},
error: function () {
console.log({"v3": arr['version3']});
}
})
}
index.php
<?php applican(); echo $v3; ?>
Like Magnus said, variables in PHP have different scopes Variable scope, You can't reach it out of the scope. In your code, $v3 can only be reached inside the function applican(), but not index.php. You can extend the variable's scope with keyword global:
<?php # inc/send.php
function applican(){
global $v3;
$v3 = $_POST['v3'];
};
Or other solution like:
<?php # inc/send.php
function applican(){
return $_POST['v3'];
};
<?php # index.php
$v3 = applican(); echo $v3;
Related
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.
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console
I want add AJAX support to my plugin and I have huge problem with this simple thing. WordPress isn't permitting me to use normal AJAX and I need to use WordPress version.
At all times, the WordPress function (that should generate output) returns 0. And I think that the reason is that WP doesn't trigger 'function'. I try to force the function to run many times, but I don't have any idea what I can improve.
<?php
public function widget( $args, $instance ) {
$options = get_option('Free_Quotation_options');
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery.ajax({
url: ajaxurl,
type: 'POST',
action: 'fqtag',
data: {
'whatever': 'text'
},
success: function (output) {
$('#secondary').append(output);
}
});
});
</script>
<?php
add_action( 'wp_ajax_fqtag', 'fqtag' );
add_action( 'wp_ajax_nopriv_fqtag', 'fqtag' );
function fqtag() {
global $wpdb;
echo 'echo';
die();
}
}
I try to add alert('echo'); to the test function, but it doesn't have any effect. I think that AJAX doesn't run the proper function: fq_tag_support_callback() .
On the beginning I had a problem with ajaxurl variable. It was not defined. It's not a normal situation. I attempt to resolve this problem by using:
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
Do you have any idea, how can I try to solve this problem?
---EDIT--- After discussion with David I have file like this (all time doesn't work)
<?php
/*
Plugin Name: TEST PLUGIN
Description: TEST
Author: Krzysztof Kubiak
Version: 1.0
*/
function Test_01_settings_init(){
register_setting( 'Test_01_settings_filed', 'Test_01_options', 'Test_01_validate' );
}
add_action('admin_init', 'Test_01_settings_init' );
function T01_init_method() {
wp_enqueue_script('jquery');
}
add_action('init', 'T01_init_method');
function Test_01_menu_page(){
add_menu_page( 'Test_01', 'Test_01', 'manage_options', 'T01_menu_page', 'T01_add_page' );
echo my_test();
}
add_action('admin_menu', 'Test_01_menu_page');
function my_test(){
echo 'Function test';
}
function T01_add_page() {
echo 'TEST_01_plugin';
}
function Test_01_validate($input) {
}
//AJAX FROM HIRE
function test_callback() {
$whatever = 8;
echo $whatever;
die();
}
add_action( 'wp_ajax_nopriv_fqtag', 'test_callback', 1 );
add_action( 'wp_ajax_fqtag', 'test_callback', 1 );
function print_js() { ?>
<script type="text/javascript">
jQuery.ajax({
url: 'wp-admin/admin-ajax.php',
type: 'POST',
action: 'fqtag',
data: {
'whatever': 'text'
},
success: function (output) {
alert(output);
}
});
</script>
<?php
}
add_action('wp_print_footer_scripts', 'print_js', 1000);
?>
remove
<script>alert('echo');</script>
your response should be echo if you check your console. I suspect all the above code is in your plugin functions file. Basically the php function should be placed in the functions file.
The jquery should be placed in the template from which you want to receive the response.
Place this in your functions file...remove the jquery from the class...
add_action('wp_print_footer_scripts', 'print_js', 1000);
function print_js() { ?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery.ajax({
url: 'wp-admin/admin-ajax.php',
type: 'POST',
data: {
'action': 'test_callback',
'whatever': 'text'
},
success: function (output) {
alert(output);
}
});
});
</script>
<?php
}
Move this outside your class...
function test_callback() {
$whatever = 8;
echo $whatever;
die();
}
add_action( 'wp_ajax_nopriv_testaction', 'test_callback' );
add_action( 'wp_ajax_testaction', 'test_callback' );
Just make sure that you have put the function 'fq_tag_support_callback()' in your plugin's main file.
I see few problems here. Action should inside the data object, not as a jQuery Ajax parameter. Also in the callback function data is stored in $_POST variable.
function test_callback() {
$whatever = $_POST['whatever'];
echo $whatever;
die();
}
add_action('wp_ajax_nopriv_fqtag', 'test_callback');
add_action('wp_ajax_fqtag', 'test_callback');
function print_js() {
?>
<script type="text/javascript">
jQuery.ajax({
url: <?php echo admin_url('admin-ajax.php'); ?>,
type: 'POST',
data: {
action: 'fqtag',
whatever: 'text'
},
success: function (output) {
alert(output);
}
});
</script>
<?php
}
add_action('wp_print_footer_scripts', 'print_js', 1000);
?>
I'm trying to make an ajax call to get result from my database, but i'm facing an error.
My javascript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="Javascript">
setTimeout(makeAjaxCall, 1000);
function makeAjaxCall(){
$.ajax({
type: "post",
url: "call/update",
cache: false,
data: {action: 'getUpdate', term: '<?php echo $id;?>'},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS'] + obj['results']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
</script>
And my controller's method:
public function update()
{
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData();
}
}
function pollNewData(){
$term = $_POST['term'];
$query = $this->db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
i have this error on chrome debugs tool:
500 (Internal Server Error)
You have several issues. Below is the working code:
public function update()
{
if(!function_exists('pollNewData')){ // don't redeclare if already exists
function pollNewData($db){ // pass $db
$term = $_POST['term'];
$query = $db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData($this->db); // pass $this->db
}
}
}
Changes:
Moved the function definition to before it is called - it must exist before calling.
The $this context is not set in the function, so pass the $db object as an argument.
When defining functions inside a class method, you must have a function_exists() check because on the second call, it will try to redeclare the function and produce a fatal error.
For future debugging you should turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some suggestions:
url: "<?php echo base_url();?>call/update",
//pollNewData();
echo $this->pollNewData(); //call like this and echo it out to the ajax
//echo json_encode(array('STATUS'=>200, 'results'=>$res));
return json_encode(array('STATUS'=>200, 'results'=>$res)); //return it instead to the calling function
I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" onclick="loadXMLDoc()">Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?
In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData