symfony - populating multiple drop down select lists (AJAX) - UPDATED - javascript

I have a form, with 2 fields, that are select lists.
I need to select an option from select_list_1 that then populates select_list_2
I have the following in my template:
<script type="text/javascript">
$(document).ready(function() {
$('select#sf_guard_user_profile_corp_id').change(function() {
$.ajax({
url: "updateAreaManager?corp_id=" + this.value,
dataType: "text/html",
success: (function(data) {
$('select#sf_guard_user_profile_area_manager_id').html(data);
})
});
});
});
</script>
This calls the executeUpdateAreaManager method, which currently is simply:
public function executeUpdateAreaManager(sfWebRequest $request)
{
$id = $request->getParameter('corp_id');
}
Would someone be able to help me get the data I need into the second select list?
Thanks

I am guessing that since you have a corp_id being passed to your action, you are trying to get a list of Managers based on a corp_id value.
In your action, you can query your database in order to get a result set, by doing something like:
$q = Doctrine_Query::create()->from('Manager m')->innerJoin('m.Corps c')->where('c.id=', $id);
$results = $q->execute();
You then can pass the results to your javascript, whatever way you want. I suggest straight HTML at this point. Your code will ressemble something like this (still in your action.class.php file):
echo "<p>Hi, I came from an action.</p>";
return true;
At this point, your javascript should be displaying that HTML on your page. Make it generate what you n eed, assuming an HTML form in your case.

Related

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

Collecting Row IDs in an Array using Jquery and then Querying those values for a new table

I'm trying to set up a function using jquery/php where a user selects a checkbox in a row with a specific ID (the id matches the primary key of the row data in my database), stores each row ID into an array, and then upon clicking the "compare selected rows" button passes it to a new page where a table of results is displayed with only those selected rows.
each input looks like this
<input type='checkbox' id='$id' class='compareRow'></input>
I am pretty novice at jquery and was planning to use a variation of a previous script I had put together to display dynamic row data in a modal. I am not sure if this code is relevant at all but it also passes the row id to another php page in order to query the database. Mind you this has only been used for single queries in the past where this new function would need some sort of foreach statement at the query level in order to process the array of IDs, im sure.
Heres the script I've been trying to tweak
$(function(){
$('.compareRow').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'query.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
success : function(r)
{
other code?
});
}
});
});
});
I know that there is much more needed here but this is just what I have so far, any help would be greatly appreciated.
Update, so I've created the page and have the following:
in my compareSelected.php I have the following code:
if(isset($_POST['post_id'])){
$compare_received = $_POST['post_id'];
}
print_r($compare_receive);
It returns undefined index.
I also modified the code to change to that page after like so:
$('.compareRowButton').click(function(){
var ids = [];
//loop to all checked checkboxes
$('.compareRow:checked').each(function(){
//store all id to ids
ids.push($(this).attr('id'));
});
$.ajax({
type : 'post',
url : 'compareSelected.php', //query
data : {post_id:ids}, // passing id via ajax
success : function(r)
{
window.location = 'compareSelected.php';
}
});
});
Not sure why it won't pick up the array values.
If you're set on your current implementation, you could maintain a reference to the data returned by each ajax call in the rows array. Later, you could implement a button that fires a function to append the row data to your table. Of course, you may need to parse the data returned by the request prior to appending.
$(function(){
var rows = [];
$('.compareRow').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'query.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
success : function(data){
rows.push(data);
}
});
});
$('.displayTable').click(function(){
// append to table or divs
});
});
I would suggest you avoid a page reload here. Or, if you must, make the Ajax request on the following page. You want to avoid tightly coupling your logic between different jQuery modules. Ajax should be utilized to load data asynchronously, without requiring a page reload.
On your code. your sending ajax request everytime you click the checkbox.
better to make another button or something before sending ajax request.
$('SOME_ELEMENT').click(function(){
var ids = [];
//loop to all checked checkboxes
$('.compareRow:checked').each(function(){
//store all id to ids
ids.push($(this).attr('id'));
});
$.ajax({
type : 'post',
url : 'query.php', //query
data : {post_id:ids}, // passing id via ajax
success : function(r)
{
other code?
});
}
});
});

