javascript variable pass into php - javascript

I get category id by js and want to use it to get category description.
when i am passing this id using ajax into php variable its print correct output but when i try to put this id in get_description code ajax give 500 error and not return output why this happen please help me.
Below is my code.
<script type="text/javascript">
$(".-filter").click(function() {
var js_var = this.id;
$.ajax ({
type: "POST",
url: "<?php echo plugin_dir_url( __FILE__ ); ?>category.php",
data: { val : js_var },
success: function( result ) {
$("#update").html(result);
}
});
});
</script>
<div id="update">
<?php
$cat_id = $_POST['val'];
echo $cat_id;
//echo term_description($cat_id,'category');
?>`enter code here
</div>
Thanks,

Related

Adding $var from php to this JavaScript

I have used this script to set an order.
<script type="text/javascript">
$( "#post_list" ).sortable({
placeholder : "ui-state-highlight",
update : function(event, ui)
{
var post_order_ids = new Array();
$('#post_list li').each(function(){
post_order_ids.push($(this).data("post-id"));
});
$.ajax({
url:"ajax_upload.php",
method:"POST",
data:{post_order_ids:post_order_ids ,var_i_want:<?php print $var_i_used;?>},
success:function(data)
{
if(data){
$(".alert-danger").hide();
$(".alert-success ").show();
}else{
$(".alert-success").hide();
$(".alert-danger").show();
}
}
});
}
});
</script>
Now i would like to add a $var (set in php) to be send with it to ajax_upload.php
I am not familiar with javascript. Is this possible?
EDIT:
Got it line is updated how it works.
Thnx.
You need to specify where you want to add this variable exactly, otherwise you can pre-render js variable from server side using php like this :
your other code <?php echo "var var_name = var_value;"; ?> your other code
Before $.ajax({, you should get the php value. e.g.
var variable_name = '<?php echo $var?>';
after that you can set the variable in data:
data:{post_order_ids:post_order_ids,var:variable_name},
Here is one way to do that:
$.ajax({
url:"ajax_upload.php",
method:"POST",
data:{
post_order_ids:post_order_ids,
myVarFromPhp: <?php echo (($var) ? $var : "null"); ?>
},
...

ajax send and get data to/from controller mvc

This is my script:
<script>
$(document).ready(function(){
$("#ID_Blangko").on("change", function() {
var blangko = $("#ID_Blangko").val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah';
$.ajax({
url: baseUrl,
data: {nama : blangko},
dataType: "json",
success: function(datas){
$("#Jumlah_Blangko").val(datas);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#Jumlah_Blangko').val("some error.");
}
});
});
});
</script>
and this is my controller code:
public function ajax_jumlah($nama)
{
$this->db->select('Jumlah_Blangko');
$this->db->where('Nama_Blangko', $nama);
$result = $this->db->get('tb_blangko');
$amount = $result->row()->Jumlah_Blangko;
return json_encode($amount, JSON_NUMERIC_CHECK);
}
i've double checked the onchange function and controller function is working well and returning value. The problem is I cant pass this value to my ajax code and print it on input form. Here's my html:
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="row">
<div class="col-md-6">
<?php
$atribut_blangko = 'class="form-control" id="ID_Blangko"';
$selectedBlangko = $values->ID_Blangko;
echo form_dropdown('ID_Blangko', $dropdown_Blangko, $selectedBlangko, $atribut_blangko);
?>
</div>
<div class="col-md-6">
<?php echo form_input('Jumlah_Blangko', '', 'id="Jumlah_Blangko" class="form-control" placeholder="Jumlah" maxlength="50" readonly="true"') ?>
</div>
</div>
<?php echo form_close() ?>
update #2 and this solve my problem
this the controller function im accessing directly from browser URL that is http://localhost/amc/program/administrasi/blangko_rusak/ajax_jumlah/Malaysia
and i found out that
return json_encode($amount, JSON_NUMERIC_CHECK); this doesnt work and then i changed to:
echo json_encode($amount, JSON_NUMERIC_CHECK); this work.
I dont know how this is possible, anyone can explain?
Please check the line no 3 in your code it should be "$("#ID_Blangko").val()" instead of "$("#ID_Blangko").val"
Explanation:
in the above code line you were expecting to get the value of the element having id "ID_Blangko" and you are using the jQuery, but the main thing here is that the "val" is a function and not a variable so you can not access the value by just saying "$("#ID_Blangko").val" because it looks for a property named as 'val'
I think
var blangko = ID_Blangko.value;
should be
var blangko = $('#ID_Blangko').val();
or
var blangko = $(this).val();
EDIT
Your problem with controller/action not seeing the variable could be because it expects params instead of query string vars like most frameworks do. Something like this could help you with that
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah/' + blangko;

Wordpress AJAX doesn't work - response 0

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);
?>

update DB with onClick

i try to update the status of a messae in my pm's by only clicking the read button on my page. so i found some solution here on this site, but it doesn't really work for me.
i use this ajax before the html button:
<script type="text/javascript">
function setRead(){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { name: $("select[name='gelesen']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
</script>
the button is styled css and uses it's own javascript to toggle the content (open/close)
so i want to update the status by opening the message
<span class="toggleOpen" onclick="setRead()"><input type="hidden" method="post" name="gelesen" value="<?php echo $row['id']; ?>">lesen</span>
the included site is
<?php
ini_set('include_path', 'inc');
require("connect.php");
{
$id = $_POST['id'];
$sql = "UPDATE
PMS
SET
gelesen = 'yes'
WHERE id = '".mysql_real_escape_string($id)."' AND gelesen = 'no'";
mysql_query($sql) OR die("<pre>\n".$sql."</pre>\n".mysql_error());
}
but i get always the notice of the undefined variable 'id'.
how can i give this variable to the included site?
because i have to wait 8 hours before i can reply i edit my post:
thanks for the answer but i still get the message of a undefined index: name
so the variable is not postet to my update_pm_staus.php
ihave updated my script to this:
<script type="text/javascript">
function setRead(){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $(this).children("[name='gelesen']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
and the update_pm_status.php to this:
ini_set('include_path', 'inc');
require("connect.php");
$id = $_POST['name'];
$sql = "UPDATE
PMS
SET
gelesen = 'yes'
WHERE id = '".mysql_real_escape_string($id)."' AND gelesen = 'no'";
mysql_query($sql) OR die("<pre>\n".$sql."</pre>\n".mysql_error());
i also changed my html like this in hope to bring it to work.
<span class="toggleOpen" onclick="setRead()" input type="hidden" method="post" name="gelesen" value="<?php echo $row['id']; ?>">lesen</span>
It looks as though you are sending the id correctly, but you are sending it as name. You'd want to update your JavaScript to pass the key:value pair that you're expecting, with the key name that you expect in your PHP.
<script type="text/javascript">
function setRead(){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $(this).children("[name='gelesen']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
</script>
You'll notice that in the data: {} block of the AJAX request, I've updated your key:value pair to be named id, rather than name. If you do what your key to be named name when POST'ing, then you'd want to update your PHP to look for that:
$id = $_POST['name'];
sorry for the late response. i got the to work. i use
<script type="text/javascript">
function setRead($id){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $id}
}); }
and the html like this
onclick="setRead(this.id);
thanks for to all helping me out :)

ajax not able to pass variable to php

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

Categories