I have two tables, has-many relationship,
in the master add.ctp, allow user to upload 0~5 files(file path information are stored in details table)
I want to dynamically display attachment(detail) form in the master/add.ctp
1, user choose number of files want to upload from dropdown list,
echo $this->Form->input('attachments', array( 'options' => array(1, 2, 3, 4, 5),'empty' => '(choose one)', 'onchange' => 'showNumber(this.value)'));
then forloop
{
echo $this->Form->input('attachment_path', array('type'=>'file','label' =>'Attachment, Maximum size: 10M'));
}
//but I don't know how to capture this.value, I know Javascript can not pass value to php.
or user click 'add another attachment' link, then detail form shows up.
How to achieve this function, any help would be appreciated.
I have read this article:
Assign Javascript variable to PHP with AJAX
and get same error: the variable is undefined
Edit:
http://cakephp.1045679.n5.nabble.com/Adding-fields-to-a-form-dynamically-a-complex-case-td3386365.html
'For each field use a default name with [] at the end (which will make
it stack like a array) example: data[][book_id] after the fields have
been submitted'
Where should I place the []?
I think you should use Ajax for this.
Simply create an ajax call on select.change() and then a method in the controller that returns the necessary info.
You can return an array of data using echo json_encode(array('key' => 'value')) directly on your controller (or better in a custom view) and access it with Javascript:
success: function(data) {
alert(data.key);
}
Edit...
In your javascript use something like...
$('select').change(function(e) {
var select = $(this);
$.ajax({
type: "POST",
dataType: "json",
url: "/attachments/youraction",
data: { data: { id: select.find(":selected").val() } },
success: function(data) {
for (i in data) {
var input = $('<input>', {type: "file", label: data[i].Attachment.label})
$('form.your-form').append(input);
}
}
})
});
Then in "Yourcontroller" create "youraction" method:
<?php
class AttachmentsController extends AppController
{
public function youraction()
{
if (!$this->RequestHandler->isAjax() || !$this->RequestHandler->isPost() || empty($this->data['id']))
{
$this->cakeError('404');
}
// Do your logic with $this->data['id'] as the select value...
$data = $this->Attachment->find('all', array('conditions' => array('id' => $this->data['id'])));
// ....
// then output it...
echo json_encode($data);
// This should be done creating a view, for example one named "json" where you can have there the above echo json_encode($data);
// Then..
// $this->set(compact('data'));
// $this->render('json');
}
}
It's more clear now?? If you have doubts about ajax + cakephp you should do a search on the web, where you will find a lot of tutorials.
I use this approach to achieve this function. (finally got it :))
http://ask.cakephp.org/questions/view/foreach_loop_with_save_only_saving_last_member_of_array
Yes, AJAX can do lots of things, to me, it's very hard to understand the logic in a day..
Anyway, Thanks again.
Related
I am working on the filter part in search page but the issue is In the main search page all the result looped from the controller, and Now I am using jquery for the filter process, but things are confusing. How to do this in a right way?
So here is the process :
Step 1 : user search something Like "support" and then system go to the searchController file and give the result
return view('/search')->with(["documents" => $results, "filters" => $filters]);
Here $filter indicates the category filters; Like this
Then When User click on any category then it will filter the result but now the issue is I am using jquery and now things getting weird. Can somebody help me on this.
JS Code :
$(document).on("click", ".category_filter1",function() {
var test = new Array();
$("input[name='category_filter']:checked").each(function() {
test.push($(this).val());
});
showValue(test);
});
function showValue(data){
$.ajax({
'url': 'search/filter/'+(data.length > 0 ? data : "all"),
'type': 'GET',
success: function(response){ // What to do if we succeed
if(response.data == "success")
document.getElementById('result').innerHTML = response.categories;
},
error: function(response){
// alert('Error');
}
});
}
and The Controller from where all result came from :
public function filter($data){
$t_data = explode(',' , $data);
$filters = $this->load_filters();
if(count($t_data)>0 && $t_data[0]!== "all"){
$results = DB::table('documents')
->whereIn('category', $t_data)
->paginate(5);
}else{
$results = Document::paginate(5);
}
return redirect('/search')->with(["documents" => $results, "filters" => $filters]); // This part is really confusing
}
So the flow will be like this :
Summarizing from as discussed in comments,
In order to call the controller without refreshing the page you need to use ajax, (use jquery or any other frontend framework). Return your response as json,
return response()->json($your_return_array);
For images store it in public folder, such as public/images/your-image.png.
Then call it using url() method in your blade.
<img src="{{url('/images/your-image.png')}}" alt="Image"/>
i am trying to filter custom post type called podcasts with ajax, using two custom taxonomies id as parameters, genre and country.
This is the front end: https://imgur.com/a/G2vB62q.
As you can see, i can choose a genre or/and a country to use as filter for my posts (below there is an array with the parameters that are passed).
In my podcast page i have two foreach, with link within, with name and the term_id.
foreach ($genre/$country as $category) {
echo '<a class="button-prova/button-prova2 premuto2"
name="keyword/keyword2" id="keyword/keyword2"
value="'.$category->term_id.'"
href="#">'.$category->name.'</a>';
}
Then, within function.php, i have my ajax function and ajax-fetch.
$( document ).ready(function() {
$(document).on("click touchend", ".premuto, .premuto2", function () {
fetch(this);
});
});
function fetch(prova){
if($(prova).attr('name') == 'keyword'){
var1 = $(prova).attr('value') ? jQuery(prova).attr('value') : 0;
} else
{
var2 = $(prova).attr('value') ? jQuery(prova).attr('value') : 0;
}
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: [var1,var2] },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
At first, when i choose one genre, the country is set to 0, as you see in the code. But when i select the other taxonomy, genre set to 0 (or vice versa, like in the image). There is a way to store my precendent selection?
Since you use AJAX. The previously selected value will persist if you declare the variable outside the functions. Try this.
var keywords = {};//Put this line outside of the function, so it available globally
$(document).ready(function() {
$('.premuto, .premuto2').on("click", function () {
keywords[$(this).attr('name')] = $(this).attr('value');
fetch();
});
});
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { 'action': 'data_fetch', 'keywords': keywords },
success: function(data) {
}
});
}
The keywords variable will look like this:
{keyword:0,keyword2:4}
And it will be read as an associative array in the PHP side.
Additional note:
Using javascript global variables can lead to clashing variable names from other scripts/plugins. To remedy this, you can encapsulate all your scripts inside a self-invoked function like this:
(function(){
/*PUT YOUR PLUGIN SCRIPTS HERE*/
})();
The buttons you use to filter have a certain markup (probably a class) when clicked. You can use that class as a toggle. In your 'fetch' function you can do:
keywords = Array();
$('.filters.toggle').each(function(){ // all filters with the toggle class
// add those values to the keywords array
keywords.push($(this).val()); // .val() is the same as attr('value')
});
keywords will be an array of all genres, countries that are toggled on.
then:
data: { action: 'data_fetch', keyword: keywords},
On my model I have the following function which is a query to inner join 3 tables
function get_all_listaproveedorfamilia($clave)
{
$this->db->select('proveedor.razonSocial, proveedor.nombre1, proveedor.telefonoFijo1, proveedor.telefonoMovil1, proveedor.correoElectronico1, proveedor.tipo, familia.clave');
$this->db->from('proveedor');
$this->db->join('relacionproveedorfamilia', 'relacionproveedorfamilia.idProveedor = proveedor.id', 'inner');
$this->db->join('familia', 'familia.id = relacionproveedorfamilia.idFamilia', 'inner');
$this->db->where('familia.clave', $clave);
$this->db->order_by('proveedor.razonSocial');
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result_array();
}
}
The $clave value is a string retrieved from a select dropdown, and I send it to my controller using ajax
Jquery function in my view to send $clave value
$('#idFamilia').change(function(){
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione"){
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
}
});
}
});
Here is the code from my controller, where I use the clave value and call the function in my controller
function obtenerListaProveedorFamilia(){
$this->load->model('Proveedormodel');
$clave = $_POST['clave'];
$data['listaproveedorfamilia'] = $this->Proveedormodel->get_all_listaproveedorfamilia($clave);
$data['_view'] = 'proveedor/index';
$this->load->view('layouts/main',$data);
}
I want to visualize the array returned by the function to check if the query is working and getting the values i want to retrieve. I have already tried the following methods to visualize the array adding addtional code to my jquery function $('#idFamilia').change(function(){});
-Get the array from the view and check it on the browser's console
var test = <?php echo json_encode($listaproveedorfamilia); ?>;
console.log(test);
-Trying to append print_r to a pre tag
$('#prueba').append('<?php print_r($listaproveedorfamilia) ?>');
With both options I get the following PHP error on my view
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: listaproveedorfamilia
Filename: proveedor/index.php
This error appears as soon as the page loads, but it should wait for the user to select an option from the select dropdown and then use that option to build the query. How can I fix this and check the content of my array?
You need to add the success method to your ajax call. This is where the data created at the server will be sent.
$('#idFamilia').change(function () {
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione") {
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
},
success: function (returned) {
console.log(returned);
}
});
}
});
You can use your browser's web dev tool to see what the javascript console has logged.
Because we don't know what the view file contains it's hard to comment on what to expect.
Typically ajax calls are used to return html that return is put into the DOM using $("some_selector").html() or a variety of other DOM manipulation methods to update the current browser screen.
Another way to "visualize" the return would be to simply append it to what is already on the screen. This is not likely what you'll eventually want. But you'll be able to see what came back.
Change the success function to this
success: function (returned) {
$('body').append(returned);
}
I'm new to stackoverflow (as a member at least) and I have a question.
I'm also new to PHP by the way.
Thing is:
I want to dynamically fill a second dropdown list with entries based on a first dropdown list (I want to show cities based on a selected province).
I managed to get the selected province to an external PHP file with an AJAX call in Javascript.
But when I include the external PHP file in my original PHP file, the variable of the external file is undefined.
The AJAX call is fired with an onchange event on the first dropdown menu.
And maybe you can also help with how I use that variable to get the right content in the second dropdown. I've used a multidimensional Array for that.
HTML:
echo('<select name="provincie" id="provincie" onchange="ProvinciePHP()">');
foreach ($provincie as $provincies){
echo ("<option> $provincies </option>");
}
echo ('</select>');
echo('<select name="stad" id="stad"> </select>')
PHP ARRAY:
$provincie = array(
'Selecteer een provincie',
'Drenthe',
'Flevoland',
'Friesland',
'Gelderland',
'Groningen',
'Limburg',
'Noord-Brabant',
'Noord-Holland',
'Overijssel',
'Utrecht',
'Zeeland',
'Zuid-Holland',
);
$stad = array(
'Drenthe' => array("Assen", "Emmen", "Hoogeveen", "Meppel"),
'Flevoland' => array("Almere", "Biddinghuizen", "Dronten", "Lelystad"),
'Friesland' => array("Heerenveen", "Joure", "Leeuwarden", "Sneek"),
'Gelderland' => array("Apeldoorn", "Arnhem", "Nijmegen", "Zutphen"),
'Groningen' => array("Delfzijl", "Groningen", "Stadskanaal", "Veendam"),
'Limburg' => array("Maastricht", "Roermond", "Sittard", "Venlo"),
'Noord-Brabant' => array("Breda", "Den Bosch", "Eindhoven", "Tilburg"),
'Noord-Holland' => array("Alkmaar", "Amsterdam", "Haarlem", "Hilversum"),
'Overijssel' => array("Deventer", "Enschede", "Hengelo", "Zwolle"),
'Utrecht' => array("Amersfoort", "Breukelen", "Utrecht", "Zeist" ),
'Zeeland' => array("Goes", "Middelburg", "Terneuzen", "Vlissingen"),
'Zuid-Holland' => array("Alphen a/d Rijn", "Den-Haag", "Rotterdam", "Schiedam"),
);
function getProvincie(){
var provincie = $('#provincie option:selected').val();
$.ajax({
type: "POST",
url: "getprovincie.php",
data: {data: provincie},
success: function(data) {
alert(data);
$('#stad').css('display','inline');
},
error: function(data) {
}
});
}
//PHP page to where the AJAX call points:
<?php
$resultaat = $_POST['data'];
echo($resultaat);
I'm quite new to programming, and im trying to update a certain column in a database using php and javascript.
The data base only has 2 columns, seatnums and status. Basically, i want the status to reset back to 1 if the status is currently 0. Could anybody point me in the right direction?
I have a class inside a div in my HTML:
<a class='two' href="javascript:databaseReset() ">Reset</a>
My javascript function (Part im struggling with):
function databaseReset();
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
function over(id) {
selectedseat=$(id).attr('title');
$(id).attr('src','images/mine.gif');
$(id).attr('title', 'Available');
}
function out(id) {
$(id).attr('src','images/available.gif');
}
my php file:
<?php
include("dbconnect.php");
$query="UPDATE seats SET status=1 WHERE status=0";
$link = mysql_query($query);
if (!$link) {
die('error 2');
}
?>
I assume it was simply a typo, but your function call needs to wrap brackets around the ajax call:
function databaseReset(){ //<---*****Add these braces*****
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
}; //<---*****Add these braces*******
your code seems to declare the function, but not assign its functionality
Also, the data section is unnecessary, as it is not used. In fact, since you are not posting data, you can use the "GET" method instead.
Beyond that your code looks good, can you please specify what the issue is?