How to add javascript img? - javascript

I know this may be ridiculously easy for a javascript programmer, but I want to change "incorrect answer" and "correct answer" for an image located in my folder assets/img/avatar/incorrect.png any idea how i may do this? I've tried to google, but every option i've tried doesn't seem to work?
<script type="text/javascript">
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
if(!$("#myForm").validationEngine('validate'))
{
return false;
}
var id = $('input[type=radio][name=is_correct]:checked').attr('id');
var formData = $("#myForm").serializeArray();
$.ajax
({
type: "POST",
url: "<?php echo base_url()?>user/checkanswer/<?php echo $questionrecord[0]['id']?>/"+id,
cache: false,
data : formData,
async: false,
success: function(data)
{
if( data == '0' ){
$("#msgbox_answer").fadeTo(200,0.1,function() { //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('Incorrect Answer').addClass('messageboxerror').fadeTo(900,1);
document["pic1"].src = "assets/img/avatars/incorrect.png";
});
}else if( data == '1' ){
$("#msgbox_answer").fadeTo(200,0.1,function() { //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html(' Correct Answer').addClass('messageboxok').fadeTo(900,1);
});
}
$( "#remove_submit" ).remove();
$("#view_correct_answer").html('<span class="whitetext">View correct answer</span>');
}
});
});
$(".hidetext").click(function () {
$(".text_class").toggle("slow")
});
$('.carousel').carousel({
interval: 4000 //changes the speed
})
</script>

Related

page redirect is not working in jquery

<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.

ajax hide load more button on no more data

I have implemented the load more functionality using ajax in yii. This is what I am doing in my script:
$(document).ready(function() {
$(document).on('click', '.discover-more', function() {
$('.discover-more').hide();
$('.loading').show();
var lastId = $('ul#ulscroller li:last').attr('id');
$.ajax({
cache: false,
type: 'POST',
url: '<?php echo $host . $url . '/index.php?r=site/LoadMore&lastid=' ?>' + lastId,
success: function(data) {
$('#ulscroller').append(data);
$('.discover-more').show();
$('.loading').hide();
if (data.length() == 0) {
$('.discover-more').hide();
$('.nomore').show();
}
}
});
});
});
Now, what i have to do is to hide discover more button when there are no more images to show. I have tried a couple of methods in the success call back, like if(data.length() == 0) and if(data.size() < 1) but both do not seem to work? any ideas?
Try this,
if($.trim(data).length == 0)
hope this will work !
.length without (), it is a property and not a method.
if (data == "") {
$('.discover-more').hide();
$('.nomore').show();
}

How do I clear data shown on mouseenter with onmouseout

