I'm working on a Laravel project. In my blade view, I have a Javascript function like this:
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
Then, I call this function in the body tag and pass two php parameters to it:
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
But when I run this, I got a error: "Uncaught ReferenceError: autoFill is not defined".
Here is my full code in blade view if you want:
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
Activiti Form
</div>
#if(isset($formDataResult) && isset($dropdownValue))
<div class="links">
<form action="{{ url('handle-form') }}" method="POST">
<!--Loop form data and call components to render form-->
#foreach($formDataResult as $formDataValue)
<div class="links">
#if($formDataValue['type'] == 'select')
#if(array_key_exists('description',$formDataValue))
<?php
$dropDown = $formDataValue['name']
?>
#component('components/InputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'enumData' => $dropdownValue
])
#endcomponent
#else
<?php
$emptyDropDown = $formDataValue['name'];
?>
#component('components/EmptyInputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name']
])
#endcomponent
#endif
#elseif($formDataValue['type'] == 'text')
#component('components/InputText',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'type'=>$formDataValue['type']
])
#endcomponent
#endif
<br>
</div>
#endforeach
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
<!--Hidden input to store task id-->
#component('components/HiddenInput',[
'id' => $taskId
])
#endcomponent
<div>
<input type="reset" value="Reset Form">
<button type="submit">Complete Task</button>
</div>
</form>
</div>
<!--If don't have form data, show error alert-->
#else
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>Notice!</strong> There are no tasks at this moment!
</div>
#endif
</div>
</div>
</body>
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
How I can fix this?
Thank you very much!
You are trying to call the function before you define it. Put the <script type="text/javascript">...</script> defining the function before your <script> autoFill('$dropDown', '$emptyDropDown'); </script> which tries to call it.
You can read js value to using PHP. But you can print js value to HTML screen.
You have a <span> or <div> tag with class or id attribute then you can place your value inside that.
Here is your js functionality
<script>
// whatever value you need in your js from PHP. you need to below code.
let dropdown = <?php echo $dropDown; ?>
let emptyDropdown = <?php echo $emptyDropDown; ?>
// now pass your js variables here.
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
let $this = $(this);
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
Related
I'm trying to implements a button that can refresh the content of a div. This div contains values taken with ajax from the database.
There is a function that can do it?
This is the main page:
include("top.php");
include("funzioni.php");
is_logged();
?>
<script src="JavaScript/inserisciMateria.js" type="text/javascript"></script>
<body>
<?= include ("navbar.html") ?>
<div class="corpo">
<p class="titolo"> Scegli l'anno di cui ti interessa vedere i corsi disponibili! </p>
<hr>
<div class="anni">
<<button id="ShowPrimoAnno" >Primo Anno</button>
<button id="ShowSecondoAnno" >Secondo Anno</button>
<button id="ShowTerzoAnno" >Terzo Anno</button>
<button id="ShowQuartoAnno" >Quarto Anno</button>
<button id="ShowQuintoAnno" >Quinto Anno</button>
</div>
</div>
<script src="JavaScript/selezionaAnno.js" type="text/javascript"></script>
</body>
</html>
I tried to implement it on the button ShowPrimoAnno, in the file selezionaAnno
$(document).ready(function(){
$("#ShowPrimoAnno").click(function(){
$anno = ($(this).attr('data-value'));
$.getScript("inserisciMateria.js");
});
$("#ShowSecondoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
$("#ShowTerzoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
$("#ShowQuartoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
$("#ShowQuintoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
});
The main page and the function takes the content from a js file called inserisciMateria
var card1 = "<div class=\"container\"><div class=\"img-container\"><img src=\"imgs/";
var card2 = ".jpg\"></div><div class=\"content\"><div class=\"head\">"
var card3 = "</div><div class=\"preferiti\"><img src=\"imgs/wishlist.png\" alt=\"Mia Immagine\"></div><div class=\"inner-data\">";
var card4 = "</div><div class=\"anno\">Anno: ";
var card5 = "</div><div class=\"difficolta\">Difficolta\': ";
var card6 = "</div><div class=\"info\"><a href=\"";
var card7 = "\" target=\"_blank\">Per saperne di più</a><i class=\"far fa-heart\"></i></div></div></div></div>";
$(document).ready(function(){
$.ajax({
url:'action.php',
type: 'GET',
success:function(response) {
var data = JSON.parse(response);
var n = data.length;
var finalCard= "";
for (var i= 0; i < n; i++) {
finalCard+=card1+data[i].Nome+card2+data[i].Nome+card3+data[i].Descrizione+card4+data[i].Anno+card5+data[i].Difficolta+card6+data[i].Link+card7;
}
$(".corpo").append(finalCard);
}
});
});
And it takes the data from the database by this file called action.php
<?php
$conn = new mysqli("localhost","root","","utenti");
$json=array();
$anno=2;
$sql="SELECT * FROM corsi WHERE anno = $anno";
$stmt=$conn->prepare($sql);
$stmt->execute();
$result=$stmt->get_result();
while($row=$result->fetch_assoc()){
array_push($json, $row);
}
echo json_encode($json);
?>
But it doesn't work... what's missing?
you are appending the content in
$(".corpo").append(finalCard);
you are selecting the area for content ".corpo" by class, JS doesn't know which of the different elements with this class to take and this can bring problems, select the area by ID instead.
I have a problem in my script.
I have a loop in php who show this in html, this work good :
<?php foreach ($locations as $key => $value) : ?>
<div class="storelocator-info" data-id="<?= $value['codepostal']; ?>"
style="display: block;">
<p class="title-depot"><?= $value['name']; ?></p>
</div>
<?php endforeach ; ?>
Now i have a searchbar who i enter a zip code like 11 or 11111 send in ajax in my controller, i return the result in json format like this :
try {
jQuery.ajax({
url: url,
dataType: 'json',
type: "POST",
data: form.serialize(),
success: function(data) {
if (data['success'] === false){
var index;
var a = data.zip;
for (index = 0; index < a.length; ++index) {
jQuery('.storelocator-info').hide();
jQuery('.storelocator-info[data-id='+a[index]+']').show();
}
jQuery('.storelocator-error').hide();
} else{
jQuery('.moulinroty-loader').hide();
jQuery('.storelocator-info').hide();
jQuery('.storelocator-error').fadeToggle();
}
}
});
} catch (e) {
console.log('error' + e);
}
data.zip is an array like this ['85000,85001'];
I want to show only "" where data.zip == data-id attribute with javascript or jquery .
the result show only the last result in my array with data-id = 85001,
so i want to show 85000 and 85001
can you explain me where is my mistache or error please?
Thank for help
You are hiding all elements in every iteration of your loop. Hide them before and then show those which need to be shown:
var a = data.zip;
jQuery('.storelocator-info').hide();
for (var index = 0; index < a.length; ++index) {
jQuery('.storelocator-info[data-id=' + a[index] + ']').show();
}
here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});
I have this rating script, when people click on any of the stars It allow people to clic again to update but I want people just to clic one time and load a message to DIV like "thanks for your vote" and clear our the stars.
current función https://co.angelesinfieles.com/profileview/rating/
<script>
// rating script
$(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var therate = $(this).attr('id');
for (var i = therate; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
var dataRate = 'act=rate&post_id=<?php echo $id; ?>&ip=<?php echo $_COOKIE["PHPSESSID"]; ?>&rate='+therate; //
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-active');
};
$.ajax({
type : "POST",
url : "<? echo $domain ?>profileview/rating/ajax.php",
data: dataRate,
success:function(){}
});
});
});
</script>
<div class="rate-ex1-cnt">
<div id="1" class="rate-btn-1 rate-btn"></div>
<div id="2" class="rate-btn-2 rate-btn"></div>
<div id="3" class="rate-btn-3 rate-btn"></div>
<div id="4" class="rate-btn-4 rate-btn"></div>
<div id="5" class="rate-btn-5 rate-btn"></div>
</div>
$.ajax({
type : "POST",
url : "<? echo $domain ?>profileview/rating/ajax.php",
data: dataRate,
success:function(data){
alert (data); // data is your return value
}
});
I posted this code minutes 15 mins ago and I did get help for the preventDefault issue , but now I'm not getting my alerts to work , yet firebug doesn't show any error related to this code .. May i ask where I'm going wrong ,
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.preventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.preventDefault();
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
I suggest changing your design. Using <form> codes and posting isn't always the best way of sending your data to another (or the same) page for PHP processing. Instead, switch over to using AJAX code to submit your form.
For one thing, this will allow you to get away from the e.preventDefault kludges. A number of things will iron themselves out if you use the AJAX approach (instead of submitting a form). I can see that you're already using AJAX in your code, but if you're still uncomfortable with it you can check out these other answers:
Form not posting correctly
Place PHP results inside HTML Page
Update data in a DIV
Change your #edit_fields_submit input field from type="submit" to type="button" and use javascript/AJAX to:
Get all the values you would normally submit as a <form>;
Use AJAX to submit them to a PHP file for processing
In the success: function of the AJAX code block, use javascript to send the user over to whatever page you want them to see next
Example:
$('#edit_fields_submit').click(function(event) {
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
var field_data = //you know how to get these values
var project_id = //etc
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/myprocessor.php",
dataType: "json",
data: string,
success: function(data){
document.location.href='yournewpage.php';
}
});
});