Passing data in PHP file to JS file in JSON format - javascript

I am trying to build a small program on a webpage that shows a drop-down list input type with the makes of cars (Ford and BMW in this case). Once a selection is made, the user clicks the submit button and below the form, a list of models specific to the make will appear in the results div.
I was provided with 4 files:
index.php:
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="js/main.js"></script>
data.php:
<? php
function data() {
$data = array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);
}
ajax.php:
<?php
require_once( 'data.php' );
$data = data();
$json_data = array();
And main.js:
$(document).ready(() => {
var run_ajax = function() {
results = $('#results');
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function(response) {
},
});
}
$('#submit').on('submit', function(e) {
e.preventDefault();
run_ajax();
});
});
How do I access the data in data.php from main.js? I'd appreciate a thorough explanation of possible. Thank you in advance.

Every thing is done seeing your provided code you have to just connect them but first you need to change the data.php file to the following
<?php
function data() {
return array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);}
then your ajax.php file to the following
<?php
require_once( 'data.php' );
$data = data();
$make = $_POST['make'];
// print_r($data);exit;
foreach($data as $car){
if(in_array($make,$car)){
$filtered[]=$car;
}
}
echo json_encode($filtered);
then change your main.js function to the following
$(document).ready(() => {
var run_ajax = function () {
results = $('#results');
$.ajax({
type: 'post',
url: 'ajax.php',
data: $("form").serialize(),
dataType: 'json',
beforeSend: function () {},
success: function (response) {
for (var key in
response) {
$("#results").append(" <div > Make: " + response[key]['make'] +
", Model:" + response[key]['model'] + " </div>");
}
},
});
}
$('#form').on('submit', function (e) {
e.preventDefault();
run_ajax();
});
});
hope that sorts out
EDIT
Actually, we have to send the select dropdown's selected make and filter out the cars with the same make to be responsed back and shown in the lower div have to change a few more things inside the ajax.php file

Your data() function must first return an array:
function data(){
$data = array('key'=>'value');
return $data;
}
Then echo or print() the json_encoded array:
$data = data();
echo json_encode($data);

Firstly your you dont need to define a function in your data.php file, since it is included in the ajax.php file, any variable there would be accessible
data.php:
<? php
$data = array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);
the ajax.php file reads the data from data.php file filters the array and put the models of the selected make into a new array and echo as json string
ajax.php:
<?php
require_once('data.php');
$filtered_make = [];
$make = $_POST['make'];
foreach ($data as $car) {
if (strtolower($make) == strtolower($car['make'])) $filtered_make[] = $car['model'];
}
echo json_encode($filtered_make);
index.php:
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="http://www.izivote.com/res/js/jquery.min.js"></script>
<script src="js/main.js"></script>
onsuccess, in the main.js file, the returned list of models in the json object from ajax.php is put in a list and displayed in the result container
main.js:
$(document).ready(() => {
var run_ajax = function() {
results = $('#results');
var formData = $('#form').serialize();
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function(response) {
var resultHTML = "<ul>";
for(var index in response){
resultHTML += "<li>" + response[index] + "</li>";
}
resultHTML += "</ul>";
results.html(resultHTML);
},
});
}
$('#form').on('submit', function(e) {
e.preventDefault();
run_ajax();
});
});
I hope this helps

return the data() as an array.
then encode the $data to json.
<?php
require_once( 'data.php' );
$data = data();
$json_data = json_encode(array());
and ajax:
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function( response ) {
console.log(response); // check the return result
$.each(response, function(key, val){
$("#results").append("<div>Make:"+key+" , Model:"+val+"</div>");
});
},
error: function (msg) {
alert("Error: check console");
console.log(msg);
}
});
not tested but hope it helps

Related

Dynamically load WordPress post content into DIV using HTML select, query, and AJAX

