rateYo jquery plugin function star rating codeigniter/php - javascript

HTML:
<div id="submit-review">
<form action="<?=base_url()?>story/submit_review/<?=$story['story_id']?>" method="post">
<div class="form-group">
<label for="review-rating">Rate the story</label>
<div id="review-rating"></div>
</div>
<div class="form-group">
<label for="review-content">Write your review</label>
<textarea class="form-control" name="review-content"></textarea>
</div>
<button class="btn btn-default">Post Review</button>
</form>
</div>
<script>
$(function () {
tinymce.init({
selector:'textarea'
});
$("#review-rating").rateYo({
starWidth:"25px"
});
});
</script>
Controller:
public function submit_review(){
$story_id = $this->uri->segment(3);
$review_content = $this->input->post('review-content');
}
I tried experimenting with the jquery script provided by the website:
$(function () {
var $rateYo = $("#rateYo").rateYo();
$("#getRating").click(function () {
/* get rating */
var rating = $rateYo.rateYo("rating");
window.alert("Its " + rating + " Yo!");
});
$("#setRating").click(function () {
/* set rating */
var rating = getRandomRating();
$rateYo.rateYo("rating", rating);
});
});
But i keep having problems, I don't have any background in jquery. I've done javascript validation but that was years ago. I could relearn but then i'd have to start with javascript first.
My idea is to somehow set a value to a hidden input type inside my <form> then just get it from there via post in CI.
<input id='review-rating' type="hidden" value=""></input>
var $rateYo = $("#review-rating").rateYo();
$("#submit-review").click(function () {
var rating = $rateYo.rateYo("review-rating");
$("#hidden-rating").val(rating);
window.alert("Its " + rating + " Yo!");
});
But i could not test the above code if it works or not because whenever i try to add it, my other jquery functions won't work. I'm using rateYo plugin and tinymce.
This is my current scripts:
$(function () {
tinymce.init({
selector:'textarea'
});
$("#story-rating").rateYo({
rating: <?=$story['rating']?>,
readOnly: true
});
<?php if(isset($reviews['your_review']) AND $reviews['your_review'] != NULL){ ?>
$("#my-rating").rateYo({
rating: <?=$your_review_rating?>,
readOnly: true,
starWidth: "25px"
});
<?php } ?>
$("#review-rating").rateYo({
starWidth:"25px"
});
<?php foreach($reviews['other_reviews'] as $id=>$row){ ?>
$("#rating-<?=$id?>").rateYo({
rating: <?=$row['rating']?>,
readOnly: true,
starWidth: "25px"
});
<?php } ?>
});
I barely got the above to work.
Anyway, my question is, how do i pass the rateYo value to my CI controller? if my above idea is of sound logic, then can you write how the syntax should look like here?
I guess i'm learning jquery as i need them, albeit messy.(i can't concentrate reading wall of texts/codes, i learn better by trying them)

Okay so while i was waiting for any answer. I read a quick tutorial on W3school.(i find w3school a reliable source for tutorials on anything, any other tutorials are either too complex or assumes the reader knows everything there is to know that leaves them confused)
So i changed the code abit:
var rating = $("#review-rating").rateYo("rating");
$("#hidden-rating").val(rating);
I've attached the above code to a button click event.
Now i can finally get the value from the controller:
$this->input->post('hidden-rating');
Still i'll wait for even better answers.

Related

copying Javascript working on a laravel view to another site not working

