I want to use ajax response data in another javascript.
AJAX In view (sell_report.php)
<script src="<?php echo base_url(); ?>public/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$('.select_year_product').on('change',function () {
var select_year_product = $('.select_year_product').val();
$.ajax({
method : "POST",
url : '<?php echo site_url('sell_report/select_data_yearwise'); ?>',
data: { select_year_product:select_year_product },
success : function (data){
alert(data);
}
});
});
</script>
Above is the ajax call here in i have to select product yearwise from database it's working fine. i got response in alert(data) in ajax response. Below is the my controller Code from here i got result.
Sell_report.php (Controller)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sell_report extends CI_Controller {
public function select_data_yearwise()
{
$select_year_product = $this->input->post('select_year_product');
$res_yearwise = $this->db->query("select * from product where year='$select_year_product'");
$row_yearwise = $res_yearwise->result();
print_r($row_yearwise);
exit();
}
}
Now,
I want to use this reponse in another javascript which is in the same view
where i write the ajax script.
The script in which i want the ajax response is explained below.
This script is for dynamic graph i have to pass the values which i got in array of ajax response through for each loop.
<script type="text/javascript">
var Script = function () {
//morris chart
$(function () {
// data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type
Morris.Bar({
element: 'hero-bar',
data: [
{device: 'iPhone', geekbench: 136},
{device: 'iPhone 3G', geekbench: 137},
{device: 'iPhone 3GS', geekbench: 275},
{device: 'iPhone 4', geekbench: 380},
{device: 'iPhone 4S', geekbench: 655},
{device: 'iPhone 5', geekbench: 1571}
],
xkey: 'device',
ykeys: ['geekbench'],
labels: ['Geekbench'],
barRatio: 0.4,
xLabelAngle: 35,
hideHover: 'auto',
barColors: ['#6883a3']
});
$('.code-example').each(function (index, el) {
eval($(el).text());
});
});
}();
</script>
EDIT with AJAX Response:
Array
(
[0] => stdClass Object
(
[id] => 25
[name] => Product 1
[handle] => Handle1
[description] => <p>This is for Testing..!</p>
[total_order_income] => 1420
[type_id] => 19
[brand_id] => 5
[supplier_id] => 5
[final_price] => 147
[user_id] => 2
[supplier_code] => 123456
[sales_account_code] => 123456
[purchase_account_code] => 123456
[supply_price] => 100
[markup] => 5
[retail_price] => 105
[tax_amount] => 42
[quantity] => 50
[status] => 1
[dt_added] => 1472551929
[dt_updated] => 1472551929
)
[1] => stdClass Object
(
[id] => 29
[name] => Samsung 4G
[handle] => Samsung 4G
[description] => <p>It is very good phone</p>
[total_order_income] => 1420
[type_id] => 18
[brand_id] => 6
[supplier_id] => 1
[final_price] => 121
[user_id] => 2
[supplier_code] => 100
[sales_account_code] => 200
[purchase_account_code] => 300
[supply_price] => 100
[markup] => 10
[retail_price] => 110
[tax_amount] => 11
[quantity] => 0
[status] => 1
[dt_added] => 1472627773
[dt_updated] => 1472627773
)
[2] => stdClass Object
(
[id] => 30
[name] => Product 12
[handle] => Handle
[description] => Description
[total_order_income] => 1420
[type_id] => 0
[brand_id] => 0
[supplier_id] => 0
[final_price] => 150
[user_id] => 2
[supplier_code] => Description
[sales_account_code] => 123
[purchase_account_code] => Description
[supply_price] =>
[markup] =>
[retail_price] =>
[tax_amount] =>
[quantity] => 20
[status] => 1
[dt_added] => 1472628990
[dt_updated] => 1472628990
)
)
Here is x-axis i want product names and in y-axis i want
total_order_income.
Create the bar chart. Morris.Bar(options) returns the bar chart object for future use so make sure to save a reference to it. (to update the data)
Hook up the year change event so that you do your AJAX request. If you do this after you create the bar chart and within the same scope, you can use the chart without creating a global variable for it. (yay for closures)
In the AJAX success callback, process the data to convert it into the correct format.
Still in the AJAX callback, call chart.setData(data) to update the chart.
/* Step 1 */
var bar_chart = Morris.Bar({
element: 'hero-bar',
data: [],
xkey: 'device',
ykeys: ['geekbench'],
labels: ['Geekbench'],
barRatio: 0.4,
xLabelAngle: 35,
hideHover: 'auto',
barColors: ['#6883a3']
});
/* Step 2 */
$('.select_year_product').on('change',function () {
var select_year_product = $('.select_year_product').val();
$.ajax({
method : "POST",
url : '<?php echo site_url('sell_report/select_data_yearwise'); ?>',
data: { select_year_product:select_year_product },
success : function (data){
/* Step 3: format data here */
/* Step 4 */
bar_chart.setData(data);
}
});
});
If you needed help with step 3 then I'll happily give some pointers but it would be helpful to provide some sample responses from the AJAX request.
Edit: JSON encoding the data before sending it makes more sense than parsing the print_r output:
public function select_data_yearwise()
{
$select_year_product = $this->input->post('select_year_product');
$res_yearwise = $this->db->query("select * from product where year='$select_year_product'");
$row_yearwise = $res_yearwise->result();
echo json_encode($row_yearwise);
exit();
}
Client side:
success : function (data){
JSON.parse(data).map(d => /* extract the details you want here */ )
/* Step 4 */
bar_chart.setData(data);
}
Related
Hi there I use this function for numbering pagination on wordepress.
function numbering_pagination() {
global $wp_query;
$all_pages = $wp_query->max_num_pages;
$current_page = max(1, get_query_var('paged'));
if ($all_pages > 1) {
return paginate_links(array(
'base' => get_pagenum_link() . '%_%',
'format' => '?paged=%#%',
'current' => $current_page,
'mid_size' => 1,
'max_size' => 1,
'type' => 'list',
'next_text' => __('next'),
'prev_text' => __('prev')
));
}
}
and is Work well with (index, category). but in page search, the permalink show like this when I click next button.first ckick like this.
exmp.com/?s?paged=2
secend click.
exmp.com/?s?paged=2?paged=2
PLZ enyone HElp
I have a dropdown with countries, and I want to add a dependent dropdown or textfield with Ajax according to the selected value in the main dropdown.
Case 1
For example, if the user selects the United States(US) or Canada(CA), the Ajax should fire and add a dependent dropdown.
If the US
Dropdown
New York
New Jersey
California
And more options
If CA
Dropdown
Ontario
Manitoba
Quebec
And more options
The select(dependent dropdown) has to be required.
Case 2
If the user selects any other country, the Ajax should fire and add a dependent textfield
If any country but not US nor CA
Textfield
The textfield has to be required too.
I tried the options here
Using the AJAX command option
//This is my main select
$form['country'] = [
'#type' => 'select',
'#title' => $this->t(‘Select Country'),
'#options' => [
‘US’ => t(‘United State’),
'CA' => t('Canada’),
‘BR’ => t(‘Brazil’),
‘CO’ => t(‘Colombia’),
],
'#default_value' => 'US',
'#required' => TRUE,
'#empty_option' => $this->t('Please select'),
'#ajax' => [
'callback' => [$this, 'addDependentField’],
'event' => 'change',
'wrapper' => 'output-dependent’, // This element is updated with this AJAX callback.
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
// Here I want to add a select or textfield. This dependes on the value from the main select above
$form[‘dependent_field’] = [
'#title' => $this->t('State/Province'),
'#prefix' => '<div id=“dependent-field”>’,
'#suffix' => '</div>',
];
public function addDependentField(array &$form, FormStateInterface $form_state) {
$selectedValue = $form_state->getValue('country');
switch ($selectedValue) {
case 'US':
$elem = [
'#type' => 'select',
'#options' => [
'NY' => t('New York'),
'CA' => t('California'),
'NJ' => t('New Jersey'),
'WA' => t('Washington'),
],
'#required' => TRUE,
'#attributes' => [
'id' => ['edit-output'],
],
];
break;
case 'CA':
$elem = [
'#type' => 'select',
'#options' => [
'ON' => t('Ontario'),
'PE' => t('Prince Edward Island'),
'QC' => t('Quebec'),
],
'#required' => TRUE,
'#attributes' => [
'id' => ['edit-output'],
],
];
break;
default:
$elem = [
'#type' => 'textfield',
'#size' => '60',
'#required' => TRUE,
'#attributes' => [
'id' => ['edit-output'],
],
];
break;
}
$renderer = \Drupal::service('renderer');
$renderedField = $renderer->render($elem);
// Create the AjaxResponse.
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#edit-output-2', $renderedField));
// Return the AjaxResponse object.
return $response;
}
This works only the first time, then stops working, I think it is because the fields’ types are different.
Using the render array option
I just changed all code after switch for the code below
return $form['dependent_field'] = $elem;
And it has the same behavior, it works only the first time then stops working.
I also tried
This to update multiple times
Replace more than one element form
Drupal 8 add ajax form element after ajax call
And also I found the same bad behavior after trying those answers, I still think it might be because one field is dropdown, and the other is `texfield`` because I want to update it over the same field with different types.
I think you don't need a specific AJAX for it.
You can use Form API '#states'
You can use this code to do ajax request.
This will get the list of states for the country selected
$('#countries').change(function(){
$.get("url/"+country,function(data,status){
various countries = JSON.parse(data);
for(var i = 0; i<countries.length; i++){
document.getElementById().innerHTML += "<option>"+countries[i].state+"</option>";
//here you can add the form field you wish to.
}
}
});
I have a yii2 project and i would like show events in calendar.
Yii2 fullcalendar not show events before 09:00:00, but after all good.
After 09:00:00 all good.
I'll show you my code, which works fine.
Thank you for your help.
echo yii2fullcalendar\yii2fullcalendar::widget(array(
'options' => [
'lang' => 'hu',
],
'events' => $events,
'clientOptions' =>[
'header' => [
'right'=>'month,agendaWeek'
],
'displayEventTime' => false,
'height' => 'auto',
'minTime' => '06:00:00',
'maxTime' => '20:00:00',
'html' => true,
'eventClick' => new \yii\web\JsExpression($JSEventClick),
'eventRender' => new \yii\web\JsExpression($JSEventRender),
],
));
$events array:
Array
(
[0] => yii2fullcalendar\models\Event Object
(
[id] => 1
[title] => TEST TITLE
[allDay] => 2020-03-23 08:30:00
[start] => 2020-03-23 08:30:00
[end] => 2020-03-23 9:30:00
)
}
I've searched a lot, but can't find the answer to this rather simple question:
In Symfony 2.8 I have a form, that renders a country field. Based on it's selection I want to display a zipcode and federalstate field only for the choice 'Deutschland' (data 'D'). Here is the code for the country-field:
->add('nationveranstaltungsort', ChoiceType::class, array(
'choices' => array(
'D' => 'Deutschland',
'AFG' => 'Afghanistan',
//many other countries following
),
'data' => 'D',
'label' => 'Nation Tagungsstätte'))
it's prepopulated with the Choice 'Deutschland', data 'D'.
based on that i want to dynamically display:
->add('plzveranstaltungsort', TextType::class, array('label' => 'PLZ', 'attr' => array('size' => '5', 'maxlength' => '5')))
->add('bundeslandveranstaltungsort', ChoiceType::class, array(
'choices' => array(
0 => ' ',
1 => 'Baden-Württemberg',
2 => 'Bayern',
3 => 'Berlin',
4 => 'Brandenburg',
5 => 'Bremen',
6 => 'Hamburg',
7 => 'Hessen',
8 => 'Mecklenburg-Vorpommern',
10 => 'Nordrhein-Westfalen',
11 => 'Rheinland-Pfalz',
12 => 'Saarland',
13 => 'Sachsen',
14 => 'Sachsen-Anhalt',
15 => 'Schleswig-Holstein',
16 => 'Thüringen',
),
'data' => 0,
'label' => 'Bundesland Tagungsstätte'))
If "Deutschland" is not selected, I simply want to hide/disable these fields (and handle the null value somewhere else).
I tried http://symfony.com/doc/current/form/dynamic_form_modification.html and some other javascript stuff, but as I basically don't know any JS, I couldn't find any proper resources.
Since by default the nationveranstaltungsort field has Germany selected, then there is no need to hide plzveranstaltungsort. You can hide in Javascript by using something like:
var bund = document.getElementById("bundeslandveranstaltungsort");
bund.style.display = "none";
Then to show the element use:
bund.style.display = "inline";
Depending on what css you are using, you might need to use:
bund.style.display = "block";
In you form you can specify an attribute to run a Javascript function on change like so:
->add('nationveranstaltungsort', ChoiceType::class, array(
'choices' => array(
'D' => 'Deutschland',
'AFG' => 'Afghanistan',
),
'data' => 'D',
'label' => 'Nation Tagungsstätte',
'attr' => array(
'onchange' => 'changeCountry()',
),
))
Then in the Javascript function changeCountry() hide the element or show it using the above.
The ids I show are not actually what you will use, but if you use the browser tools, for example in Firefox (I suggest using FireFox for testing), you can right-click on the choice element and choose "Inspect element"; then you can see what the "actual" id value is that you need to use. It depends on your Form name.
I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.