Showing events for multiple eventSources depend on checkboxes' choice in Fullcalendar - javascript

I'm adding the feature like in Solgema Fullcalendar - http://plone.org/products/solgema.fullcalendar/releases/2.1.2
(selecting and showing events with checkboxes selection)
My eventSourses look like:
eventSources: [
...
{
url: '/admin_schedule/get_schedule_db_recurring_events_on_daysweek/',//"<?echo $data_path?>",
type: 'GET',
data: {sch_teacher_id: sch_teacher_id},
backgroundColor: 'red',
}
],
And I want implement checkboxes for "filtering" events by teachers, checked in checkboxes. For beginning make just one checkbox (later make foreach cover)
<div class="box">
<?php
$js = 'onClick="rerender_schedule()"';
echo form_checkbox('teacher', 'vika', FALSE, $js)." Vika";
?>
</div>
By this code as I think, fullcalendar must call rerender_schedule() function which filters data from eventSource with vika's sch_teacher_id
If somebody could help with rerender_schedule() function, I will be thankful, because not good in ajax.
EDIT: (thanks to tocallaghan!). It's just a beginning right now.
My 3 checkboxes:
$data = array(
'name' => 'teacher',
'class' => 'teacher',
'id' => 'teacher',
'value' => '128',
'checked' => FALSE,
'style' => 'margin:10px',
);
echo form_checkbox($data); echo "Вика";
$data = array(
'name' => 'teacher',
'class' => 'teacher',
'id' => 'teacher2',
'value' => '111',
'checked' => FALSE,
'style' => 'margin:10px',
);
echo form_checkbox($data); echo "Вася";
$data = array(
'name' => 'teacher',
'class' => 'teacher',
'id' => 'teacher3',
'value' => '1',
'checked' => FALSE,
'style' => 'margin:10px',
);
echo form_checkbox($data); echo "Саша";
ajax on change them:
$('.teacher').change(function (event) {
events1.data.sch_teacher_id = $(this).val();
events2.data.sch_teacher_id = $(this).val();
events3.data.sch_teacher_id = $(this).val();
$calendar.fullCalendar('refetchEvents');
});
vars for eventSourses:
var events1 = {
url: 'url1',
type: 'GET',
data: {sch_teacher_id: $('#teacher').val() },
success: function (response) {
return response;
}
};
var events2 = {
url: 'url2',
type: 'GET',
data: {sch_teacher_id: $('#teacher').val() },
backgroundColor: 'green',
success: function (response) {
return response;
}
};
var events3 = {
url: 'url3',
type: 'GET',
data: { sch_teacher_id: $('#teacher').val() },
backgroundColor: 'red',
success: function (response) {
return response;
}
};
my eventSources call
eventSources: [
events1,
events2,
events3
],

You need refetchEvents , but be careful to update you data parameter before calling (otherwise it will remain the initially set value)
$('.CheckBoxClass').change(function () {
events.data.sch_teacher_id = $(this).val();
$('#calendar').fullCalendar('refetchEvents');
});
Edit: code to declare events object:
var events = {
url: 'url',
type: 'GET',
data: { Id: $('#divId').val() },
success: function (response) {
return response;
}
};
$('#calendar').fullCalendar({
events: events
});

Related

Send an JS array through Ajax