I am trying to figure out how to use WordPress and AJAX to display content (title and ACF fields) from a single post object in a page template using a HTML <select> input with no button or submit. The single post would change each time a different option is selected. The page would need to display the most recent post by default in the div when the page is loaded.
I have included the code I have implemented so far.
My knowledge of AJAX is limited.
Any tips or suggestions?
functions.php
function theme_global_script() {
wp_enqueue_script( 'sendout-ajax', get_template_directory_uri().'/js/sendouts.js', array( 'jquery' ) );
wp_localize_script( 'sendout-ajax', 'frontEndAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajax_nonce') ));
}
add_action( 'wp_enqueue_scripts', 'theme_global_script' );
add_action('wp_ajax_get_ajax_posts', 'get_sendout_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_sendout_posts');
function get_sendout_posts() {
// Query Arguments
// Select unlimited published posts from category 101 and order by date
$args = array(
'post_status' => array('publish'),
'nopaging' => true,
'numberposts' => '-1',
'order' => 'DESC',
'orderby' => 'date',
'cat' => 101,
);
// The Query
$ajaxposts = new WP_Query( $args );
$response = '';
// The Query
// If query is has results, load the sendouts template part
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-includes', 'sendouts' );
}
} else {
$response .= get_template_part( 'none' );
}
echo $response;
exit;
}
Sendout template part HTML
The $post->ID and $post->name would be returned from the WordPress query
<select id="" name="" class="sendout-select">
<option value="[$post->ID]">[$post-name]</option>
<option value="[$post->ID]">[$post-name]</option>
<option value="[$post->ID]">[$post-name]</option>
</select>
<div class="sendout-container">
<!-- Load Post object here -->
</div>
AJAX JavaScript
jQuery(document).ready(function($) {
$( ".sendout-select" ).change(function() {
$.ajax({
type: 'POST',
url: frontEndAjax.ajaxurl,
dataType: 'html',
data: {
action : 'get_sendout_posts'
},
success: function(response) {
console.log(response)
},
error: function(error) {
console.log(error)
}
});
});
});

yii2 refresh modal after submit form

I want to ask how to refresh the modal after I submit the form in another action? I use yii2.
Here is my code :
index.php:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\KategoriSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Kategoris';
$this->params['breadcrumbs'][] = $this->title;
$this->registerJs("
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var modal = $(this)
var title = button.data('title')
var href = button.attr('href')
modal.find('.modal-title').html(title)
modal.find('.modal-body').html('<i class=\"fa fa-spinner fa-spin\"></i>')
$.post(href).done(function( data ) {
modal.find('.modal-body').html(data)
});
})
");
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'kateg_id',
'kateg_nama',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{size} {view} {update} {delete}',
'buttons' => [
'size' => function($url, $model, $key) {
return Html::a(Html::tag('i','',
[
'class'=>'fa fa-th-list',
'title'=>'Size'
]),
[
'size',
'id'=>$model->kateg_id,
],
[
'data-toggle'=>'modal',
'data-target'=>'#myModal',
'data-title'=>'Size',
]);
}
]
],
],
]); ?>
<?php
Modal::begin([
'id' =>'myModal',
'header' => '<h4 class="modal-title">...</h4>',
'footer' => Html::button('Close', ['class' => 'btn btn-default','data-dismiss'=>'modal']),
]);
Modal::end();
?>
The size button on my grid view will show the modal that returns the render ajax from action size in my controller.
After that here is my size view:
$form = ActiveForm::begin(); ?>
<?= $form->field($model, 'ukuran')->textInput(['id'=>'ukuran']) ?>
<?= $form->field($model, 'kateg_id')->textInput(['id'=>'kategori','type'=>'hidden','value'=>$id]) ?>
<div class="form-group">
<?= Html::button('Tambah', [
'class' => 'btn btn-primary',
'onclick' =>'
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function(res){
alert("PROCESS_SUCCES");
}
});
',
]) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::begin(['id' => 'pjax-grid-view']); ?>
<div id="grid">
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'ukuran_id',
'ukuran',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<?php Pjax::end(); ?>
I'm trying to add refresh after alert but it does not work. It will close the modal and back to index again.
So I'm confused what it should be?
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function(res){
alert("PROCESS_SUCCES");
}
});
I noticed in your .post call, you don't do anything with the res that's passed as the parameter of the success function. You just alert "PROCESS_SUCCES" (is this a macro for something?), and it stops. To modify elements on your page, you would want to select one and use the .html() or .val() functions to change it. Something like this:
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function (res) {
alert("PROCESS_SUCCES");
$("#my_output_area").html(res);
}
});
Alternatively, you can use $.ajax() instead of $.post().
$.ajax({
type: "post",
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function (res) {
alert("PROCESS_SUCCES");
$("#my_output_area").html(res);
}
});

