Cannot populate select fields with AJAX in Wordpress - UPDATE - javascript

UPDATE: My ajax function for handling the response is correct, but I have a hard time to iterate through the response object and populate the select field. I've tried and with for loop instead of each() and is working better but the select field was populated with "undefined". Any ideas?
Below is my Jquery code
jQuery(document).ready(function() {
// Avoid conflicts
$ = jQuery;
$('#nomoi-select').change(function() {
var nomos_name = $('#nomoi-select option:selected').attr('id');
var jsonMimeType = "application/json;charset=UTF-8";
type = 'POST';
data = { 'parent_id': nomos_name, action : 'get_child_categories' };
dataType = 'json';
contentType = "application/json; charset=utf-8";
processData = false;
$.post( ajaxurl, data, function(response) {
if( response ){
console.log(response);
var content = '';
var data = JSON.stringify(response);
$(data).each(function(key, value) {
content += '<option>' + value + '</option>';
});
$(content).appendTo("#town-select");
}
});
}).change();
});
My ajax function:
function get_child_categories() {
if (isset($_POST['parent_id'])) {
$parent_id = ($_POST['parent_id']);
$result = array();
$args = array(
'post_type' => 'seller',
'order_by' => 'name',
'hide_empty' => 0,
'exclude' => 1,
'taxonomy' => 'nomos',
'hierarchical' => 1,
'child_of' => $parent_id
);
$categories = get_categories( $args );
foreach ( $categories as $cat ) {
$result = array(
'town_id' => $cat->cat_ID,
'town_name' => $cat->cat_name
);
echo json_encode($result);
}
}
die();
}
add_action('wp_ajax_get_child_categories', 'get_child_categories');
add_action('wp_ajax_nopriv_get_child_categories', 'get_child_categories');
The OnChange is working fine and I get the following output from log:
{"town_id":"41","town_name":"\u0391\u0393\u0393\u0395\u039b\u039f\u039a\u0391\u03a3\u03a4\u03a1\u039f"}{"town_id":"42","town_name":"\u0391\u0393\u03a1\u0399\u039d\u0399\u039f"}{"town_id":"40","town_name":"\u0391\u0399\u03a4\u03a9\u039b\u0399\u039a\u039f"}{"town_id":"84","town_name":"\u0391\u039b\u03a5\u0396\u0399\u0391"}{"town_id":"85","town_name":"\u0391\u039c\u03a6\u0399\u039b\u039f\u03a7\u0399\u0391"}{"town_id":"86","town_name":"\u0391\u039d\u0391\u039a\u03a4\u039f\u03a1\u0399\u039f"}{"town_id":"87","town_name":"\u0391\u039d\u03a4\u0399\u03a1\u03a1\u0399\u039f"}{"town_id":"88","town_name":"\u0391\u03a0\u039f\u0394\u039f\u03a4\u0399\u0391"}{"town_id":"89","town_name":"\u0391\u03a1\u0391\u039a\u03a5\u039d\u0398\u039f\u03a3"}{"town_id":"90","town_name":"\u0391\u03a3\u03a4\u0391\u039a\u039f\u03a3"}{"town_id":"91","town_name":"\u0398\u0395\u03a1\u039c\u039f"}{"town_id":"92","town_name":"\u0398\u0395\u03a3\u03a4\u0399\u0395\u03a9\u039d"}{"town_id":"93","town_name":"\u0399\u0395\u03a1\u0391\u03a3 \u03a0\u039f\u039b\u0397\u03a3 \u039c\u0395\u03a3\u039f\u039b\u039f\u0393\u0393\u0399\u039f\u03a5"}{"town_id":"94","town_name":"\u0399\u039d\u0391\u03a7\u039f\u03a5"}{"town_id":"95","town_name":"\u039c\u0391\u039a\u03a1\u03a5\u039d\u0395\u0399\u0391\u03a3"}{"town_id":"96","town_name":"\u039c\u0395\u0394\u0395\u03a9\u039d\u039f\u03a3"}{"town_id":"97","town_name":"\u039c\u0395\u039d\u0399\u0394\u0399\u039f\u03a5"}{"town_id":"98","town_name":"\u039d\u0391\u03a5\u03a0\u0391\u039a\u03a4\u039f\u03a5"}{"town_id":"99","town_name":"\u039d\u0395\u0391\u03a0\u039f\u039b\u0397\u03a3"}{"town_id":"100","town_name":"\u039f\u0399\u039d\u0399\u0391\u0394\u03a9\u039d"}{"town_id":"101","town_name":"\u03a0\u0391\u039b\u0391\u0399\u03a1\u039f\u03a5"}{"town_id":"102","town_name":"\u03a0\u0391\u039d\u0391\u0399\u03a4\u03a9\u039b\u0399\u039a\u039f\u03a5"}{"town_id":"103","town_name":"\u03a0\u0391\u03a1\u0391\u0392\u039f\u039b\u0391\u03a3"}{"town_id":"104","town_name":"\u03a0\u0391\u03a1\u0391\u039a\u0391\u039c\u03a0\u03a5\u039b\u0399\u03a9\u039d"}{"town_id":"105","town_name":"\u03a0\u039b\u0391\u03a4\u0391\u039d\u039f\u03a5"}{"town_id":"106","town_name":"\u03a0\u03a5\u039b\u039b\u0397\u039d\u0397\u03a3"}{"town_id":"107","town_name":"\u03a3\u03a4\u03a1\u0391\u03a4\u039f\u03a5"}{"town_id":"108","town_name":"\u03a6\u03a5\u03a4\u0395\u0399\u03a9\u039d"}{"town_id":"109","town_name":"\u03a7\u0391\u039b\u039a\u0395\u0399\u0391\u03a3"}

