JQuery loading issue on submission - javascript

On my website. Im having trouble with JQuery. Im not an expert here so please understand.
Here it is the script that I'm using its working actually but, once you click the submit btn..even you have an incomplete info in the form the loader still show processing. Even the my board says: please complete your..., still the loading gif is running.
The Script:
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).on( "click", ".show-page-loading-msg", function() {
var $this = $( this ),
theme = $this.jqmData( "theme" ) || $.mobile.loader.prototype.options.theme,
msgText = $this.jqmData( "msgtext" ) || $.mobile.loader.prototype.options.text,
textVisible = $this.jqmData( "textvisible" ) || $.mobile.loader.prototype.options.textVisible,
textonly = !!$this.jqmData( "textonly" );
html = $this.jqmData( "html" ) || "";
$.mobile.loading( 'show', {
text: msgText,
textVisible: textVisible,
theme: theme,
textonly: textonly,
html: html
});
})
.on( "click", ".hide-page-loading-msg", function() {
$.mobile.loading( "hide" );
});
</script>
My php code: (This is not complete i just want to share the end part)
<div class="form-group">
<div class="col-md-5 col-sm-8 col-xs-8">
<?if (Core::config('general.recaptcha_active')):?>
<?=Captcha::recaptcha_display()?>
<div id="recaptcha3"></div>
<?else:?>
<?= FORM::label('captcha', _e('Captcha'), array('for'=>'captcha'))?>
<span id="helpBlock" class="help-block"><?=captcha::image_tag('publish_new')?></span>
<?= FORM::input('captcha', "", array('class' => 'form-control', 'id' => 'captcha', 'required', 'data-error' => __('Captcha is not correct')))?>
<?endif?>
</div>
</div>
<?endif?>
<div class="control-group">
<div class="controls">
<?= FORM::button('submit', __('<i class="glyphicon glyphicon-send"></i> Publish New Ad'), array('type'=>'submit', 'data-corners'=>'false', 'class'=>'pub-new show-page-loading-msg', 'data-theme'=>'b', 'data-textonly'=>'false', 'data-msgtext'=>'Processing....', 'data-textvisible'=>'true', 'action'=>Route::url('post_new',array('controller'=>'new','action'=>'index'))))>
</div>
</div>
</fieldset>
<?= FORM::close()?>
To know more Please you can go here, but you need to use mobile to see : https://linkinads.com/publish-new.html or here in youtube for video : https://www.youtube.com/watch?v=dKzabE2eJN0

though I dont know the real issued here but after i move this, things are fixed
'data-ajax'=>'false'
solve my issue.

Your button is a submit button. These button fire an event to process the form natively in HTML.
In your Javascript, instead of binding your code to the click event for the class of the button, you should instead bind it to the submit event of the form (which is tied to the button and the form as a whole) and then block the default submit action. Something like the below.
$('#publish-new').submit(function(event) {
event.preventDefault(); //Prevents the default form event from firing
//Rest of your code can go here
});

Related

rateYo jquery plugin function star rating codeigniter/php

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.

JQuery Guillotine: Multiple Change Events Firing