Yii2 Ajax request in yii2

By using kartik select2 plugins in Yii2, I try to make dependence dropdown for country and states.
Form field for country and states:
$url = yii\helpers\Url::toRoute('op-client/lists');
$this->registerJs($this->render('script.js'), \yii\web\VIEW::POS_READY);
$form->field($model, 'country_id')->widget(Select2::classname(), [
'data' => $countryData,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true,
],
'pluginEvents' =>
[
'change' => 'function()
{
getstate
(
$("#select2-opclient-country_id-container").val(),
"'.$url.'"
)
}',
],
]).'
$form->field($model, 'states_id')->widget(Select2::classname(), [
'data' => $statesData,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true,
],
]).'
Script.js
function getstate($countryid,url)
{
//console.log(startdate + enddate);
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type:"POST",
cache:false,
url:url,
data:{countryid:countryid, _crsf:csrfToken},
success:function(data){
$("#select2-opclient-states_id-container").val(data);
},
})
}
Controller:
public function actionLists()
{
$request = Yii::$app->request;
$country = $request->post('countryid');
$countStates = OpStates::find()
->where(['country_id' => $country])
->count();
$states = OpStates::find()
->where(['country_id' =>$country])
->all();
if($countStates > 0)
{
foreach($states as $state){
echo "<option value='".$state->id."'>".$state->state_name."</option>";
}
}
else
{
echo "<option></option>";
}
}
When I run the program, it show error "Uncaught ReferenceError: countryid is not defined".
But I thought i passed the countryid into it already? Where have I done wrong?
Any help/advice will be appreciated. Thankss
Please check below code,i think you did little mistake in country_id variable name.
public function actionLists()
{
$request = Yii::$app->request;
$country = $request->post('country_id');
$countStates = OpStates::find()
->where(['country_id' => $country])
->count();
$states = OpStates::find()
->where(['country_id' =>$country])
->all();
if($countStates > 0)
{
foreach($states as $state){
echo "<option value='".$state->id."'>".$state->state_name."</option>";
}
}
else
{
echo "<option></option>";
}
}
and here
function getstate(countryid,url)
{
//console.log(startdate + enddate);
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type:"POST",
cache:false,
url:url,
data:{countryid:countryid, _crsf:csrfToken},
success:function(data){
$("#select2-opclient-states_id-container").val(data);
},
})
}
It will solve your issue.

insertion into cart does when page refreshes in codeigniter with ajax

I am adding items into cart with ajax in codeigniter.
My problem is that the cart got updated when i refreshes page. I have ajaxify it to prevent page refresh. but its not happening. My code is right and there is no error. but still its not working.
my controller code is
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
}
my view code is
function insert()
{
var item_id=$("#item_id").val();
var item_name=$("#item_name").val();
var item_price=$("#item_price").val();
var dataString = "&item_id=" + item_id + "&item_name=" + item_name + "&item_price=" + item_price;
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function()
{
alert('hello');
}
});
}
<form id="form">
<input type="hidden" id="item_id" name="item_id" value={{data.id}}> <input type="hidden" id="item_name" name="item_name" value={{data.item_name}}> <input type="hidden" id="item_price" name="item_price" value={{data.price}}>
<p>Add to Cart</p>
</form>
the concept of the cart is to add the cart array in a session
so the php will not feel the changes until you reload the page
so you have to append the table with javascrip
// in controller
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
echo json_encode($data) ;
}
// in your javascript
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function(data)
{
// just replace YOUR-TABLE-ID with table id
//and complete the tr you want to append
var tr = "<tr><td>"+data.id+"</td><td>"+data.name+"</td></tr>";
$("#YOUR-TABLE-ID tr:last").after(tr);
}
});
What is happening when you try to use $item_id instead radnom number:
$data = array(
'id' => $item_id,
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);