Passing values for JQPlot from PHP

As a novice js and jqplot programmer, I need guidance on passing an array of value from php to an external javascript for plotting (using jqplot). I am confused about the order and how html, php & external js, jqplot is called. A short sample code structure will be very helpful to follow. We may use the following sample codes as guide. Thanks
$(document).ready(function(){
var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});
Instead of the fixed data points above, I want them to dynamically loaded via an array from the following php script.
<?php
$Start_Value = $_POST['Start'];
$End_Value = $_POST['End'];
for($i=$Start_Value;$i<=$End_Value;$i+++)
$Plot_Val[$i] = $i + 2;
json_encode($Plot_Val);
?>
You have several options. Here are the 2 easiest:
Just 'paste' the array from PHP as a JavaScript global variable.
Add <script>var myData = <%= json_encode($Plot_Val); %>;</script> at the top of your page and then use myData in place of the data array.
Even better option is to use Ajax to call the PHP page from JavaScript and get the results , separating front-end and back-end code.
Best way is to use AJAX, something like this in JS:
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
Update: To get your values from a form, you cannot put form action to js, but rather use js to get the values from a form. So the form itself shouldn't do a POST request, but rather the js should take the values from a form and send the POST.
Something like this:
<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>
JS, we will wrap the above AJAX code into a function:
function submitValues(startValue, endValue) {
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
}
$(document).on('click', '#submitButton', function(){
var start = Number($('#start').val());
var end = Number($('#end').val());
//I guess you need numbers instead of text, that's why they are wrapped inside Number()
submitValues(start, end);
});
This should work.
Keep in mind that I have no idea what your form looks like, this is just a dummy example, but it should be similar enough. You get the form values with the jQuery's .val() method and then give those values to the ajax function.

how to access and output json results from $.ajax() success callback

I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}

adding new dropdown lists in asp without reloading the page

I would like to have a page that would contain:
hyperlik "Add new country".
After clicking this link by user, dropdown list with names of countries should appear. However this hyperlink should stay on this page. When user click this hyperlink once again, second dropdown list with exactly the same names should appear. This should be repeat as long as user clicks hyperlink.
It is important that this page shouldn't be reloaded.
Does anyone has any idea how can it be made?
The typical way to achieve this is to have your Add new country link trigger an ajax call out to a page you create which will provide the data for your list.
The preferred method these days seems to be having that page you call build up a JSON response, then your callback on the ajax method where you called it can populate that data into a drop down.
The page you call from AJAX could be something simple like this:
protected override void Render(HtmlTextWriter writer)
{
Dictionary<string, int> myStuff = new Dictionary<string, int>();
myStuff.Add("country1", 1);
myStuff.Add("country1", 2);
JavaScriptSerializer jss = new JavaScriptSerializer();
Response.Write(jss.Serialize(myStuff.ToList()));
Response.ContentType = "application/json";
}
Use this jQuery on your main page:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
getCountries();
});
});
function getCountries() {
$.ajax({
url: "ApiPage.aspx",
dataType: "json",
success: function (data) {
for (var i in data) {
$("#myDropDown").append($('<option></option>').val(data[i].Value).html(data[i].Key));
}
}
});
}
</script>
Tested and working. (in a simplified example) I did have to convert from Dictionary to List for the json serializer to make it an array as desired. See the updated Serialize call. There is also some validation, e.g. did the ajax call return real data?, that would need added to a real life implementation.
It looks like you are doing it a least approximately right.
in the HTML if you have some tag that surrounds the area you want the drop down box to then it is simple.
for example:
in HTML:
Add new country
<div id="dropdownarea"></div>
in javascript:
function addDD(){
document.dropdownarea.innerHTML += "HTML code for the drop down that you want";
}

Categories