Taking the hint from Tom Kriek:
You could always build all of the tags inside the php
script,and then return that to the function. This saves you iterating
it on the ajax side. All you have to do then is stick the html in the
right spot. Namely in the select tag.
I've used $(#town-select).html(response); in the JQuery response and worked perfectly. Thanx everybody!

Related

AJAX load more function multiplies the old data?

I have a PHP code that creates a JSON data from wordpress posts in the database.
I load this JSON on my html page using AJAX.
The above works fine.
Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.
So this my AJAX code for loading more:
var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
$.ajax({
url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
dataType: 'json',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
if (!$.trim(data)) {
}
else {
}
$.each(data, function (pi, item) {
var id = item.id;
var img = item.img;
var title = item.title;
var date_added = item.date_added;
var item = '' + title + '';
$('.myDiv').before(item);
i++;
});
},
error: function () {
//error handling////
}
});
});
And this is my PHP code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
$t = $_GET['t'];
$page = $_GET['page'];
$posts = get_posts(array(
'posts_per_page' => $page, //add -1 if you want to show all posts
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $t //pass your term name here
)
))
);
$output= array();
foreach( $posts as $post ) {
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$mysqldate = $post->post_date;
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'F d Y', $phpdate );
// Pluck the id and title attributes
$output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
}
echo json_encode( $output );
When I click on the 'Load More' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.
I know I am missing something in my PHP code but I couldn't figure out what.
Could someone please advice on this issue?
Thanks in advance.
The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.
The parameter your want to set as your $page parameter is "paged".
Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6
https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
You could also use WP API instead of rolling your own

Codeigniter if data inserted return true to json again ? it's possible?

I'm using json to post data to controller but i can't do some effects if data is inserted to database successfully,
This if statement does not work in this javascript code ?
I mean .like-btn .html() does not work but data inserted in database ?
My experience in Javascript between 0 and 10 :D
Using Codeigniter 3.0.3
Here's my javascript
<script type="text/javascript">
$(document).ready(function() {
$(".like-btn").click(function(event) {
var liker_id = "<?php echo $this->session->userdata('id'); ?>";
var post_id = $(this).attr('post-id');
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('home/AddLike'); ?>",
dataType: 'json',
data: {liker_id: liker_id, post_id: post_id},
success: function(res) {
if (res)
{
$('.like-btn[post-id = '+post_id+']').html('<span class="fa fa-check"></span> Liked');
}
}
});
});
});
</script>
Here's my controller
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
}
And here's my model method
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
return true;
}
}
Just change below on your model:
change return to echo
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
echo true;
}
}
You should debug your code of ajax response. And you should check whether you are getting any response in res variable.
Important
1)In if condition you should use double quotes("") to wrap variable post_id like
$('.like-btn[post-id = "'+post_id+'"]').html...
2) Another thing is you should return "true" as string not as boolean and check with string in ajax success block.
Solved add this line at the end of controller method
echo true;
code after edit
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
echo true;
}