I've this type of array in JS:
[{
websitetype: "onepager"
}, {
layout: "provided"
}, {
layout_provided: "wireframes"
}, {
languages: "single"
}, {
client_name: "dasda"
}, {
client_email: "asdasd#asdasd.fr"
}, {
client_conditions: "on"
}, {
client_newsletter: "on"
}]
How can I send it through Ajax ?
What I tried is:
$.ajax({
type: 'POST',
url: 'assets/send.php',
data: {datas},
success: function(response) { },
});
This is what I would like to get in PHP:
[datas] => Array
(
[websitetype] => onepager
[layout] => provided
[layout_provided] => wireframes
[languages] => single
[client_name] => dasda
[client_email] => asdasd#asdasd.fr
[client_conditions] => on
[client_newsletter] => on
)
What I'm missing here please ?
Thanks.
The first thing you should do is reduce that array into an object matching the format you want
const dataObject = Object.fromEntries(datas.flatMap(o => Object.entries(o)))
This looks like the following
{
"websitetype": "onepager",
"layout": "provided",
"layout_provided": "wireframes",
"languages": "single",
"client_name": "dasda",
"client_email": "asdasd#asdasd.fr",
"client_conditions": "on",
"client_newsletter": "on"
}
You then have two options for posting it to PHP
Send it as raw JSON
$.ajax({
method: "POST",
url: "assets/send.php",
contentType: "application/json",
data: JSON.stringify(dataObject),
processData: false
})
Then read and parse the JSON in PHP
$datas = json_decode(file_get_contents("php://input"), true);
// example
echo $datas["websitetype"]; // "onepager"
Alternatively, let jQuery format the data as an associative PHP array
$.ajax({
method: "POST",
url: "assets/send.php",
data: {
datas: dataObject
}
})
This will post an application/x-www-form-urlencoded request body of
datas%5Bwebsitetype%5D=onepager&datas%5Blayout%5D=provided&datas%5Blayout_provided%5D=wireframes&datas%5Blanguages%5D=single&datas%5Bclient_name%5D=dasda&datas%5Bclient_email%5D=asdasd%40asdasd.fr&datas%5Bclient_conditions%5D=on&datas%5Bclient_newsletter%5D=on
PHP can read this as an array via $_POST
print_r($_POST['datas']);
Results in
Array
(
[websitetype] => onepager
[layout] => provided
[layout_provided] => wireframes
[languages] => single
[client_name] => dasda
[client_email] => asdasd#asdasd.fr
[client_conditions] => on
[client_newsletter] => on
)
Encode your data string into JSON.
const datas = [{
websitetype: "onepager"
}, {
layout: "provided"
}, {
layout_provided: "wireframes"
}, {
languages: "single"
}, {
client_name: "dasda"
}, {
client_email: "asdasd#asdasd.fr"
}, {
client_conditions: "on"
}, {
client_newsletter: "on"
}]
const jsonString = JSON.stringify(datas)
$.ajax({
type: 'POST',
url: 'assets/send.php',
data: { datas: jsonString },
success: function(response) { },
});
In your PHP:
$data = json_decode(stripslashes($_POST['datas']));
// here i would like use foreach:
foreach($datas as $data){
echo $data;
}

How to update image with AJAX in Laravel

