How to render view only after selection in yii2 - javascript

I am rendering two views in my single view.
<?= $form->field($model, 't_type')->dropDownList([
'' => 'Please Select', 'Slab Based' => 'Slab Based',
'TOU Based' => 'TOU Based']) ?>
<div class="showSlab" id="slab" style="display: none">
<?php echo $this->render('_slabBased', [
'modelsTariffSlabs' => $modelsTariffSlabs,
]); ?>
</div>
<div class="showTou" id="tou" style="display: none">
<?php echo $this->render('_touBased', [
'modelsTouSlabs' => $modelsTouSlabs,
]); ?>
</div>
By default both div's are hidden but both of them are rendering. But I want to render the form only when I select option 'Slab Based' or TOU Based
JS
$('#mdctariff-t_type').on('change', function () {
if (this.value === 'Slab Based') {
$("#slab").show();
$("#tou").hide();
} else if (this.value === 'TOU Based') {
$("#tou").show();
$("#slab").hide();
} else {
$("#slab").hide();
$("#tou").hide();
}
});
Note: After rendering the form I am also saving it
Update 1
I have tried to render it via ajax
$url = Url::toRoute(['/mdctariff/_slabBased','modelsTariffSlabs'=>$modelsTariffSlabs]);
doGet('$url')
function doGet(url, params) {
params = params || {};
$.get(url, params, function(response) { // requesting url which in form
$('#slab').html(response); // getting response and pushing to element with id #response
});
}
Reference: How to render partial using AJAX? Laravel 5.2
When I selects an option I am not able to view the form. In my Network tab I am getting error Not Found (#404): Page not found.. The URL generated is http://localhost/mdc/backend/web/mdctariff/_slabBased
While pasting this URL at my browser I am getting the same error. I must be missing something that I don't know
How can render my view only when I select an option?
Any help would be highly appreciated.

In your URL
$url = Url::toRoute(['/mdctariff/_slabBased','modelsTariffSlabs'=>$modelsTariffSlabs]);
The first argument should be the proper existing route. But you have written it in the form of a directory, i.e. mdctafiff folder then _slabBased file.
What you need to do here is, you need to create an action method in the controller so that you can access it through route. Like MdctariffController and partialAction and then in the body of partialAction method you need to call the _slabBased view file. Futher you can also take reference here for Url::toRoute().

Related

Wordpress: HowTo pass persisted/global values from one page to another?

So I have created two pages in wordpress, which both utilise plugins via shortcodes:
[sc_page1]
[sc_page2]
In the callback function of page1, I have the following code:
<?php
function showcountries_callback() {
include_once("pdo_mysql.php");
pdo_connect("localhost","wpuser","920support");
pdo_select_db("wpdb");
$getIDs = pdo_query("SELECT value from P where id=y");
echo json_encode($getIDs, JSON_PRETTY_PRINT);
}
?>
My javascript does the following:
success: function (data) {
console.log(data);
jQuery('#MyForm').submit(function(){
jQuery.post('', function() {
window.location = 'http://192.x.x.x/index.php/searchresults/?id=' + data;
});
return false;
});
And in the fontend function of page2, I want to do the following:
<?php
function searchresults_frontend() {
foreach($getIDs as $row){
$htmlSearchResult .= "<option value='{$row[somevalue]}'>{$row[somevalue]}</option>";
}
return $htmlSearchResult;
}
add_shortcode("sr_frontend", "searchresults_frontend");
?>
Once the query in page1 is completed, the user is redirected to page2 via window.location.href. So how can I use the object value, $getIDs, from page1 in page2 as I've described?
If I understand your situation correctly, the simplest way to pass data around between pages is to have the first snippet you posted return an hidden field with value set to $getIDs.
Then, from the javascript snippet you can access the hidden field, read the value it contains and pass it to the second page as a URL parameter, so now you have the value available to the second snippet of code in the $_GET.

Building query string GET vars dynamically

I'm head below water on this, using Laravel I have a search page of which ajax calls a url and updates the html for filter by the way of html links which contain get vars ($(this).attr('href'); which contains ?var=test sent via ajax) to return filtered results. As ajax this doesn't update the url I'm using history.replaceState to update that.
Now here's my issue, the links which be shown as buttons (using BS) - so my link href will include the ?thisbuttonvar=whatever BUT if that get var already exists then the link href should not include ?thisbuttonvar=whatever it should remove it
I have created a function to try to handle this as follows (sorry I can't get it to paste properly):
function href_append_query($param) {
parse_str($_SERVER["QUERY_STRING"], $query_array);
if (array_key_exists(current(array_keys($param)), $query_array))
{
$key = current(array_keys($param));
if ($param[$key] == $query_array[$key])
{
unset($query_array[$key]);
}
}
else
{
$query_array = $query_array + $param;
}
$query = http_build_query($query_array);
return '?' . $query; }
The issue with this is when I do a
#foreach ($category->subCategories()->get() as $sub_category)
<li><a class="search-filter" href=<?=href_append_query(['sub_category' => $sub_category->sub_category_url])?>>{!! $sub_category->sub_category !!}</a></li>
It works for the first link, but all the rest of my href's come back the same (as the first one that enters the function)
Can anyone assist in getting this function to work so the foreach link has the appropriate href OR an entirely different "easier" way all together :)
My jQuery if it helps paint a better picture
$(document).on("click", '.search-filter', function(e) {
e.preventDefault();
$('#spinner-modal').modal('show');
$('#spinner-modal p').html('<b>Searching,</b> please wait...<br />');
query = $(this).attr('href');
history.replaceState(null, null, query);
$.ajax({
type: "GET",
url : query,
success : function(data, status){
$('#job-results').html(data);
$('#spinner-modal').modal('hide');
},
error : function(status){
console.log(status);
},
});
});

securely passing sensitive data from PHP to javascript

My scenario looks like this, I'm showing database paginated grid on the screen.
I want add a button to download CSV spreadsheet .
so I coded something like this:
$(function(){
var file_complete = false;
var final_sql = $('.initiate_download').val();
var orderby = $('#search_submit').data('orderby');
var $posturl = $url + "index.php/Spawner/launch_spawner";
$('#downloadModal').modal('hide');
$('.initiate_download').on("click", function(e) {
e.preventDefault();
$('#pleaseWait').html($html);
setTimeout(function() {
$.ajax({ // initiate download
url: $posturl,
type: "POST",
data: {
final_sql: final_sql,
orderby: orderby,
report: $report
},
success: function(data) {
var download_id = data;
// console.log(download_id);
check_download_status(download_id);
}
})
}, 2000);
})
});
<div class="row top-buffer">
<button id="search_submit" class="btn btn-primary initiate_download" type="submit" value="<?php echo $sql; ?>" data-orderby="<?php echo $orderby;?>" name="final_sql_lic" >Download List</button>
<span id="pleaseWait"> </span>
</div>
it works fine, but the problem is that you can view SQL with view page option, is there a way around it ?
What most people do is they don't embed the SQL on page, but instead expose URLs that handle the SQL stuff behind the scenes.
In your example, you might create a page like this:
http://website.com/api/csv?select=col1,col2,col3&orderBy=someColumn&where=someCondition
Then your php will take those parameters and generate the sql based off of those and run the query. Make sure you securely handle the input to avoid SQL injection (See http://bobby-tables.com/php.html).
The problem with your current scenario is that someone viewing your source will plainly see that you're passing SQL directly to your server, meaning they can generate their own SQL like: DROP TABLE table1, table2; or worse.

Symfony2 Passing ajax request data to a form rendering controller

I have a problem with a Symfony Form which I want to prefill based on which record is viewed beforehand. The intention is to create a means for changing the record data.
I navigate to the form page via javascript and send an ajax request to the same controller the form is rendered by.
This is part of the page used for viewing records:
<input type="button" id="changeRecord" value="change"/>
record id: <div id="recordID"> {{ record_id }} </div>
I access the record id through javascript/jQuery like this:
var CssSelectors = new Array(
"recordID"
);
function getCurrentRecordID() {
return parseInt($.trim($("#" + CssSelectors[0]).text()));
};
The button-code in javascript is the following:
$('#changeRecord').click(function () {
window.location.replace(Routing.generate(recordChangeRoute));
$.ajax({
url: Routing.generate(recordChangeAjaxRoute),
type: "POST",
data: {'recordID': getCurrentRecordID()}
});
// both Routes point to the same controller
// problem located here ???
The Symfony Controller Action is the following:
public function changePlasmidRecordAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$recordHandle = $em->getRepository('DataBundle:RecordClass');
$AjaxRequest = Request::createFromGlobals();
$RecordID = $AjaxRequest->request->get('recordID');
$recordToUpdate = $recordHandle->findOneBy(array('id' => $RecordID));
$updateForm = $this->createForm(new RecordClassType(), $recordToUpdate);
$updateForm->handleRequest($request);
if ($updateForm->isValid()) {
$em->flush();
return this->redirect($this->generateUrl('route_showRecord'));
} else {
return $this->render('DataBundle:RecordClass:updateRecord.html. twig',
array(
'RecordID' => $RecordID,
'form' => $updateForm->createView()
));
}
}
What I am trying to achieve is:
view a record
go to prefilled form
make changes and save
Viewing records, creating the form, persisting the changes to the database - all work. What does not work is accessing the needed ID inside the controller.
I can access the ajax request data the way I try in an other controller action without problems.
How is the "Form Request" interfering? Or is it?
Do I have to use an Event Listener?
Any help is greatly appreciated, thanks in advance!
I fixed it by leaving the ajax stuff away and submitting the required data via GET. Like so:
$('#changeRecord').click(function () {
window.location.replace(Routing.generate(recordChangeRoute, {'recordID': getCurrentRecordID()}));
});
Thank you for your input, all the best.

Saving changes to a dropdown box into a database in CakePHP

I am new to cake and mysql, and am trying to create a simple job tracking app. I want to have a dropdown box for each job with a list of the status' a job can be at. When a user changes the active item in the box I want to save this into the database.
Any help in how to handle this would be very much appreciated. Below is what I have tried so far:
How I create the set of forms in the view with the options taken from the enums in my database table:
<?php $id = count($jobs)-1; ?>
<?php for ($job = count($jobs)-1; $job >= 0; --$job): ?>
<tr>
<td>
<?php echo $this->Form->input('status'.(string)$id, array('type'=>'select', 'class' => 'statusSelect','label'=>'', 'options'=>$states, 'default'=>$jobs[$job]['Job']['Status'])); ?>
</td>
I am using a jquery script to set an on change listener for each dropdown and call an action in my controller:
$(".statusSelect").change(function(){
//Grab job number from the id of select box
var jobNo = parseInt($(this).attr('id').substring(6));
var value = $(this).val();
$.ajax({
type:"POST",
url:'http://localhost/projectManager/jobs',
data:{ 'id': jobNo,
'status':value},
success : function(data) {
alert(jobNo);// this alert works
},
error : function() {
//alert("false");
}
});
});
And I have this function in my controller:
public function changeState($id = null, $status = null) {
//I don't think the id and status are actually
//being placed as arguments to this function
//from my js script
}
Thank you!!!
You are POSTing to /projectManager/jobs, which corresponds to ProjectManagerController::jobs().
Your function is declared as public function changeState($id = null, $status = null). Assuming changeState(..) is a function within ProjectManagerController, this corresponds to /projectManager/changeState/$id/$status.
You need to switch the URL the AJAX is POSTing to. You can either do something like:
url:'http://localhost/projectManager/changeState/'+jobNo+'/'+value', remove the data {} and leave your function as is, or you can do
url:'http://localhost/projectManager/changeState', leave the data {}, change your function to changeState() and then use $this->request->data within changeState() to access the data.
I am guessing you have another function, jobs(), and that is why the AJAX is working properly and the alert is generating.

Categories