PHP & JavaScript - Variables - javascript

I just basically have a View with an Associative Array with Accidents Information.
The User will be able to click in the Country. When that happen I want to show them the information about accidents related with that country.
That information comes from PHP and the Click event is captured in JQuery...
How Can I insert the var country inside the index of the
associative array that came from PHP with an Index for each country?
.on('click', function(i, row) {
var country = row.label;
accident_chart.setData([{
a: <?php echo "".$charts['accidents_status'][**NEED var country value here**]['accidents']; ?>,
y: 'Accidents',
},
{
a: <?php echo $charts['accidents_status']['Qatar']['lost_time_accidents']; ?>,
y: 'Lost Time',
}
]);
});

You can't do that. Use AJAX instead to get the accident_chart data.
.on('click', function(i, row) {
var country = row.label;
$.ajax({
type: "GET",
url: "/get_accident_chart", // Just replace it with your PHP controller function that can access your $charts variable
data: {country: row.label},
dataType: "json",
success: function(data) {
accident_chart.setData(data);
},
error: function(data) {
return data;
}
});
});
In your PHP
get_accident_chart(){
$country = $_GET['country'];
$accident_chart = array(
array(
'a' => $charts['accidents_status'][$country]['accidents'],
'y' => 'Accidents'
),
array(
'a' => $charts['accidents_status']['Qatar']['lost_time_accidents'],
'y' => 'Lost Time'
)
);
echo json_encode($accident_chart);
}

Related

Get tag, custom taxonomy and attachment data from get_pages function

I currently have some code which retrieves all pages submitted by the currently logged in author using the get_pages function. I am then passing the result to Javascript via Ajax. Everything works as expected, and I'm retrieving the pages that I should be.
My issue is, the object does not have any data for the tags, other custom taxonomies and attachments on this page.
Is there a way to attach this data to the returned object?
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxpages = get_pages($args);
echo json_encode($ajaxpages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
}
});
At this point, each entry will return something like:
ID: 100
comment_count: "0"
comment_status: "open"
filter: "raw"
guid: "https://example.com/?page_id=100"
menu_order: 0
ping_status: "closed"
pinged: ""
post_author: "1"
post_content: "This is the post content"
post_content_filtered: ""
post_date: "2021-06-18 10:00:00"
post_date_gmt: "0000-00-00 00:00:00"
post_excerpt: "This is the excerpt"
post_mime_type: ""
post_modified: "2021-06-18 10:00:00"
post_modified_gmt: "0000-00-00 00:00:00"
post_name: ""
post_parent: 19
post_password: ""
post_status: "pending"
post_title: "Example page"
post_type: "page"
to_ping: ""
I would like it to also include data along the lines of:
tags: "example, test"
myCustomTaxonomy: "extra information, more data"
attachments: "https://example.com/wp-content/uploads/2021/06/myImage.png"
Is this possible?
In case it's useful, this is the solution I came up with. It certainly may not be efficient but it appears to suit my purposes at least.
What I ended up doing was populating a select list with each of the pages found in the first AJAX call. Selecting a page in this list then calls the second function which gets the various extra metadata for that page.
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxPages = get_pages($args);
echo json_encode($ajaxPages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
function get_ajax_meta()
{
$editId = $_POST['editId'];
$meta = [];
$editTags = get_the_tags($editId);
$editCustomTaxonomy1 = get_the_terms($editId, 'CustomTaxonomy1');
$editCustomTaxonomy2 = get_the_terms($editId, 'CustomTaxonomy2');
$media = get_attached_media('', $editId);
array_push($meta, (object)[
'tags' => $editTags,
'customTaxonomy1' => $customTaxonomy1,
'customTaxonomy1' => $customTaxonomy2,
'media' => $media
]);
echo json_encode($meta);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_meta', 'get_ajax_meta');
add_action('wp_ajax_nopriv_get_ajax_meta', 'get_ajax_meta');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
// populate the dropdown with the pages
if (pageList.length > 0) {
for (var i = 0; i < pageList.length; i++) {
$("select[name=edit-page]").append("<option value='" + pageList[i].ID + "'>" + pageList[i].post_title + "</option>");
}
}
}
});
$("body").on("change", "select[name=edit-page]", function () {
editId = $(this).val();
// get the meta information of the selected page (tags, custom taxonomies, attached files)
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { "editId": editId, action: "get_ajax_meta" },
success: function (response) {
pageMeta = response;
// get the tags
console.log(pageMeta[0].tags[i].name)
// get custom taxonomy 1 data
console.log(pageMeta[0].customTaxonomy1[i].name)
// get custom taxonomy 2 data
console.log(pageMeta[0].customTaxonomy2[i].name)
// get attached file data
if (Object.keys(pageMeta[0].media).length > 0) {
for (var i = 0; i < Object.keys(pageMeta[0].media).length; i++) {
console.log(pageMeta[0].media[Object.keys(pageMeta[i].media)[0]]);
}
}
}
});
});

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

Insert statement into custom WordPress database

