I was tried to make JQuery AJAX post variable to custom php file in WordPress. But it doesn't work at all.
$column_filter_text = $_POST['filtertext'];
Javascript success but returns undefined value. Actually the variable was not passing from JQuery AJAX to Php file. The following are the code below:
database-table-data.php in the WordPress theme folder.
<?php
require_once('../../../wp-config.php');
require_once("../../../wp-load.php");
global $wpdb;
$column_filter_text = $_POST['filtertext'];
echo "<script>console.log('php post variable: '" . $column_filter_text . ");</script>";
$result = $wpdb->get_results ("
SELECT " . $column_filter_text . " FROM wpgw_wpdatatable_1");
foreach ( $result as $row )
{
echo $row . "<br>";
$return_arr[] = array("filter_column_data" => $row);
}
echo json_encode($return_arr);
?>
Javascript file code:
columnfiltertext = "bmc";
jQuery.ajax({
url: "https://********.com/wp-content/themes/oceanwp/database-table-data.php",
method: "post",
//data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
data: { filtertext: "bmc" }, //"column_filter_number":column_filter_number},
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var filter_column_data = response[i].filter_column_data;
//alert(filter_column_data);
console.log(i + ":" + filter_column_data);
}
},
error: function() {
alert('Not OKay');
}
});
});
});
This is the right way to getting data from the database
Add this code to the function.php theme file
<?php
function database_table_data()
{
global $wpdb;
$column_filter_text = $_POST['column_filter_text'];
$result = $wpdb->get_results ("SELECT " . $column_filter_text . " FROM wpgw_wpdatatable_1");
if($result){
echo json_encode($result);
} else {
echo json_encode('record not fount');
}
wp_die();
}
add_action('wp_ajax_database_table_data', 'database_table_data');
add_action('wp_ajax_nopriv_database_table_data', 'database_table_data');
?>
Javascript file code:
<script>
(function ($) {
$('button').click(function (e) {
e.preventDefault();
var columnfiltertext = "bmc";
$.ajax({
type: "post",
url: "https://********.com/wp-admin/admin-ajax.php?action=database_table_data",
data: { column_filter_text: columnfiltertext },
dataType: "json",
success: function (response) {
console.log(response)
}
});
});
})(jQuery)
</script>
Related
I want the list all the details from tow tables using single id without refreshing the Page using Ajax
This is my button and div:-
<button id="brand" data-b_id="21">brand</button>
<div id="#showdata"></div>##
This is my javascript:-
$('#brand').click(function() {
show_product();
function show_product() {
var b_id = $('#brand').data('b_id');
//alert(bid);
$.ajax({
type: 'POST',
url: '<?php echo base_url('index.php/Airtel/get_bdid')?>',
dataType: 'JSON',
data: {
b_id: b_id
},
success: function(data) {
var html = '';
var i;
for (i = 0; i < data; i++) {
html += '<tr>' +
'<td>' + data[i].b_name + '</td>' +
'<td>' + data[i].d_name + '</td>' +
'<td>' + data[i].d_id + '</td>';
};
$('#showdata').html(html);
}
});
}
});
This is my controller:-
public function get_bdid(){
$b_id=$this->input->post('b_id');
$data=$this->mymod->get_bdid($b_id);
echo json_encode($data);
}
This is my model:-
public function get_bdid($b_id){
$this->db->where('b_id',$b_id);
$this->db->select('*');
$this->db->from('brand');
$this->db->join('dth', 'dth.b_name = brand.b_name');
$query = $this->db->get();
return $query->result();
}
Perhaps, there are many errors in browser developer mode.
plz Check your javascript
success: function(data) {
console.log(data);
}
"get_bdid" controller is retrun "json" data type
success: function(data) {
var obj = JSON.parse(data);
console.log(obj);
// or loop
}
I want to loop a table in json,
my return value is
Array(
[0]Array(
[m_id]=>2
[event_id]=>37
[activity_id]=>20
)
[1]Array(
[m_id]=>20
[event_id]=>3
[activity_id]=>2
)
)
my script is
function get_out_mail(user_name){
var datastring = 'user_name=' + user_name;
alert(datastring);
var a = false;
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url(); ?>admin/get_out_mails",
data: datastring,
cache: false,
success: function (result) {
alert(result);
var result = $.parseJSON(result);
console.log(result.from);
$('#myTable').html('');
$("#myTable").append('<tbody><?php foreach ($get_all_mail as $get_all_mails) { ?><tr id="target-list"><td><input type="checkbox" id="mail-checkbox-1" class="custom-checkbox"></td><input type="hidden" name="mid" value="<?php echo $get_all_mails['m_id']; ?>"/><td><i class="glyph-icon icon-star"></i></td><td class="email-title" ><?php echo $get_all_mails['from']; ?></td><td class="email-body" ><?php echo $get_all_mails['subject'] ?></td><td><i class="glyph-icon icon-paperclip"></i></td><td>17 Jan 2014</td></tr><?php } ?></tbody>');
}
});
return a;
}
my controller
public function get_out_mails(){
if ($this->session->userdata('admin_logged_in')) {
$user_name = $this->input->post('user_name');
$result['out_mail'] = $this->admin_model->get_out_mailss($user_name);
print_r($result['out_mail']);
}
Here I want to append my return array value in json using foreach loop, how can I do this.
It is ajax request It is better to return complete html part in controller instead of appending in the View page :
Example controller :
echo $values ="<body>
<tr> test</tr>
</body>";
View : Success : function(data){
$('#id').html(data);
}
With that you will hide the complete loop from the view page and get the code in controller
Replace your controller function with this:
public function get_out_mails(){
if ($this->session->userdata('admin_logged_in')) {
$user_name = $this->input->post('user_name');
$result['out_mail'] = $this->admin_model->get_out_mailss($user_name);
$data = '<tbody>';
foreach ($get_all_mail as $get_all_mails) {
$data .= '<tr id="target-list"><td><input type="checkbox" id="mail-checkbox-1" class="custom-checkbox"></td><input type="hidden" name="mid" value="'.$get_all_mails['m_id'].'"/><td><i class="glyph-icon icon-star"></i></td><td class="email-title" >'.$get_all_mails['from'].'</td><td class="email-body" >'.$get_all_mails['subject'].'</td><td><i class="glyph-icon icon-paperclip"></i></td><td>17 Jan 2014</td></tr>';
}
$data .= '</tbody>';
echo $data;
}
And, replace your script with this:
function get_out_mail(user_name){
alert(datastring);
var a = false;
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url(); ?>admin/get_out_mails",
data: {'user_name': user_name},
cache: false,
success: function (result) {
alert(result);
var result = $.parseJSON(result);
console.log(result.from);
$('#myTable').html(result);
}
});
return a;
}
JS
<script type="text/javascript">
function myfunction(course_id, subject_id) {
var site_url = '<?php echo site_url(); ?>';
var ajaxurl = site_url + "/wp-admin/admin-ajax.php";
alert(ajaxurl);
var data = {
action: 'example_ajax_request'
};
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
}
</script>
PHP
add_action('wp_ajax_example_ajax_request', 'insert_data_customtable' );
add_action('wp_ajax_nopriv_example_ajax_request','insert_data_customtable');
function insert_data_customtable()
{
$result="hi";
echo $result;
exit(0);
}
Can you elaborate the question a little bit. You have passed parameters to functions where are from they coming.
echo json_encode($result);
echo $result;
it will display the value stored in it
Right, i only want a very simple ajax request to get this working. im new with yii 2.0 framework you see.
in my view index.php:
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { test: test },
success: function(data) {
alert(data);
}
});
}
Now when i call this i assume that it should go to my CasesController to an action called actionAjax.
public function actionAjax()
{
if(isset($_POST['test'])){
$test = "Ajax Worked!";
}else{
$test = "Ajax failed";
}
return $test;
}
EDIT::
Ok great, so this works up to here. I get back the alert that pops up with the new value for $test. However i want to be able to access this value in php as ultimately i will be accessing data from a database and ill be wanting to query and do various other things.
So how do i now use this variable in php instead of just the pop up alert()?
Here is how you can access the post data in controller:
public function actionAjax()
{
if(isset(Yii::$app->request->post('test'))){
$test = "Ajax Worked!";
// do your query stuff here
}else{
$test = "Ajax failed";
// do your query stuff here
}
// return Json
return \yii\helpers\Json::encode($test);
}
//Controller file code
public function actionAjax()
{
$data = Yii::$app->request->post('test');
if (isset($data)) {
$test = "Ajax Worked!";
} else {
$test = "Ajax failed";
}
return \yii\helpers\Json::encode($test);
}
//_form.php code
<script>
$(document).ready(function () {
$("#mausers-user_email").focusout(function () {
sendFirstCategory();
});
});
function sendFirstCategory() {
var test = "this is an ajax test";
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->getUrlManager()->createUrl('cases/ajax') ; ?>",
data: {test: test},
success: function (test) {
alert(test);
},
error: function (exception) {
alert(exception);
}
})
;
}
</script>
You can include js this way in your view file:
$script = <<< JS
$('#el').on('click', function(e) {
sendFirstCategory();
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: "<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>",
data: {test: test},
success: function(data) {
alert(data)
}
});
}
I have a anchor;
When I click on it, the following code executes:
<script>
$('.viewcnp').click(function() {
event.preventDefault();
var r = prompt("Enter your password:");
if (r) {
$.ajax({
type: "POST",
url: '<?php echo Yii::app()->baseUrl; ?>' + '/index.php/admin/user/viewCnp/id/' + '<?php echo $model->id; ?>',
data: {'password': r},
success: function(data) {
$('.cnpdecrypted').text(data);
},
dataType: 'text'
});
}
});
</script>
this code makes a request to this action:
public function actionViewCnp($id) {
$model = User::model()->findByPk($id);
if ($model) {
return '{"data":"' . Utils::decrypt_cnp($model->cnp) . '"}';
}
else
return false;
}
If in the action I echo the cnp decripted, its there, but i can't set the value because I don't receive it on success.
You should simply use echo instead of return :
if ($model) {
echo Utils::decrypt_cnp($model->cnp);
}