When the user hovers over an image an information box comes up about that image, the information them changes inside the box as I move over another image but when I am over no images the information box stays. I can't close the information box (i.e. tooltips).
JS :
var id;
$(document).ready(function () {
$('a').mouseenter(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
});
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
});
How can I get the information box to disappear on mouse out?
I have tried multiple tests but the box doesn't even appear with them, the last one I tried is in the code above.
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
I am only starting out with javascript, jquery etc. in the last year.
Thank you in advance!!
Here is the php.
<div class="thumbnails">
<?php
$query = mysqli_query($connection, "select * from portfolio");
print "<ul>";
while ($row = mysqli_fetch_assoc($query)) {print "<li><img onClick=preview.src=" . $row['image'] . "name=" . $row['folio_id'] . "src={$row['image']}></td></li>";
}
print "</ul>";
?>
</div>
<!--Folio Information-->
<div id="fillFolio">Project Information</div>
I'm not sure, but try to use :
$('a').onmouseleave(function () {
$("#fillFolio").empty();
}
Hope this helps.
$("a").hover(function(){
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
}, function(){
//im not sure u want to hide or want to just clear your question not clear
$("#fillFolio").empty();
$("#fillFolio").hide();
});
Why not use jQuery hover = (mouseenter + mouseleave)
<script type="text/javascript">
var id;
$(document).ready(function () {
$('a').hover(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
,function () {
id = $(this).empty();
});
</script>

Speed Up Jquery heartbeats

I'm a pretty new programmer who made an application that sends out a heartbeat every 3 seconds to a php page and returns a value, the value of which decides which form elements to display. I've been fairly pleased with the results, but I'd like to have my jquery as fast and efficient as possible (its a little slow at the moment). I was pretty sure SO would already have some helpful answers on speeding up heartbeats, but I searched and couldn't find any.
So here's my code (just the jquery, but I can post the php and html if needed, as well as anything anyone needs to help):
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'POST',
contentType: "application/json",
cache: true,
data: { "dataid": dataid },
success: function(data){
var msg = $.parseJSON(data);
if (msg == ""){ //after reset or after new patient that is untouched is added, show checkin
$e.find('.checkIn').show();
$e.find('.locationSelect').hide();
$e.find('.finished').hide();
$e.find('.reset').hide();
}
if ((msg < 999) && (msg > 0)){ // after hitting "Check In", Checkin button is hidden, and locationSelect is shown
$e.find('.checkIn').hide();
$e.find('.locationSelect').show();
$e.find('.finished').hide();
$e.find('.reset').hide();
$e.find('.locationSelect').val(msg);
}
if (msg == 1000){ //after hitting "Checkout", Option to reset is shown and "Finished!"
$e.find('.checkIn').hide();
$e.find('.locationSelect').hide();
$e.find('.finished').show();
$e.find('.reset').show();
}
}
});
});
},3000);
$('.checkIn').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "checkin.php",
// Data used to set the values in Database
data: { "checkIn" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.locationSelect').show();
$container.find('.locationSelect').val(1);
}
});
});
$('.reset').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "reset.php",
// Data used to set the values in Database
data: { "reset" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.checkIn').show();
}
});
});
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
$e = $(this);
var data = $e.data("param").split('_')[1] ;
$.ajax({
type: "POST",
url: "checkout.php",
// Data used to set the values in Database
data: { "checkOut" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.finished').show();
$container.find('reset').show();
}
});
}
else{
$e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of select (1 for the first select)
// You can map this to the corresponding select in database...
$.ajax({
type: "POST",
url: "changeloc.php",
data: { "locationSelect" : $(this).val(), "selectid" : data},
success: function() {
// Do something here
}
});
}
});
});
</script>
Thanks for all and any help! Please just ask if you need any more details! Thanks!
Alot of factors could be causing slowness. Some things to consider:
The speed of the heartbeat is not dependent on your client-side javascript code alone. There may be issues with your server-side php code.
Also, a heartbeat every three seconds is very frequent, perhaps too frequent. Check in your browser's developer debug tools that each of the requests is in fact returning a response before the next 3 second interval. It could be that your server is slow to respond and your requests are "banking up".
You could speed your your jQuery a fraction by streamlining your DOM manipulation, eg:
if (msg == "")
{
$e.find('.checkIn').show();
$e.find('.locationSelect, .finished, .reset').hide();
}

How to keep track of actions called by a jQuery dialog box?

I have a bit of a dillema :)
I have a link for users to vote on an item. A click on a link generated a jQuery AJAX call checking if the person is logged in. If not, the dialog box displays a form to login.
But the problem is that the jQuery call to log in and the whole bit with the popup box is in a different place.
What I need to do is check if user got logged in successfully, and update the vote count.
I am doing it on this site: http://www.problemio.com
Here is my jQuery code so far:
<script type="text/javascript">
$(document).ready(function()
{
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
$("#newprofile").click(function () {
$("#login_div").hide();
$("#newprofileform").show();
});
$('.vote_up').click(function()
{
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (data);
},
error : function(data)
{
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
//alert(JSON.stringify(data));
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
});
</script>
It all works except right after the line $dialog.dialog('open'); - I don't know how to
Get a signal back for success of fail, and don't know exactly how to
Update the very item that was voted on since it is just one of many items that can be voted on in the page.
How can I do these two things?
Try this approach:
Have a hidden input within the div that is your login dialog.
Set that with the problem_id before you do the .dialog('open')
On the success callback of the Login button click, retrieve problem_id from the hidden input and perform vote-up or vote-down.
Hope that helps
EDIT: (Trying to code a workable example after OP's second comment)
<script type="text/javascript">
$(document).ready(function() {
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function () {
$("#login_div").hide();
$("#newprofileform").show();
});
$('.vote_up').click(function() {
var problem_id = $(this).attr("data-problem_id");
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id) {
var dataString = 'problem_id=' + problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data) {
// ? :)
alert(data);
},
error : function(data) {
errorMessage = data.responseText;
if (errorMessage == "not_logged_in") {
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
}
else {
alert("not");
}
//alert(JSON.stringify(data));
}
});
};
$('.vote_down').click(function() {
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id=' + problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function() {
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>

Categories

Resources