So on similar sites with different themes, same core functions for laravel there is a view that has
<div class="footer__item footer__item--right"> <div class="footer__item-search"> <span class="search-wrap"><input type="text" placeholder="Search" class="search"></span> </div>
in scripts the only relative javascript code which is also already on the other site
$(document).on('keyup', '.search', function() {
var query = $(this).val().toLowerCase();
doSearch(query);
});
function OnSearch(input) {
var query = input.value.toLowerCase();
doSearch(query);
}
function doSearch(query){
$.getJSON('{{ route('frontend.game.search') }}?category1={{ $category1 }}&q=' + query, function(data) {
$('#games').html(data.data);
});
}```
so copying those makes a box appear but searches nothing
What possibly the javascript is missing to actually be called and call the laravel template view mentioned ?

JavaScript function call on JQuery .load() doesn't behave like expected

I am working on a website for school, and am currently implement some sort of admin dashboard. For that, I decided to dynamically load 'modules' (actually simply .php files) into a div designed to hold them.
This works fine for modules that don't depend on specific js files, but there's one that needs the 'participation.js' file.
I had tested the module in a whole window where there was an 'onload="initSelectable()"' on the body directive, but calling this function when the module is loaded in the admin dashboard doesn't do anything.
Here is the content of participation.js (it is simply copy/pasted from the JQuery selectable, and I slightly modified the behaviour):
var selectedPlayerIDs = [];
function initSelectable(){
$('#selectable').selectable();
$('#submitParticipationBtn').hide();
console.log("initSelectable");
$("#selectable").selectable({
stop: function() {
var count = 8;
var result = $("#selectedPlayersCount").empty();
$(".ui-selected", this).each(function() {
count--;
selectedPlayerIDs.push($(this).attr("data-playerid"));
});
if(count > 1)
$('#selectedPlayersCount').html(count + " more players");
else if(count === 1)
$('#selectedPlayersCount').html(count + " more player");
else if(count === 0)
$('#selectedPlayersCount').html("no more player. You're good to go !");
else if(count === -1)
$('#selectedPlayersCount').html(-count + " player less");
else
$('#selectedPlayersCount').html(-count + " players less");
if(count === 0)
$('#submitParticipationBtn').show();
else
$('#submitParticipationBtn').hide();
}
});
}
function submitParticipation(){
alert( "JS loaded" );
$.post("participation.php", {selectedIDs : JSON.stringify(selectedPlayerIDs)}, function() {
})
.onSuccess(function() {
alert( "onSuccess" );
})
.fail(function() {
alert( "error" );
});
}
So basically this code initializes the JQuery Selectable environment. When loading the module in the div, I use $('#dynamicPage').hide().load("module1.php").fadeIn('500'); directly followed by $.getScript("participation.js");
The thing is, the module correctly loads (at least the HTML part), and I can see in the console log ("initSelectable"). But I need to manually re-execute initSelectable() from the command for it to be effective. And when I do that, I see there's an undefined getting logged in the console, before the second ("initSelectable") log (this might be due to the fact that I'm trying to call $('#selectable').selectable(); a second time).
For example, here is the participation module .php file:
<div class="well">
<h3>Create a participation</h3>
<h4>Please select <span id="selectedPlayersCount">8 players</span></h4>
<div class="row">
<div class="col-sm-4">
<ol id="selectable">
<?php include_once "../Ctrl/rankingList.php" ?>
</ol>
<button class="btn btn-success" id="submitParticipationBtn" onclick="submitParticipation()">Submit</button>
</div>
</div>
</div>
I've tried countless different way to call the initSelectable function (callbacks, events, timeOuts, etc...) and no matter what, even if it gets executed by the browser, I still need to manually re-execute it for it to be working...
So basically, my question is:
What is the correct way to load HTML and dependant JS files into a div ?
What is the correct way to load HTML and dependant JS files into a div ?
So, this would be a good start and you can take it from here.
$(function() {
$("#myDiv").load("myfile.php", function() {
console.log("HTML has been injected!");
//Get dependencies
$.getScript( "myscript.js" )
.done(function( script, textStatus ) {
//Call methods from within myscript.js
initSelectable();
})
.fail(function( jqxhr, settings, exception ) {
console.log("There was an error!");
});
});
// Remove inline event handler and bind it like below.
$("#myDiv").on("click", "#submitParticipationBtn", submitParticipation);
function submitParticipation() {
//...
//...
}
});
I am not sure why $('#selectable').selectable() is being duplicated. But, it's left you to fix :)
Okay so I was doing it wrong. I thought that putting the <script src "path/to/script.js"></script> in the module file didn't work. But actually, it does, and I simply needed to call $(document).ready(initSelectable()) in the JS file to be sure the initSelectable was executed at the right time.
So now my .php file looks like this:
<div class="well">
<h3>Create a participation</h3>
<h4>Please select <span id="selectedPlayersCount">8 players</span></h4>
<div class="row">
<div class="col-sm-4">
<ol id="selectable">
<?php include_once "../Ctrl/rankingList.php" ?>
</ol>
<button class="btn btn-success" id="submitParticipationBtn" onclick="submitParticipation()">Submit</button>
</div>
</div>
<script src="../Ctrl/participation.js"></script>
</div>
Thanks all for your help :P

jquery Return to same screen without refreshing screen

I have an upload view that needs to be used to upload three attachments. Now I used this code for the UI part in the view:
<div id="theDeliveryNoteContent">
<form action='Order/Save' method="post" enctype="multipart/form-data" id="deliveryNoteForm">
<div >
<label style="text-align: left;">Delivery note:</label>
<input type="file" name="DeliveryNoteFile" id="DeliveryNote" style="width: 400px;" />
<div style="margin-top:4px;margin-bottom:4px" >
<input type="submit" value="Upload" id="btnAddAttachment" />
</div>
</div>
</form>
</div>
Now the method that I want to call is situated inside my Orders controller. Here is the method I'm using. The code works fine until the return part.
[HttpPost]
public ActionResult Save(HttpPostedFileBase DeliveryNoteFile)
{
try
{
string customer = GetCustomerLinkedToPortalUser();
var uploadPath = "C:\\Attachments\\" + customer;
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
if (DeliveryNoteFile != null)
{
var fileName = Path.GetFileName(DeliveryNoteFile.FileName);
var physicalPath = Path.Combine(uploadPath, fileName);
DeliveryNoteFile.SaveAs(physicalPath);
}
return RedirectToAction("Index");
}
catch (Exception)
{
throw;
}
}
The problem is that when the method returns to the screen it refreshes the screen and all the entered information is lost. I want to save the file to that directory and come back to the order screen and upload the next file. Now how I'm supposed to do that I'm not sure so that is what I need help with.
A colleague mentioned that I could use jQuery.Form script to do an ajax call so what I did is I added the jquery.form.js script to my project, did the referencing and I also added this to my javascript:
$("#deliveryNoteForm").ajaxForm({
target: "#theDeliveryNoteContent"
});
So now it returns to my screen, but it messes up the layout and refreshes the screen (seems) anyway. Is there any other easy way to return to the previous screen with the method which I used without losing all the entered information?
you need async file upload. Use this. Read some docs it is all simple.
Example:
Javascript initialize:
$(function () {
$('#DeliveryNote').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
Html:
<input id="DeliveryNoteFile" type="file" name="files[]" data-url="yourUploadController/Save/" style="width: 400px;" />
and remove submit button.

Html.TextBoxFor not rendering when added by a library

I'm currently working on a website at work. Everything's been working so far, except when I've moved a function to a library so it can be reusable.
The function is a click event for a set of two radio buttons. When the "Yes" button is clicked, a textbox and it's label need to appear. When the "No" button is clicked, they need to disappear.
The label is appearing just fine on the "Yes" click. And the function as a whole worked perfectly on the page itself. However, when I moved the script to a library for reusability within the project, the textbox no longer appears. I have tried swapping out for an input tag, with similar results.
The relevant html:
#ModelType PROJECT.Form
#Code
ViewData("Title") = "PageTitle"
Layout = "~/Views/Shared/_LayoutPage.Desktop.vbhtml"
End Code
<script>
$(function () { initFunction() })
</script>
#Using Html.BeginForm("Process", "Home")
#Html.AntiForgeryToken()
#Html.Hidden("page", 4)
#<div id="formColumn" class="grid_19 alpha">
<h3>Process Title</h3>
<fieldset>
<legend>Page Title</legend>
<ol class="grid_18 push_1">
//a couple yes/no questions here, works fine
<li><label>Question 3</label></li>
<li>
<ol id="appendHere"class="horizontalList clearfix">
<li><label>Yes</label></li>
<li>#Html.RadioButtonFor(Function(a) a.Q3Radio, True)</li>
<li><label>No</label></li>
<li>#Html.RadioButtonFor(Function(a) a.Q3Radio, False)</li>
</ol>
</li>
//more working stuff
</ol>
<div class="clear"></div>
<button name="submit" id="submit" value="submit" class="push_1">Submit</button>
<button name="cancel" id="cancel" value="cancel" class="push_1">Cancel</button>
<button name="back" id="back" value="back" class="push_1">Back</button>
</fieldset>
</div>
End Using
The javascript:
function initFunction() {
$(function () { $("input[name=Q3Radio]").click(function () { handleQ3Check(this) }) })
var check = true
function handleQ3Check(elem) {
if (elem.value == "True") {
if (check) {
$('#appendHere').append('<li class="appended"><label>Amount: $</label></li><li class="appended">#Html.TextBoxFor(Function(a) a.appendAmount)</li>')
$(function () { $("input[name=appendAmount]").blur(function () { handleFees(this, 'stuff') }) })
check = false
}
} else {
var appendedInput = $('.appended')
if (appendedInput != null) {
handleFees(appendedInput, 'stuff')
$(appendedInput).remove()
check = true
}
}
}
}
As stated above, I have tried making the textbox out of an input tag, but that does not appear. What appears with this case is Amount: $ #Html.TextboxFor(Function(a) a.appendAmount) exactly like that.
Any help or nudges in the right direction while I further attempt to debug the issue would be greatly appreciated.
When you include the Javascript in the same vbhtml file the reason why it works is that the vbhtml file gets compiled before it is then sent out to the client's browser. Have a look at the javascript that is getting rendered either by viewing the source or using developer tools/or similar in your favourite browser.
When you ask javascript to write out
$('#appendHere').append('<li class="appended"><label>Amount: $</label></li>
<li class="appended">#Html.TextBoxFor(Function(a) a.appendAmount)</li>')
It will do just that.
Judging by your comments it seems as though you're already aware of this though :-) and that you're making progress.

How do I submit HTML hidden form fields to iPad iOS Safari and/or Chrome?

I have a simple form-app that works great with full operating systems/browsers, but when I submit the form data using an iPad, none of the <input type='hidden'> fields data show up on the results page. All the other data loads correctly. I am using Template Toolkit to populate the results page with the form parameters.
HTML snippet:
<input id='patientCity' name='patientCity' type='hidden'>
<input id='patientState' name='patientState' type='hidden'>
<label for='zip'>Zip Code</label>
<input name='patientZip' id='patientZip' placeholder='Zip Code' type='text' class='mediumInput' required>
Javascript snippet ($zip is passed in as 'patient'):
function loadCityStates($zip) {
var $actualZip = ($zip + "Zip");
var $city = ($zip + "City");
var $state = ($zip + "State");
document.getElementById($actualZip).onchange = function() {
populateCityState(document.getElementById($actualZip).value);
document.getElementById($city).value = $cityState[0];
document.getElementById($state).value = $cityState[1];
}
}
TT HTML snippet:
<span class="item">Address: </span><span class="info"> [% params.patientStreet %]; [% params.patientCity %], [% params.patientState %] [% params.patientZip %] </span>
Thanks!
I think your first mistake is your not using a JS framework, so the event attaching is probably not happening like #klugerama stated. I've provided a JSFiddle based on what I think you're trying to do here, http://jsfiddle.net/nickyt/wKPdv/
Here's the JS from that fiddle:
// using jQuery as you really should be using a JS framework, but if not you could attach events using pure JS, but then you need to manage attaching events for all browsers.
var patientZipContext = $("#patientZip");
var patientCityContext = $("#patientCity");
var patientStateContext = $("#patientState");
var showHiddenContext = $("#showHidden");
console.log(patientZipContext)
console.log(patientCityContext)
console.log(patientStateContext)
function populateCityState(zipCode) {
// Whatever your code does. Returning dummy code for now.
return ["someCity", "someState"];
}
showHiddenContext.on("click", function() {
$("input[type='hidden']").each(function() {
this.setAttribute("type", "text");
})
});
patientZipContext.on("change", function() {
var cityState;
console.log("onchange fired");
cityState = populateCityState(this.value);
// code to handle empty or incomplete array goes here
patientCityContext.val(cityState[0]);
patientStateContext.val(cityState[1]);
});

Categories