CJuiAutoComplete onSelect not working - YII

New to YII. I have to load a page with AJAX call on selection from CJuiAutoComplete Field.
<?php
echo CHtml::label(Yii::t('location', 'PLZ'), 'GeoData_plz');
?>
</td><td>
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'GeoData[plz]',
'source' => 'js:function(request, response) {getAutoCompleteData("plz", response);}',
'options' => array(
'minLength' => '0',
),
'htmlOptions' => array(
'size' => 8,
'maxlength' => 15,
'class'=>'addrChange'
),
'value' => $model->geo_data->plz));
?>
I tried adding onSelect of different plz in htmlOptions (to act as submit buttion) but its not working, Here I just want to submit plz in database on select of different plz below is the code.
echo CHtml::label(Yii::t('location', 'PLZ'), 'GeoData_plz'); ?></td><td><?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'id' => 'GeoData_plz',
'name' => 'GeoData[plz]',
'source' => 'js:function(request, response) {
getAutoCompleteData("plz", response);
}',
'options' => array(
'minLength' => '0',
//'select' => 'js:function(event, ui){ alert(ui.item.value) }',
),
'htmlOptions' => array(
'size' => 8,
'maxlength' => 15,
'class'=>'addrChange',
'onSelect' => 'CHtml::ajax({
url: "'.$this->createUrl('location/getAddressTabContent').'",
dataType: "json",
data: {
loc_id: ' . $model->id . '
},
success: function(data) {
$("#addressBricks").html(data.brick_table);
}
})'
),
'value' => $model->geo_data->plz
));
Thanks for the reply, But here i just want to submit data on select I used the code given by you but its not working
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'model'=>$model,
'attribute'=>'GeoData[plz]',
'source'=>'js: function(request, response) {
getAutoCompleteData("plz", response);
$.ajax({
url: "'.$this->createUrl('location/getAddressTabContent').'",
dataType: "json",
data: {
loc_id: ' . $model->id . '
},
success: function (data) {
$("#addressBricks").html(data.brick_table);
}
})
}',
'options'=>array(
'delay'=>300,
'minLength'=>0,
'select'=>'js:function(event, ui) {
$.ajax({
type:"POST",
url: "' . $this->createUrl('location/getAddressTabContent'') . '",
data: {selected: ui.item.value},
success:function(data) {$("#addressBricks").html(data.brick_table);}
});}'
),
'htmlOptions' => array(
'size' => 8,
'maxlength' => 15,
'class'=>'addrChange',
'value' => $model->geo_data->plz,
'id' => 'GeoData_plz',
),
));
It's in options array, not in htmlOptions:
'options'=>array(
.....
'select'=>'js:function(event, ui) {
//your ajax request here
//use $.ajax()
//your selected item = ui.item.id
}
Hope this will help.
I have edited your widget. Just use this widget to get it working.
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'model'=>$model,
'attribute'=>'GeoData[plz]',
'source'=>'js: function(request, response) {
$.ajax({
url: "'.$this->createUrl('location/getAddressTabContent').'",
dataType: "json",
data: {
loc_id: ' . $model->id . '
},
success: function (data) {
$("#addressBricks").html(data.brick_table);
}
})
}',
'options'=>array(
'delay'=>300,
'minLength'=>1,
),
'htmlOptions' => array(
'size' => 8,
'maxlength' => 15,
'class'=>'addrChange',
'value' => $model->geo_data->plz,
'id' => 'GeoData_plz',
),
));

Categories

Resources