I have an ajax call under a function called refreshClick that is meant to fill a div with a select box that is generated by php.
Javascript:
function refreshClick() {
$.ajax({
url: "modules/elements/customersList.php",
success: function(data){
$('#refreshdiv').html(data);
}
});
}
HTML:
<div id="refreshdiv">test</div>
PHP:
while($row = $result->fetch_assoc()){
$returnString .= '<option value="'.$row['customerid'].'" data-tokens="'.$row['Phone'].$row['customerid'].$row['Email'].$row['ID'].$row['alt1Name'].$row['alt1Info'].$row['alt2Name'].$row['alt2Info'].'">'.$row['Name'].'</option>';
}
echo '<select data-live-search="true" class="selectpicker form-control" data-selected-text-format="count > 1" style="width:100%" name="customer">';
echo $returnString;
echo '</select>';
So as you can see this code is pretty simple. I cannot for the life of my figure out whats going wrong. I have a button just above the refreshdiv div that calls the refreshClick() function, but when I click it the word test disappears. It LOOKS like it just clears out the div, but if I Inspect Element, I can see that the div was filled the way it was suppose to be, with the correct data aswell, but nothing is visable. Could someone help me figure out where I am going wrong?
Side note: The reason I want to use it this way is so I can call this function any time to refresh the contents of the select box, so that way if whoever is using the software updates the customer list they can refresh the select box without refreshing the page. If there is an easier way to do this, please enlighten me.
--Test data screenshot
This is console.log(typeof data) and console.log(data)
--Inspect element screenshot
(Ignore the hideous refresh button, it's temporary.) I would also like to include, in the page before I click the refresh button the word "Test" shows in the refreshdiv div. It DOES show.
Oh, you are using bootstrap. That's the problem. Bootstrap needs to init every select. It does on startup, but every time it changes you need to run:
$(select).selectpicker('refresh');
To re-init the new ones.
Related
Basically, it's a form that needs specific information, "Tamanho"/"Tamanhos" means "size"/"sizes", which I have a list of acceptable sizes that goes from 8 to 30 that are registered in a database (to make it easier to add more acceptable sizes if needed), the user should be able to chose many "sizes" and put a quantity of "how many products of that size?" in an input right after it.
I was able to create an JavaScript function AddTam() called by a button that generates one more block to fill, with a select, and all the block's select inputs are named Tam[], so their values pass as an array, and their respective inputs named as "TamQnt8", the number 8 at the end refers to the size chosen, it changes every time the user chooses other size for the same block using other function DefTam(), that way, I could verify the sizes array in the Back-End, and use it to get their respective quantities and organize it all in an array, to finally send it to the database.
But for some reason, when I test if the information is passing through correctly, it doesn't send any data in the key "Tam" saying it's undefined when I tested it, in PHP I'm testing: if(!empty($_POST['Tam'])) but i also tried isset().
I just don't know what's wrong, so I was asking if isn't it the method I'm using insertAdjacentHTML() to generate the blocks, and if it works as well as createElement() in forms.
Also, when I created the blocks manually and instead of many selects I used checkboxes, it was working, just decided to change to the generated method because the checkboxes took way too much space in the screen, even worse for mobile.
Here's a simplification of the code in HTML:
<form method="post">
<section>
<div class="littlebutton" id="addTamanho" onclick="AddTam()">Add Tamanho</div>
</section>
<script>
var contador = 0;
function AddTam(){
let tamTitulo = document.querySelector('#addTamanho');
tamTitulo.insertAdjacentHTML("afterend",
'<div class="cellTam cell">'+
'<select name="Tam[]" class="'+contador+'tam8 '+contador+'" onchange="DefTam(this)">'+
'<?php foreach ($_SESSION["tamanhos"] as $key => $value) { ?>'+
'<option value="<?php echo $value["tamanho"];?>"><?php echo $value["tamanho"];?></option>'+
'<?php }?>'+
'</select>'+
'Tem => <input class="qnt" id="'+contador+'tam8" name="TamQnt8" type="number" min=1>'+
'</div>');
contador++
}
function DefTam(ElementTam){
let infoTam = ElementTam.value;
let refTam = ElementTam.getAttribute("class");
refTam = refTam.split(" ");
let relInput = document.getElementById(refTam[0]);
ElementTam.setAttribute("class", refTam[refTam.length-1]+"tam"+infoTam+" "+refTam[refTam.length-1]);
relInput.setAttribute("name", "TamQnt"+infoTam);
relInput.setAttribute("id", refTam[refTam.length-1]+"tam"+infoTam);
}
</script>
<button class="post" name="Inserir" type="submit">Postar</button>
</form>
Output: The Add Tamanho button, 3 generated blocks of the form and the Elements tab of browser's Developer tools
Sorry if I wrote something wrong or weirdly, still learning English, or if it's just a silly mistake in my code, also, any help is welcome.
I'm having an issue using javascript onchange event listener in cakephp3.7.
In fact I have a e-commerce web application built with cakephp3.7 running fine. Now I want to enhance the sales submission form in the website, by dynamically loading extra fields that sellers fill based on the category of products the seller chooses. That means, if the sellers chooses electronic from the category input field, then the electronic exta fields that were previously of style display:none in the CSS, will now be displayed.
The electronic extra fields are as follow with id=elctronic:
<div id="electronic">
<?php echo $this->Form->control('subcategorie',['label'=>'choose sub category', 'class'=>'form-control', 'option'=>['Computer','Phone','Multimedia'],'empty'=>'choose'); ?>
<?php echo $this->Form->control('brand',['class'=>'form-control', 'placeholder'=>'the brand']); ?>
<?php echo $this->Form->control('model',['class'=>'form-control', 'placeholder'=>'the model']); ?>
</div>
Then if the product is about clothes for exemple, the electronic input fields will be hidden and the clothes extra fields will be displayed with id=clothe as bellow:
<div id="clothe">
<?php echo $this->Form->control('Gender',['label'=>'What gender?', 'class'=>'form-control', 'option'=>['Males','Females'],'empty'=>'choose'); ?>
<?php echo $this->Form->control('Size',['class'=>'form-control', 'placeholder'=>'Size']); ?>
<?php echo $this->Form->control('model',['class'=>'form-control', 'placeholder'=>'the model']); ?>
</div>
The category input field where the onchange event listener is used is as bellow, and the javascript function extraForm() should get called, but it doesn't and there is the issue:
<?php echo $this->Form->control('category',['id'=>'categ','label'=>'choose category', 'class'=>'form-control', 'options'=>['electronics','clothes'],'empty'=>'choose'),'onchange'=>'extraForm("categ"); ?>
And then in the layout for the method add() of ProductsController, I set the extraForm() function as below:
<script>
function extraForm(s1){
var s1=documentgetElementById(s1);
var s2=documentgetElementById("electronics");
var s3=documentgetElementById("clothes");
if(s1.value == "electronics"){
s2.style.display = "bloc"
} else {
s3.style.display = "bloc"
}
}
</script>
It's three days now since I can't figure out what I'm missing. Yesterday I searched through the net and there were people saying that event listener such as onchange, onclick and onselect event listeners are deprecated for cakephp 3 and I don't understand how. So how to achieve the dynamic load of extra input form triggered by selected option in cakephp3.7.
**
FIRST EDIT
**
Like I said in the comments, I simplified the question to make it understandable. The full context is that I have 2 standarts fields category and subcategory. When the user select a category, an AJAX fonction presentes to the user a list of subcategories to choose from.
My AJAX is:
$(document).ready(function(){
$('#getSubCat').change(function(e){
$.ajax({
type: "POST",
url: "/products/getsubsaterogie",
data: {categ: $(this).find('option:selected').text()},
dataType: 'json',
cache: false,
headers : {
'X-CSRF-Token': $('[name="_csrfToken"]').val()
},
success: function(data){
console.log(data);
let subcat = $('#subcategories')
for (let sc of data) {
console.log(sc.subcategorie)
$('<option />', {value: sc.subcategorie_id, text: sc.subcategorie}).appendTo(subcat);
}
}
});
e.preventDefault();
})
})
The categorie input field is:
<?php echo $this->Form->control('categorie_id', ['id'=>'getSubCat', 'options' => $categories, 'label' => __("What category ?"), 'class'=>'form-control', 'empty' => '(choose)']);
?>
After the user choose a category the list of subcategory fetched from database by AJAX appears well in this form input, and this is where the onchange is set to call the extraForm() function, but does not:
<?php echo $this->Form->control('subcategorie_id', ['id'=>'subcategories', 'label' => __("What subcategory ?"), 'class'=>'form-control', 'options'=> [],'empty' => '', 'onchange' => 'myFormShow("getSubCat","subcategories")']);
?>
And After subcategory selected, the relevant extra form doesn't appear, but if I manually change display to bloc in CSS, it does show, which means that the javascript function isn't called onchange event, I even used onselect but still not having it.
And the javascript function extraForm is actually receiving 2 arguments like extraForm(s1, s2). This is my real context.
I'm really stuck here. Any help is really appreciated, thanks in advance.
- EDIT ACCORDING TO GREG'S REQUEST:
According to Greg's comment this is my cake code to generate the list inside subcategory. I didn't know all these details were necessary since I thought it was cakephp 3 issues regarding javascript events listeners.
public function getsubsaterogie(){
if($this->request->is('ajax')){
$d = $this->request->getData();
$subcat = '';
$cat = TableRegistry::get('Categories')->find()
->where(['categorie' => $d['categ']])
->select('id')
->first();
if(!empty($cat)){
$subcat = TableRegistry::get('Subcategories')->find()
->where(['categorie_id' => $cat->id])
->all();
}
echo json_encode($subcat);
exit();
}
}
Thanks in advance, best regards !
It's always very daunting not knowing what the real problem is, since this is not my first foray in using ajax along with cakephp. I can attest on Greg Schmidth great experience when he said "the subcategories won't display at all". In fact, 2 days later and when endeavouring to hunt down the real issue,
I emptied cache,
I removed browser cookies
And suddenly the whole app started behaving unexpectedly,
The subcategories were not displaying any more
The jQuery based animations codes I made for animating advertisements
on the website frontend were also getting weird.
These all made me think of jQuery issue, and indeed it was the real issue. I'm using 3 differents versions of jQuery and all 3 versions are necessary for my projects. The 3 jquery versions were silently conflicting and were not giving me any clue to troubleshoot what was going wrong. Now that I know it's a jquery issue, I used the jQuery noConflict approach described in this link
<?= $this->Html- >script('http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js') ?>
<?= $this->Html->script('lecker/ajax/getSubCategorie.js') ?>
<script>
var jQuery_1_12 = $.noConflict(true);
</script>
<?= $this->Html->script('https://code.jquery.com/ui/1.12.1/jquery-ui.js') ?>
// This for the second jquery version
The description was not as straightforward as it seemed but other questions on stackoverflow also contributed to help me.
Ultimately, It's not an issue about whether we can still use enchange event with cakephp version 3 form helper, but rather an issue about the right $ variable used by jquery in ajax code to get subcategories, it was not yielding.
Using bootstrap-editable.js, I have various fields in a table & form all working pretty well, including a few selects.
For one particular select, I want to see the text and save the ID back to the database (whereas, the other selects are just displaying and saving text).
The relevant javascript:
$('#cntryID').editable({
type: 'select',
autotext: 'auto',
pk: <?php echo($addrID);?>,
url: '/include/update_address.php',
// adds a default value if one had already been set
<?php if ($cntryID<>"") echo("value: $cntryID, \n"); ?>
source: [<?php
// php code that enumerates the values and prints them as below
echo("\n\t\t" . '{value: "' . $id . '", text: "' .$choice .'"}');
}
?>]
});
});
I've made a jsfiddle to demonstrate:
https://jsfiddle.net/pcartagena/qde6k043/
I thought there was an example that demonstrated this very concept but I can't seem to find it to compare.
Ok. I'm embarrassed to have to admit that this one took entirely too long to figure out... but...
The problem, as shown in the jsfiddle was that the HTML:
Just the relevent portion shown:
228
The 228 I putting in between the open/close a tag was throwing it off. The fact that value was set in the jquery code didn't matter.
I'm posting the answer if only to save someone from wasting as much time as I did on this. :-)
I have two textareas, an iframe and a submit button. They are all in the same page. What I want to do is that; user will code some html and javascript codes in to the first textarea. the second one is already hidden to pass the javascript codes. After the user click submit button, s/he will see results in the iframe. actually what i am saying is something like w3school's trying page.
my submit button is:
<INPUT type="submit" value="Run the Codes" name="submit" onclick="sendthem()">
my textarea's are:
<TEXTAREA id="textareaCode1" style="WIDTH:100%;HEIGHT:400px" name="code22" rows="21" wrap="logical" cols="42"><?=$code;?></TEXTAREA> //the user's textarea
<textarea id="textareaCode" style="WIDTH:100%;HEIGHT:400px" name="code" rows="21" wrap="logical" cols="42"><?=$code;?></textarea> //this is actually hidden (style="display:none;") one but to see what happens, temporary i made it visible.
and my sendthem() function is:
function sendthem()
{
var t=document.getElementById("textareaCode1").value; //the visible textarea
t=t.replace(/</g,"SMALLER"); //string manipulation to pass js codes via php post
t=t.replace(/>/g,"GREATER"); //string manipulation to pass js codes via php post
t=t.replace(/=/g,"EQUAL"); //string manipulation to pass js codes via php post
document.getElementById("textareaCode").value=t; //manipulated code goes in to hidden textarea
document.getElementById("sampleform").submit(); //send the form
}
And my php code is:
<?
$code = $_POST['code'];
echo "$code"; // here i can see the manipulated code like "SMALLERhtmlGREATER"
?><br/><? // to try it :
$code = str_replace("GREATER", ">", $code); // I reverse the changes
$code = str_replace("EQUAL", "=", $code);
$code = str_replace("SMALLER", "<", $code);
printf("%s",$code); //and there is no js codes.. i tried echo or other php print commands also.
?>
Here is a screenshot http://i57.tinypic.com/sghcba.png (I hope it helps)
Now.. I think my problem is in the PHP part. Can anyone tell me why I can't see the JS part of code, after reversing changes ?
And please, I don't want to change all my codes with jQuery or AJAX etc.. I want to fix this code. Thanks in advance...
I am trying to populate a text field with the value of the select field.
So based on the selection the text field should change.
In this case, I am selecting First Name and Last name of the person and in the
option value="I have person email here"
Now, I am using onchange event on select element which calls the findemail() function.
Problem is I am getting the correct emails return but
it redirect me to another page and show me the value there.
Can anyone please help me?
CODE
function findemail(e)
{
document.getElementById('man-email-add').innerHTML=document.write(e.value);
}
HTML (I am using PHP to get all the values)
<select id="manager_detail" onchange="findemail(this.options[this.selectedIndex]);">
<?php
foreach ($data['display']['userMangers'] as $manager){
echo $manEmail = $manager['Email'];
echo "<option value='$manEmail'>".$manager['First_Name'].' '.$manager['Last_Name'].' ('.$manager['Position'].')'.'</option>';
}
?>
</select>
Redirect to new page to show the value:
It's because you're using document.write() after the page has loaded, which doesn't look necessary here anyway:
document.getElementById('man-email-add').innerHTML= e.value;
Does it redirect to new page or reloads the same page showing the email? I believe it's doing the later as document.write(e.value); writes that value to the page. So replace document.write(e.value); with e.value;
If man-email-add is an input field, use document.getElementById('man-email-add').value=e.value;