Yii array helper selecting already set value from database - javascript

Am using array helpers if data exists i want to select the value...here product category master id is a foreign key in product master table.
A modal gets called on edit button and it uses the same modal as create button
but the fields are populated using hidden input field.
I want to select the already set value from the database.
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
The above code is not working.
<?= $product_form->field($form_product_model, 'product_category_master_id')->dropDownList(
ArrayHelper::map(ProductCategoryMaster::find()->all(),'id','category'),['prompt'=>'','class'=>'form-control select2','style' => 'width:100%;height:80% !important']
);?>
function editProduct(id) {
console.log(id);
$.ajax
({
type:"GET",
url: "<?= Yii::getAlias('#web')?>/product-category-master/product?id="+id,
cache: false,
dataType:"json",
success: function(data)
{
console.log(data);
$('#sourceproduct').click();
$("#newid").val(data.id);
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
//document.getElementById("editbutton").showModal();
//var myArr = JSON.parse(data);
return false;
}
});
}

Found the solution i just had to put
$('#productmaster-product_category_master_id').val(data.product_category_master_id).trigger('change');
instead of
$('#productmaster-product_category_master_id').val(data.product_category_master_id);

Related

Last chance at jQuery AJAX Toggle

I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData

Post Multiple Forms Data Via Ajax to Single View in Django

i have two forms on a page. 1st is shown and 2nd one is hidden.
1st form shows list of users and their emails in grid and pagination. when i select a multiple users from grid then a div shows up on the right side of the gird. which will be used to send email to selected user.
2nd form that shows up will input email subjects from users and then pass these whole data to django views.
i have user this ajax code to send whole data to the views function.
$("#_send").click(function(){
var frm = $('#messageform');
frm.submit(function () {
var selectedID = [];
$(':checkbox[name="selectedvalues[]"]:checked').each(function(){
selectedID.push($(this).data("email"));
});
$.ajax({
type: 'POST',
url: '/sendemail/',
processData: true,
data: {'frm':frm.serialize(),
'selectedID': selectedID},
success: function (data) {
alert(data);
},
error: function(data) {
alert("error");
}
});
return false;
});
});
and in django views i am catching like this;
def Send_Message(request):
checked_items = request.POST.getlist('selectedID[]')
Msg_Content = str(request.POST.get('content'))
frm = request.POST.get('frm')
print checked_items
print frm
print Msg_Content
it outputs like this;
abc#gmail.com,abc123#cogilent.comm
csrfmiddlewaretoken=dP7VkSQdWx0fXuX0kJC46arv6HFElvgz&subject=Hi+This+is+testing+message&content=ddddd
but i want these data seperately, message content and message subject.
When you serialize the data; you should be able to do request.POST.get('subject') etc

Codeigniter: How to pass array from controller to view without refresh

Basically I have a form in the view with one input enabled, and multiple inputs disabled (only to show information derivated from the unique input).
Now, I need to send this input to the controller to make a query, and send back to the view an array with the fields information but without refresh the site (because I cant loose the progress that I have in this page).
Maybe the solution is to use javascript to send the controller the input field, and in the function return the array of values to refresh the form, but how?
EDIT: Sorry for my bad english.
var input = $('#input').val();
$.ajax({
type:"POST",
url: <?php echo base_url().'controllername/action'?>
data: {input : input},
success: function(data){
// this data should be contain an arra
$('#where_to_insert_array').html();
}
});
In controller action and in action
function action()
{
$data = $this->input->post('input');
get data from database on $data
make its array and then echo it
echo array();
}
Finally I understand how to pass the array from the controller to the view dynamically, this is the code:
The view javascript:
function getClient(){
if($('#cedula_cliente').val()){
$.ajax({
type : "post",
url: "<?php echo base_url().'index.php/clientes/getClienteFactura'?>",
cache: false,
data : {cedula : $('#cedula_cliente').val()},
success : function(json){
var obj=jQuery.parseJSON(json);
if(obj[0]){
$('#nombre_cliente').val(obj[0].nombre);
$('#apellido1_cliente').val(obj[0].apellido1);
$('#apellido2_cliente').val(obj[0].apellido2);
$('#dir_cliente').val(obj[0].dir);
}else{
alert("Usuario no encontrado");
}
},
});
}else{
alert("Debe ingresar una cédula de usuario");
}
}
Im using obj[0] because "cedula" is the primary key and It never will return more than 1 row.
And this is the controller function:
public function getClienteFactura(){
$cedula = $this->input->post('cedula');
$query = $this->Client_model->getClientByCedula($cedula);
echo json_encode($query);
}
Thanks for the answers, maybe I should have looked better on google, the key to solve the problem was Json.

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

Populate jqGrid dropdown using beforeShowForm Event

I'm trying to dynamically populate a dropdown when a user is trying to add a new record in a detail jqGrid. Here's what I have so far. It's pulling in the data fine but it just won't set the value to the dropdown. Any help would be greatly appreciated.
beforeShowForm: function(formid) {
var sr = $("#list").jqGrid('selrow');
if (sr) {
// get data from master
var UserID = $("#list").getGridParam('selrow');
var roles = $.ajax({ type: "POST",
url: '<%= ResolveUrl("~/Admin/GetRoles/") %>' + UserID,
dataType: "json",
async: false,
success: function(data) {
}
}).responseText;
// set the field in detail with the value of mnaster
$("#UserID", formid).val(UserID);
// try and populate dropdown
$('#detail').setColProp('Description', { editoptions: { value: roles} });
} else {
// close the add dialog
alert("no row is selected");
}
}
In your first question I explained you how to use dataUrl to generate the contain of the dropdown list dynamically. If you use form editing to modify the grid data you can use beforeInitData instead of beforeShowForm to modify the dataUrl to '<%= ResolveUrl("~/Admin/GetRoles/") %>' + $("#list").jqGrid('selrow') before the form will be filled. In the way you can simplify your code, make the ajax request asynchronous and the question with setting the values to the dropdown control will be solved automatically.

Categories