I have a custom database that I want to insert items into from a WordPress front-end interface. When I submit the form, I can get the JSON values just fine, but for some reason, it doesn't seem to be inserting into the database. I do not get any error messages.
Here's what I'm doing (please note that I am testing the name variable, hence why it's not pulling from an input field):
I am using the auto_increment_id value from SHOW TABLE STATUS to create the commmittee_id value, and would prefer for that to be inserted as the primary key.
JavaScript
$(".addButton").click(function() {
var commitAddID = $(this).attr('id');
var name = "1name";
var date_created = $("#addCommCreated_input_"+commitAddID).val();
var status = $("#addCommStatus_input_"+commitAddID).val();
var disbanded = $("#addCommDisbanded_input_"+commitAddID).val();
var dataString = {
'action': 'addCommittee',
'committee_id': commitAddID,
'old_id': commitAddID,
'name': name,
'description': '',
'date_created': date_created,
'status': status,
'disbanded': disbanded
};
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
dataType: "json",
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
}
});
functions.php
// set up AJAX call for addCommittee
add_action('wp_ajax_addCommittee', 'addCommittee');
add_action('wp_ajax_nopriv_addCommittee', 'addCommittee');
function addCommittee() {
global $wpdb;
$committee_id = esc_sql($_POST['committee_id']);
$old_id = esc_sql($_POST['old_id']);
$name = esc_sql($_POST['name']);
$created = esc_sql($_POST['date_created']);
$status = esc_sql($_POST['status']);
$disbanded = esc_sql($_POST['disbanded']);
$desc= esc_sql($_POST['description']);
$wpdb->insert('wp_bubu_committees',
array(
'old_id' => '',
'name' => $name,
'description' => '',
'date_created' => $created,
'status' => $status,
'disbanded' => $disbanded
)
);
exit();
}
I have also localized the AJAX URL in functions.php. Any ideas?
Edit: Updated the code-- the action was set to the . I now am able to insert into the database, but it only allows me to insert one item. Attempting to insert additional items returns nothing, but the data does post to JSON.
Remove the data type json.
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
alert(response);
}
});

speed up select2 using ajax with php

I am trying to speed up my select2 results as i have over six-thousand customers in the database. I have the input box filled with data from a mysql database and dont know what more I can try at this stage to be honest. here is my select2 javascript (Js just isnt my thing)
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<script type="text/javascript">
$(function(){
// turn the element to select2 select style
$(".js-data-example-ajax").select2(
{
ajax: {
url: "/delete.php",
dataType: 'json',
data : function(term){
return{
term: term
};
},
results: function(data){
var results = <?php echo json_encode($jsData) ?>;
$.each(data, function(index, item){
results.push({
id: item.id,
text: item.fullName
})
})
}
}
});//end select2
});//end function
in php I use a foreach loop to read the data. It works perfect without the ajax just can be very slow select a result and there will be more customers added every day. I try to send back the id and the customers full name.
<?php
$sqlSearch="SELECT first_name, last_name, id, mobile, landline FROM customer order by first_name";
echo "<select id='tbCustId' class='js-data-example-ajax' style='width: 150px' size='2' name='tbCustId' required></option>";
// echo "<select>";
$jsData = [];
foreach ($db->query($sqlSearch) as $row){
$id = $row["Id"];
$fName = $row["first_name"];
$sName = $row["last_name"];
$fullName = $fName ." ". $sName;
$jsData[] = [
"id" => $id;
"fullName" => $fullName;
];
echo "<option value=$row[id]>
$fullName
</option>";
}
echo "</select><br/>";// Closing of list box
?>
As there are too many records it taking too much time , to avoid suggestion is
Make use of Pagination or
Make use of parallel execution by firing multiple ajax request i.e. request one fetch 1 to 3000 data and parallel request fetch 3001 to 6000 data..
Example Code : might having syntax error
ajax: {
url: "/delete.php",
dataType: 'json',
data : function(term){
return{
term: term
//record no : 1 added parameter for paging
//record no : 3000
};
},
results: PushData
}
ajax: {
url: "/delete.php",
dataType: 'json',
data : function(term){
return{
term: term
//record no : 3001 added parameter for paging
//record no : 6000
};
},
results: PushData
}
function PushData(data){
var results = <?php echo json_encode($jsData) ?>;
$.each(data, function(index, item){
results.push({
id: item.id,
text: item.fullName
})
})
}

Send multidimentional array from JQuery AJAX to PHP

i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this
Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)
i must be doing some stupid mistake. here is the code.
it gets records from a table and send to PHP
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
locations = locations.toString();
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: { recordid: recordid,locations:locations },
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
and this is the PHP function where i am receiving the data:
function saveSearchedLocations(){
print_r($_POST);
}
Use JSON.stringify() instead of toString() like so:
Change your AJAX call to this:
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
ajaxData = { recordid : recordid,locations : locations }
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: JSON.stringify(ajaxData),
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.
Take this answer as a reference:
I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.
jQuery:
var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);
$.post('serive.php', { DTO: JSON.stringify(selectedData) },
function(data){ /* handle response, */ });
service.php:
header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');
$foo = json_decode($_POST['DTO']);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data
echo json_encode($arr);
This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"
sendAjax = function() {
var data = {
foo: 123,
bar: 456,
rows: [{
column1: 'hello',
column2: 'hola',
column3: 'bonjour',
}, {
column1: 'goodbye',
column2: 'hasta luego',
column3: 'au revoir',
}, ],
test1: {
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
}
When the button is clicked, the following structured data shows up in PHP's $_POST variable:
Array
(
[foo] => 123[bar] => 456[rows] => Array(
[0] => Array(
[column1] => hello[column2] => hola[column3] => bonjour
)
[1] => Array(
[column1] => goodbye[column2] => hasta luego[column3] => au revoir
)
)
[test1] => Array(
[test2] => Array(
[test3] => baz
)
)
)
This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object
here is the link u can check here
https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/
Put your data in a form and send form data with serializeArray()

Categories

Resources