I'm having problems updating a record with an image. I don't what I need to do. My image is stored in a public folder called 'img/products'
ProductController.php
This is my controller. It works well without modifying the image.
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
$products->name = $request->input('name');
$products->category_id = $request->input('category_id');
$products->description = $request->input('description');
$products->price_neto = $request->input('price_neto');
$products->iva = $request->input('iva');
$products->price_total = $request->input('price_total');
$products->image = $request->input('image');
$products->save();
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
Product.js
All I know is that I have to use var formData = new FormData ($ ("# frmAddProduct") [0]); as in the store function. I can enter records with images but not edit them. My image is stored in a public folder called 'img/products'
$(document).ready(function() {
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: {
name: $("#frmEditProduct input[name=name]").val(),
category_id: $("#frmEditProduct select[name=category_id]").val(),
description: $("#frmEditProduct input[name=description]").val(),
price_neto: $("#frmEditProduct input[name=price_neto2]").val(),
iva: $("#frmEditProduct input[name=iva2]").val(),
price_total: $("#frmEditProduct input[name=price_total2]").val(),
image: $("#frmEditProduct input[name=image]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
});
function editProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditProduct input[name=name]").val(data.products.name);
$("#frmEditProduct select[name=category_id]").val(data.products.category_id);
$("#frmEditProduct input[name=description]").val(data.products.description);
$("#frmEditProduct input[name=price_neto2]").val(data.products.price_neto);
$("#frmEditProduct input[name=iva2]").val(data.products.iva);
$("#frmEditProduct input[name=price_total2]").val(data.products.price_total);
$("#frmEditProduct file[name=image]").val(data.products.image);
$("#frmEditProduct input[name=product_id]").val(data.products.id);
$('#editProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
You should check if the file exists before trying to delete, for example:
$product = Product::find($id);
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
if (Storage::disk('local')->exists('img/products/'.$product->image)) {
Storage::disk('local')->delete('img/products/'.$product->image);
}
Take a look one example only:
public function update(UpdateProductFormRequest $request, $id)
{
$product = Product::find($id);
$data = $request->only('name','category_id','description',
'price_neto','iva','price_total');
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
// when saving the file, delete the old file first
if ($request->hasFile('image')) {
$file = $request->file('image');
$original_filename = $file->getClientOriginalName();
// $mime = $file->getMimeType(); // Suggestion
$extention = $file->getExtension();
// $size = $file->getClientSize(); // Suggestion
$stored_filename = $original_filename; // md5($original_filename); // Suggestion
$file_path = storage_path('public/img/products/');
if (Storage::disk('local')
->exists("public/img/products/{$stored_filename}.{$extention}"))
{
Storage::disk('local')
->delete("public/img/products/{$recordSet->stored_filename}.{$extention}");
}
$file_moved = $file->move($file_path, "{$stored_filename}.{$extention}");
$data->image = "{$stored_filename}.{$extention}";
}
// Updating data
$result = $product->update($data);
if ($result) {
/* return redirect()
->route('products.index')
->withSuccess('Product was successfully updated'); */
return response()->json([
'message' => 'Product was successfully updated'
'product' => $product
]); // You don't have to put 200 because it's the default
}
/* return back()
->withErrors(['Unable to update the product'])
->withInput($request->input()); */
return response()->json(['error' => 'Unable to update the product'], 400);
}
It would be better if you create a form request to do your validations.
Don't forget to create links to the storage path:
php artisan storage:link
I think it would be helpful:
$("#btn-edit").click(function() {
var formData = new FormData($("#frmAddProduct")[0]);
formData.append('_method', 'put');
formData.append('_token', "{{ csrf_token() }}"); // if you are using Blade
var route= "{{ route('products.update', ['id' => ':id']) }}"; // if you are using Blade
route= route.replace(':id', $("#frmEditProduct input[name=product_id]").val())
$.ajax({
method: 'post',
url: route,
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
Is your js script in "Blade" ? If so, try it this way:
var image = '{{ asset("/img/products/_image_file") }}'
image.replace('_image_file', data.products.image)
$("#frmEditProduct file[name=image]").val(image)
Note that we can first use the "asset ()" helper to create the full path to use to find the image, but with a "_image_file" placeholder
After that, we use the replace () function to change the "_image_file" placeholder with the actual image file brought from the ajax response.
Something like this?
ProductController.php
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
if ($request->hasFile('image')) {
$productImage = $request->file('image');
$productImageName = rand() . '.' . $productImage->getClientOriginalExtension();
if (Storage::disk('local')->exists("img/products/{$productImageName}")) {
Storage::disk('local')->delete("img/products/{$recordSet->$productImageName}");
}
$file_moved = $productImage->move(public_path('img/products'), $productImageName);
$data->image = "{$productImageName}";
}
$products->save([
'name' => $request->name,
'category_id' => $request->category_id,
'description' => $request->description,
'price_neto' => $request->price_neto,
'iva' => $request->iva,
'price_total' => $request->price_total,
'image' => $productImageName,
]);
return response()->json([
'error' => false,
'products' => $products,
]);
}
Product.js
$("#btn-edit").click(function() {
var formData = new FormData($("#frmEditProduct")[0]);
formData.append('_method', 'put');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});

Where is the error: Java Script code

Aplication is built on Yii2 with using Kartik's star-rating widget. Js code have an error:
Image with error in console:
Code:
<?php
$js = <<<JS
function (event, value, caption) {
$.ajax({
type: 'GET',
url: '/rating/update-rating',
data: {
points: value,
post_id: $post->id
},
success: function(res) {
$(event.currentTarget).rating('update', res);
},
error: function(e) {
console.log(e);
}
});
}
JS;
$this->registerJs($js);
echo StarRating::widget([
'name' => $post->post_rate,
'value' => isset($post->rating[0]['dec_avg']) ? $post->rating[0]['dec_avg'] : 0,
'pluginOptions' => [ ... ]
'pluginEvents' => [
'rating:change' => $js,
],
You forgot to add a name for your js function:
function functionName(event, value, caption) {
$.ajax({
type: 'GET',
url: '/rating/update-rating',
data: {
points: value,
post_id: $post - > id
},
success: function(res) {
$(event.currentTarget).rating('update', res);
},
error: function(e) {
console.log(e);
}
});
}

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()

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