Can somebody please give me some guidance with a problem I am having with the JQuery Guillotine? I have spent hours working on this and cannot identify the correct solution. The issue I am having is eventOnChange fires multiple times after I have changed the image. Each event is fired +1 for each successive image swap.
I have studied this link and am still unable to find a working solution: jQuery Guillotine - Swap Image
I've worked around this by killing the event and just capturing the relevant information I need when the form is posted, but it's really bothering me that I cannot find a solution that will allow me to take advantage of the event.
Here is a brief summary of what is going on:
page loads with default user avatar
user is able to manipulate avatar inside guillotine and one onchange event fires per manipulation (zoom in, zoom out, rotate, fit, etc.)
user opens file reader to select new avatar
new avatar is successfully loaded (correct scaling and dimensions)
user manipulates image but each manipulation event fires multiple times. For example, rotate right will rotate the image twice (180 degrees) after the user has selected a new avatar.
If the user opens the file reader again, the image will fire three times. And so one. 1 + x times the user selects a new avatar...
I have tried unbinding the event before reloading the image and initialing the plugin, but it has not solved the problem. Any help is greatly appreciated!
Relevant code is below.
JavaScript:
<script type="text/javascript" charset="UTF-8">
function showData (data) {
data.scale = parseFloat(data.scale.toFixed(4))
for(var k in data) { $('#'+k).html(data[k]) }
}
function loadInterface(picture) {
showData(picture.guillotine('getData'))
// Bind button actions
if(!picture.data('isBound')){
picture.data('isBound', true)
$('#rotate_left').click(function(){ picture.guillotine('rotateLeft') })
$('#rotate_right').click(function(){ picture.guillotine('rotateRight') })
$('#fit').click(function(){ picture.guillotine('fit') })
$('#zoom_in').click(function(){ picture.guillotine('zoomIn') });
$('#zoom_out').click(function(){ picture.guillotine('zoomOut') })
}
// Update data on change
picture.on('guillotinechange', function(e, data, action) {
console.log('guillotine onchange event called!')
showData(data);
console.log(action);
})
}
function loadGuillotine (picture, data) {
if(picture.guillotine('instance')){ picture.guillotine('remove') }
// Load plugin
picture.guillotine({
width: data['w'],
height: data['h'],
init: data,
eventOnChange: 'guillotinechange'
})
}
$(document).ready(function() {
var picture = $('#useravatar')
var data = { w: 250, h: 250, angle: 0, scale: 1 }
picture.on('load', function() {
// Load guillotine and controls
picture.guillotine('remove')
loadGuillotine(picture, data)
loadInterface(picture)
// Transform picture to fit, center
picture.guillotine('fit').guillotine('center')
})
})
function ReloadImage(){
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("avatar_input").files[0]);
reader.onload = function (oFREvent){
document.getElementById("useravatar").src = oFREvent.target.result;
}
}
</script>
And inside Ruby Page:
<div id='content'>
<h1>Select Avatar</h1>
<%= form_for(#avatar, url: save_avatar_path, method: :patch) do |f| %>
<%= render 'shared/errors', object: #avatar %>
<div class='frame'>
<%= image_tag 'default-user-avatar.jpg', :id => :useravatar %>
</div>
<div id='controls'>
<button id='rotate_left' type='button' title='Rotate left'> < </button>
<button id='zoom_out' type='button' title='Zoom out'> - </button>
<button id='fit' type='button' title='Fit image'> [ ] </button>
<button id='zoom_in' type='button' title='Zoom in'> + </button>
<button id='rotate_right' type='button' title='Rotate right'> > </button>
</div>
<div id='controls'>
<%= f.hidden_field :image, value: #avatar.cached_image_data %>
<%= f.file_field :image, :class => :form_field, :id => :avatar_input, :onChange => "ReloadImage()" %>
</div>
<ul id='data'>
<div class='column'>
<li>x: <span id='x'></span></li>
<li>y: <span id='y'></span></li>
</div>
<div class='column'>
<li>width: <span id='w'></span></li>
<li>height: <span id='h'></span></li>
</div>
<div class='column'>
<li>scale: <span id='scale'></span></li>
<li>angle: <span id='angle'></span></li>
</div>
</ul>
<% end %>
</div>
I have not tested your code but believe/guess you have fallen into a trap that I once found myself in.
.click() applies your function event with every iteration of the loop hence why you get multiple change events fireing (thus if the loop calls three times then the event is added sequentially three times).
Try using .one() instead of .click()
Another potential solution is to use .off().click() but it creates overhead.

jQuery popover buttons (php)

I have a a button to generate presentations. I generate 8 presentation with one click, and then I can edit each one by clicking on its name. There I have another, smaller form. I want to have also some button there, that will let me choose which fields I want to edit. This applies to "place" part - you can specify the place, if you want to. I have a button to show/hide fields connected to place edition.
<div>
<?=
Html::button(Yii::t('app', 'Add new place'), [
'id' => "add-different-place-btn",
'class' => 'btn btn-success',
])
?>
<?=
Html::button(Yii::t('app', 'Delete new place'), [
'id' => "delete-different-place-btn",
'class' => 'btn btn-success',
])
?>
</div>
<br />
<div id="place-hidden-different">
<div id="place-name-hidden">
<?= $form->field($place, "[{$index}]name")->textInput()->label(Yii::t('app', 'New place')) ?>
</div>
<div id="place-city-hidden">
<?= $form->field($place, "[{$index}]city")->textInput() ?>
</div>
<div id="place-street-hidden">
<?= $form->field($place, "[{$index}]street")->textInput() ?>
</div>
<div id="place-postcode-hidden">
<?= $form->field($place, "[{$index}]post_code")->textInput() ?>
</div>
</div>
Then, in my jQuery part I figured out something like this. Notice that I'm really new to jQuery, so it can be something really obvious :)
$('.btn-popover-link').on('click', function () {
$(document).ready(function () {
$('#place-hidden-different').hide();
$('#delete-different-place-btn').hide();
$('#add-different-place-btn').on('click', function () {
$('#place-hidden-different').show();
$('#add-different-place-btn').hide();
$('#delete-different-place-btn').show();
});
$('#delete-different-place-btn').on('click', function () {
$('#place-hidden-different').hide();
$('#add-different-place-btn').show();
$('#delete-different-place-btn').hide();
});
});
});
But, instead of getting what I want to, I get things like that:
It looks ok. But it doesn't work. Nothing happens on clicking "Dodaj nowe miejsce" (Add new place). Morover, in other presentation I get full variety of that form - example below. None of the buttons is working at all, in some popovers there are no buttons at all, in some just not working.
What can cause this situation?
If I get it well, you are using the same ID #add-different-place-btn for each of the 8 presentations button.
If this is right, the code is working as expected: IDs must be unique !
You should move to a class selector like you did with .btn-popover-link.
Also you should move $('.btn-popover-link').on('click', function () {}); inside the $(document).on("ready", function() { ... here ... });.
Even better with $(window).on("load", function() {}); but it depends on the kind of code you are running.

How can I make dynamic Ajax requests with Laravel

I'm creating a social network site using Laravel. I have a page that load all the posts created by users the currentUser follows. I have a comment section on each post. I want a user to be able to comment on any post without the page reloading so the user doesn't have to re-scroll through the page.
I have everything working fine without ajax (minus the reloading page). I'm able to post comments, the page reloads and the new comment is displayed. However, when I try to use Ajax I've been running into problems.
Here is my code.
Here is the view of the comment-box. It contains a section where I loop through each comment and display them. At the end is the type field so a user can post a new comment:
<div class="comment-box-container ajax-refresh">
<div class="comment-box">
#if ($type->comments)
#foreach ($type->comments as $comment)
<div class="user-comment-box">
<div class="user-comment">
<p class="comment">
<!-- starts off with users name in blue followed by their comment-->
<span class="tag-user">{{ $comment->owner->first_name }} {{ $comment->owner->last_name }} </span>{{ $comment->body }}
</p>
<!-- Show when the user posted comments-->
<div class="com-details">
<div class="com-time-container">
{{ $comment->created_at->diffForHumans() }} ·
</div>
</div>
</div><!--user-comment end-->
</div><!--user-comment-box end-->
#endforeach
#endif
<!--type box-->
<div class="type-comment">
<div class="type-box">
{{ Form::open(['data-remote', 'route' => ['commentPost', $id], 'class' => 'comments_create-form']) }}
{{ Form::hidden('user_id', $currentUser->id) }}
{{ Form::hidden($idType, $id) }}
{{--{{ Form::hidden('user_id', $currentUser->id) }}--}}
{{ Form::textarea('body', null, ['class' =>'type-box d-light-solid-bg', 'placeholder' => 'Write a comment...', 'rows' => '1']) }}
{{ Form::close() }}
</div><!--type-box end-->
</div><!--type-comment-->
</div><!--comment-box end-->
The user submit the form for the comment type box by pressing the "enter/return" key. Here is the JS for that
<script>
$('.comments_create-form').on('keydown', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
$(this).submit();
}
});
</script>
Here is my Ajax
(function(){
$('form[data-remote]').on('submit', function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
success: function(data) {
var tmp = $('<div>');
tmp.html(data);
$('.ajax-refresh').html(tmp.find('.ajax-refresh').html());
$('.type-box').html(tmp.find('.type-box').html());
tmp.destroy();
}
});
e.preventDefault();
});
})();
I'm running into a few problems with this code. The comment gets displayed on ever single post until I manually refresh the page then it only shows on the correct post. I feel like every post's comment-box will need it's own unique ID to solve this, but I do not know how to do this with Laravel and make the JavaScript work.
also,
After I submit one comment I can no longer submit a second one because my "submit on enter/return key" functionally is no longer working. My cursor just moves to a new line, and I'm not able to post another comment.
Does anyone know a way to fix these problems?
EDIT
Here is my ajax so far
(function(){
$(document).on('submit', 'form[data-remote]', function(e){
e.preventDefault();
var form = $(this)
var target = form.closest('div.ajax-refresh');
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
success: function(data) {
var tmp = $('<div>');
tmp.html(data);
target.html( tmp.find('.ajax-refresh').html() );
target.find('.type-box').html( tmp.find('.type-box').html() );
tmp.destroy();
}
});
});
})();
Please use the following to fix the issue:
$(document).on('submit', 'form[data-remote]', function(e){
e.preventDefault();
var form = $(this),
var target = form.closest('div.ajax-refresh');
var method = form.find('in......
......
.....
tmp.html(data);
target.html( tmp.find('.ajax-refresh').html() );
target.find('.type-box').html( tmp.find('.type-box').html() );
tmp.destroy();
}
});
});
The variable target will help you target just the right div to add the ajax response to.
Further, you would have to just reset the relevant form rather than replace the form markup. Otherwise each form will work only once.
UPDATE
The above code has been updated to use a delegated submit event -- $(document).on('submit', '.selector', ...) instead of $('.selector').on('submit', .....) since the form content is being replaced after each comment.
UPDATE 2
The following delegated keydown event should enable you to submit by pressing the enter key:
$(document).on('keydown', '.comments_create-form', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
$(this).submit();
}
});

Twitter Bootstrap alert message closes without pressing close button

I have a problem with alert messages. I want to use the alert message as a warning to the user after a particular action has been performed. The issue I am facing is that the message shows and then closes on its own without user closing the message.
<div class="row-fluid">
<div class="alert span10 offset1" style="display: none" id="changeStatusMsg">
<a class="close" onclick="$('.alert').hide()" href="#">×</a>
<strong>Status has been changed.</strong>
</div>
I am using jquery to show the message -- $('#changeStatusMsg').show();
I used the solution mentioned here
But it does not help in my case.
function changeStatus(status, widgetExternalId){
$.ajax({
url : 'Controller',
data : { 'widget' : widgetExternalId,
'method' : (status == 'I' ? "activate" : "inactivate")
},
success : function(data) {
window.location = "myaccount.jsp";
$('#changeStatusMsg').show();
}
}
});
}
It is probably do to the fact you are not calling the action that is opening it. So the page is refreshing.
If you are doing it inline:
onclick="$('#changeStatusMsg').show();return false;"
If with a click event
$(".foobar").on("click",function (event) {
event.preventDefault();
$("#changeStatusMsg').show();
});

Categories