PHP function not getting called through ajax

I have ajax call to PHP function as :
$.ajax({
url: 'Link',
type: 'POST',
dataType : 'json',
data: {'txtFromOrderDate' : '2014-08-01','txtToOrderDate' : '2014-08-05'},
success: function() {
window.location = 'Link';
}
});
PHP function as:
public function createZipAction($txtFromOrderDate,$txtToOrderDate)
{
date_default_timezone_set('Australia/Melbourne');
$date = date('m:d:Y H:i:s', time());
$exportBatch = $date;
$order = $this->getTableGateway('order');
$select = new Select();
$select->from('order')
->join('user', 'order.user_id = user.id', array('email'))
->where ("order.created between ".$txtFromOrderDate." and '2014-08-03' ");
//->where ('order.created between '.$txtFromOrderDate.' and '.$txtToOrderDate);
$data = $order->selectWith($select)->toArray();
$batchDir = __DIR__ . '/../../../../../data/export/batch/' . $exportBatch;
if(is_dir($batchDir) == false)
mkdir($batchDir);
$csvFile = fopen($batchDir . '/order.csv', 'w');
$i = 0;
foreach($data as $record) {
if($i==0) fputcsv($csvFile, $this->getCsvHeader($record));
fputcsv($csvFile, $this->updateCsvLine($record));
$pngTmpFile = $this->saveTmpImage($record['plate_id']);
$this->savePlatePdf($pngTmpFile, $exportBatch, $record['id']);
unlink($pngTmpFile);
$i++;
}
fclose($csvFile);
$filter = new \Zend\Filter\Compress(array(
'adapter' => 'Zip',
'options' => array(
'archive' => $batchDir . '.zip'
)
));
$filter->filter($batchDir);
$fileToDownload=$batchDir . '.zip';
$this->downloadOrderCSVAction($fileToDownload);
echo "exported: $i records.";
die();
}
Here when i supply dates to this function, Its not getting dates.
But when i write dates hard-code in php function as:
$txtFromOrderDate='2014-08-01'
$txtToOrderDate='2014-08-05'
Then further function works as expected.
what can be the issue???
Please help me.
When you POST to PHP (via AJAX in your case), those data variables are not set as globals. They are set in the $_POST array.
You can use them directly or set them to your global variables (just ensure you check they exist before-hand).
if (isset($_POST['youVariable')) {
$yourVariable = $_POST['yourVariable'];
}

Passing variables from PHP to AJAX success function

My aim is to update a WordPress post using AJAX. My code so far:
Script:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.
I want to modify my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.
Can anyone let me know how to pass $response and $error to my script's success function?
Is there a better approach I should be taking?
I'm newish to AJAX so forgive me if the question is very basic.
You shoud encode the response of the php script as json, as follows:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
You can create a JSON array like this one, in the backend:
$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);
And then parse the json array to fetch the returned values, like this:
success: function( data ) {
var error = '';
var something = '';
for(var i = 0; i < data.length ; i++)
{
error = data[i].error;
something = data[i].something;
}
if( error ) {
// do something
} else {
// do something else
}
},
Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.
Note that there might be a syntax error, since I'm not testing it.
What you are looking for is json_encode()
This converts a PHP array to JSON.
For example:
$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);
You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.
For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).
if you use:
echo json_encode($response);
on your .php function, remember to use:
var data = $.parseJSON(data);
on your ajax success.
Example:
function php_ajax_function() {
// whatever you want to do...
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
console.log(data);
var data = $.parseJSON(data);
if( data.status == 'error' ) {
// do something
} else {
// do other thing
}
}
the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/
success: function( data ) {
if( data == 'This failed' ) {
// do something
} else {
// do something else
}
},

jQuery.ajax Why not access the item from php json_encode?

I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?

Categories

Resources