Affichage des articles dont le libellé est Active questions tagged jquery - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged jquery - Stack Overflow. Afficher tous les articles

samedi 25 avril 2015

Find object in array and then edit it


Let's say I have the following array:

var things = [
    {
        id: "12345",
        name: "Bryan"
    },
    {
        id: "55555",
        name: "Justin"
    }
]

I want to search for the object with the id of 55555. But I want to update the name of that particular object to "Mike" from Justin but still keep the entire army intact.

At the moment, I kinda figured out a way to search for the object, but I can't find a solution to actually edit that particular finding.

Could anyone help me out? This is what I have so far:

var thing = things.filter(function (item) {
    return "55555" === item.id;
})[0]


Empty post response ajax


I'm trying to use ajax to geta response from a codeigniter controller method but it doesn't work ,the response it's empty.

    <script type="text/javascript">
            $(document).ready(function(){
                $("#crear").click(function() {
                    //$('#error_msg').html("Error");
                    $.ajax({
                        type:"POST",
                        url:"clase/create",
                        success:function(data){
                            $('#error_msg').html(data);
                        }
                    });
                });
            });
    </script>

and this is the controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Clase extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('clase_model','',TRUE);
   $this->load->helper(array('form'));
 }

 function index()
 {
    if($this->session->userdata('logged_in')){
        $data['title'] = 'Gestión de Clases';
        $data['clases'] = $this->clase_model->getAll();
      $this->load->view('header', $data);
      $this->load->view('clase_view', $data);

     }
     else{

          redirect('login', 'refresh');
     }
 }

 function create(){
    if($this->session->userdata('logged_in')){
      $this->load->library('form_validation');
      $this->form_validation->set_rules('name', 'Nombre', 'trim|min_length[2]|required');
      $this->form_validation->set_rules('info', 'Información', 'trim');

       if($this->form_validation->run() == FALSE){
          $data = array(
            'error_message1' => form_error('name'),
            'error_message2' => form_error('info')
            );
           return $data['error_message1'];
       }
       else{
          if($this->input->post('info')){
             $this->insert2($this->input->post('name'),$this->input->post('info'));
          }
          else{
            $this->insert1($this->input->post('name')); 
          }
       }   
    }
    else{
          redirect('login', 'refresh');
    }
 }

 function insert2($name,$information){
    $dat = array(
      'nombre'=>$name,
      'info'=>$information
    );
    $this-> db ->insert('clase',$dat);

    echo $name;
    redirect('clase', 'refresh');
 }
 function insert1($name){
    $dat = array(
      'nombre'=>$name,
    );

    $this-> db ->insert('clase',$dat);
    redirect('clase', 'refresh');
 }
}
?>

and the response header

Cache-Control   
no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection  
Keep-Alive
Content-Length  
0
Content-Type    
text/html; charset=UTF-8
Date    
Sat, 25 Apr 2015 16:04:47 GMT
Expires 
Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive  
timeout=5, max=100
Pragma  
no-cache
Server  
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3
Set-Cookie  
ci_session=941a601d7eaf9f590d21bd4c0aa8c2ac043faa81; expires=Sat, 25-Apr-2015 18:04:47 GMT; Max-Age=7200
; path=/; httponly
x-powered-by    
PHP/5.6.3

Somebody can tell me what is wrong?it's my first time with ajax


how to add image dinamycly jquery


i used the following code to dynamicly create an img the div is created and works fine so is the input text but the problem is that the img control is created but the img is not shown i cant find where the problem is help plz

$.each(data.user, function (i,data) {

    $("<div>"+data.id+"  </div>").attr('id',data.id).appendTo('#page_14_14');
    $('#'+data.id).css({"border-color": "#C1E0FF", 
                        "border-weight":"1px",
                        "margin-top":"10px",                    
                        "border-style":"solid"});

    var ctrl = $('<input/>').attr({ type: 'text', name:'text', value:data.email , id:data.email, disabled:true }).addClass("text");
    $(ctrl).appendTo("#"+data.id); 
    $('#'+data.email).css({"border-color": "#C1E0FF", 
                           "width":"50px",
                           "margin-top":"10px",                    
                           "border-style":"solid"});

    var img = $('<img/>').attr({ className:"inline" , src:"/www/images/Arrow.png" }).addClass("img");

    $(img).appendTo("#"+data.id);        
});   

i also used this for the following two methods for the img but i had the same problem

 var img = $('<img/>', {"class" :"inline", src:"/www/images/Arrow.png"     });


 var img = $('<img class="inline" src="/www/images/bg.png" width="50px" height="50px"  />');


php - pass an array from php to jquery ajax and then again pass the same array from jquery to php


I am in a situation where i am passing an array from php to jquery ajax using json_encode and saving it in an empty array i declared in jquery script var myarr = [], and later on in the same script i am sending the same array i-e, myarr to php script through $.ajax using JSON.stringify function and receiving the array in php script like this json_decode($_POST['myarr'], true), but the problem is it is not converting back into an array. I want to receive an array so that i can use foreach loop to read that array.

Here is the code below. First I am declaring an array in jquery script

var imgArr = [];

Then fetching all the images from php script and saving it in above declared array

PHP Script:

$getProfileId = $users->getPrfId($photoId);
$getImages = array();
$getImages = $users->getTypeImage($getProfileId);
//echo json_encode($getImages);
foreach($getImages as $value){
   echo json_encode($value);
 }

JQuery
  $.ajax({
        type: 'POST',
        url: 'fetchAllImages.php',
        data: {'photoId': photoId},
        success: function(data){
             imgArr = data;
          }
        });

Now in the same script on other button click i am sending this array imgArr to php Script using $.ajax. Here is the code:

JQuery:

$('#right_arrow').live('click', function(e){

var photoId =   $(this).siblings('#o_popup_post').children('#o_post_box').children("#o_complete_post_image").children("img").attr("id");
       $.ajax({
       type: 'POST',
       url: 'nextImage.php',
       data: {'photoId': photoId, 'imgArr' : JSON.stringify(imgArr)},
               beforeSend: function(){
                $('#o_popup_post').fadeOut("normal").remove();
                    $('.o_background_popup').append("<div id='o_popup_post'></div>");
       },
       success: function(response){
            $('#o_popup_post').append(response);
        // alert(imgArr);

       }
    });
   });  


  PHP Script:

  $photoId = $_POST['photoId'];

  $imageArray = array();
  $imageArray = json_decode($_POST['imgArr'], true);

  foreach($imageArray as $key=>$value){....}

Please help. Thanks


How to obtain innerHTML of an active li link?


I want to store the innerHTML of an active menu item to display it as a title for my page. The title HTML is {{pageTitle}}, in the "container" template.

here is my (cleaned) HTML

<template name="container">
   {{pageTitle}
   {{ > SideMenu}}
</template>

<template name="SideMenu">
    <ul id="menu-items" class="nav nav-stacked nav-pills">
        <li id="menu-item-simple" class="">
            <a href="#">
                menuItem1
            </a>
        </li>
        <li id="menu-item-simple" class="">
            <a href="#">
                menuItem2
            </a>
        </li>
    </ul>
</template>

I created an helper to return the string

Template.container.helpers({
"pageTitle":function(){
    return Session.get("pageTitle");
}
});

And an event to set the string to its correct value when a menu item is clicked

Template.SideMenu.events({
    "click #menu-items":function(e,t){
        var activeItem = $(this).find("li.active")
        Session.set ("pageTitle",activeItem.children("a").innerHTML);
        console.log (activeItem.children("a").innerHTML);
    }
});

The console returns "undefined". I don't get what I am doing wrong and since I'm just beginning, I also wanted to know if I'm going the right way.


how to put a message while waiting for callback from ajax


I would like to insert an image working.gif while the data is being processed by the PHP post.. right now it just does nothing until data is returned.. sometimes there is a 10-15 second processing time before data is returned so some sort of indication to tell the user to wait will be great. Lets use the working.gif image as that indicator.

Appreciate assistance on how i can factor the above in to the following code:

$.ajax({
    type: "POST",
    url: "post.php",
    data: dataString,

    //if received a response from the server
    success: function (response) {

        $('#ajaxResponse').html('<pre>' + response + '</pre>');


Convert jquery/js function to pass variable between pages to a ColdFusion variable


I have some jquery which checks if a particular element is visible on a page and passes a parameter to be appended to the url, so the element can be shown/hidden on the next page.

I want to see if it is possible to store this value in a coldfusion variable and then pass it via the navigation, as this seems to be a more robust method to me.

Here is my basic html:

<nav>
            <ul id="mainNav" class="clearfix">
                <li><a href="/">Main</a></li>
                <li><a href="#" class="<cfif VARIABLES.primarydir EQ 'work'>clicked</cfif>">Work</a></li>
                <li><a href="/about"  class="<cfif VARIABLES.primarydir EQ 'about'>clicked</cfif>">About</a></li>
                <li><a href="/news" class="<cfif VARIABLES.primarydir EQ 'news'>clicked</cfif>">News </a></li>
                <li><a href="/tumblr.com" target="_blank">Blog</a></li>
            </ul>
            <ul id="subNav">
                <li><a href="/work/effort" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'effort'>clicked</cfif>">Effort, We Cried!</a></li>
                <li><a href="/work/why" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'why'>clicked</cfif>">Why Do We Do This</a></li>
                <li><a href="/work/guests" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'guests'>clicked</cfif>">Guests &amp; Hosts</a></li>
                <li><a href="/work/prettygirls" class="<cfif VARIABLES.primarydir EQ 'work' and VARIABLES.secondarydir EQ 'prettygirls'>clicked</cfif>">Pretty Girls Doing Horrid Things</a></li>
            </ul>
</nav>

#subNav is set to hidden by default in the css.

I think have some basic jquery to toggle the visibility of the subNav:

    var toggleSubNav = (function(){
        trigger.on('click',function(){
            subNav.toggleClass('visible', function(){
                subNavLength = subNav.is(':visible');
            });
            return false;
        });
    }());

And then a second function which checks the visibility of the subNav and appends the url:

merge.on('click',function(){
            var url = $(this).attr('href');
            subNavLength = subNav.is(':visible');
            if(subNavLength){
                window.location = url + '?subnav=true';
            }else{
                window.location = url;
            }
            return false;
        });

Finally a function which checks the url for the content of '?subnav=true' to display this on the next page:

var subNavProp = (function(){
        if(href.indexOf('?subnav=true') > 0){
            subNav.addClass('visible');
        }else{
            subNav.removeClass('visible');
        }
    }());

The variable subNavLength is global and gets updated via these various functions.

I realise I am posting an awful lot of jquery and I don't really know how (or if) there is a way to convert this to a backend solution for coldfusion. My thought was that I could toggle a class on the subNav element that is wrapped in a coldfusion if, something like:

<ul id="subNav" class="<cfif var IS true">className</cfif>">

But I am wondering if that still requires something of a Front End solution. Or even if there is another better way to do this?


Passing mouseover through element


I'm working on a regex-analyzer that has syntax highlighting as a feature.

My site uses an overlay of two contenteditable divs.

enter image description here

Because of the difficulty in getting the cursor position and maintaining that even as tags are added and subtracted, I decided the best route was to have two contenteditable divs, one on top of the other. The first (#rInput) is pretty plain. If not for some nuisance problems that made me switch from a textarea, it could be a textarea. The second (#rSyntax) gets its value from rInput and provides syntax highlighting. I make sure that both are always scrolled to the same position so that the overlay is perfect (However, I also use a transparent (rgba(...)) font on rSyntax, so that if a momentary sync-delay should occur, the text is still legible.)

In the lower portion snapshot above, the code of the contenteditable rSyntax is this:

<span class="cglayer">(test<span class="cglayer">(this)</span>string)</span>

While rInput, positioned exactly on top, contains only this

(test(this)string)

The problem with this method is that I want to offer some alt-tooltips (or a javascript version) when a user mouses over. When the user mouses over rInput, I would like to pass the mouseover event to elements of rSyntax.

I'd like mousing over (test ... string) to show "Capturing group 1", while mousing over (this) would show "Capturing group 2", or if it were (?:test), it would say "Non-capturing group".

The terminology is a little tough because searching for things like "above" and "below" pulls up a lot of results that have nothing to do with z-index.

I did find the css property pointer-events which sounded ideal for the briefest moment but doesn't allow you to filter pointer events (set rInput to receive clicks, scrolls, but pass mouseover through to rSyntax and its child-elements.

I found document.elementFromPoint which may offer a solution but I'm not really sure how. I thought I would try document.getElementById('rInput').getElementFromPoint(mouseX,mouseY), but this function is not available to child elements.

Theoretically, I could hide the rInput on mousemove, using a setTimeout to put it back quickly, and then a tooltip should appear when mousing over child elements of rSyntax, but that doesn't seem like the best solution because I don't want rSyntax to be clickable. Clicks should always go to rInput.

It's possible to disable the mouseover wizardry while rInput has the focus, but then tooltips from rSyntax won't work, and though I haven't tried this method, I'm not sure if passing a click event from rSyntax to rInput would position the cursor properly.

Is there a method to make this work?


check if the image is available in the given URL by javascript / angularjs or jquery


I am developing an application using java and angularJS. I am getting an image url from database and in the client side I want to check whether that Image is available in that url, if ONLY display it else to display a default image I have.

So how can I check that image is actually available in the given URL..?


Manipulating dynamically generated elements on page load (not a click event or similar)


To bind code to dynamic elements the following is often used: $(document).on('click','#element',function() {});

However I want to do something with those elements on page load, not when user does something particular. How to do that?


Is there a reliable jQuery plugin hat can repopulate the form from json values?


I have a form with 180 form fields. On a button click I need to replace current form fields values with the ones from json var. Instead of doing

on some element click 
$.each(getData, function(index, value) {

    check if select
        add new value, trigger refresh
    check if radio
       add new value, trigger refresh
    check if textarea
       add new value, trigger refresh
...

is there already a plugin that does something like this? I browsed and came up with very old scripts like populate or loadJSON wich are not supported anymore.

My biggest issue is that this is a multi level json array and the field names are like

<input name="form_field[one]"...
<input name="form_field[one][two][three]"...
<input name="form_field[one][two]"...

any help is appreciated.


JQuery Mobile creates wrong HTML code


I'm currently developing a PhoneGap Application for Android using JQuery Mobile. All i want, is to dynamically change the header text of a collapsible:

<div data-role="collapsible" id="collapse">
   <h3>I'm a header</h3>
   <p>I'm the collapsible content</p>
</div>

That code is from demos.jquerymobile.com. Chrome DevTools gives me the following html for this example: http://ift.tt/1HCVBut

For any reason, if i copy exactly the same code to my index.html and run it, chrome DevTools gives me the following html: http://ift.tt/1Gt3UWD

Why are there different html codes?

I actually can change the header's text by

$("#collapse").text("new text");

but then it looses all the styling and also

$("#collapse").trigger('create').

doesn't do anything. What am I doing wrong?


Create a 3D Slideshow with jquery


I'm looking to create a 3D Slideshow or carousel through jquery, css, & html. Something like this is what i want to have http://ift.tt/1ORLSiV

It would be nice if you can include the reflection on the images as well. I only plan to put 3-5 into the carousel.

If anyone could help me, it would be much appreciated


How to end JQuery endless scroll


I know this topic is overflowing on this site however when using the endless scroll plugin below I was hoping to figure out a way of just loading from my ajax request but somehow just ending at some point. e.g. eventually reaching the bottom? Any help is much appreciated?

     <script type="text/javascript">
$(window).scroll(function()
{
    if($(window).scrollTop() == $(document).height() - $(window).height())
{
    $('div#loadmoreajaxloader').show();
    $.ajax({
    url: "{{url('contentpage')}}",
    success: function(html)
    {
        if(html)
        {
            $("#postswrapper").append(html);
            $('div#loadmoreajaxloader').hide();
        }else
        {
            $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
        }
    }
    });
    }
});
</script>


How to find today's date in DateTimePicker JavaScript?


I'm using the following javascript: http://ift.tt/1MosCse , and I want to achieve simple effect - when User selects today's day, it should show him only hours available from now until the end of the day, the previous time should be disabled. But when he choses any other day in the future - then the whole time should be available. I wrote the following function in JS:

<script>
var today = new Date();
var dd = today.getDate();
alert(dd);
           var logic = function( currentDateTime ){
  if( currentDateTime.getDay()==dd ){
    this.setOptions({
      formatTime:'g:i A', 
format: 'd/m/Y h:i A',
  minDate:'+1970/01/02',//today
  minTime: //I don't know yet how to implement the current time
    });
  }else
    this.setOptions({
     formatTime:'g:i A', 
format: 'd/m/Y h:i A',
  minDate:'+1970/01/02'//today
    });
};


                jQuery('#datetimepicker').datetimepicker({
                onChangeDateTime:logic,
                onShow:logic
                });

</script>

The problem is that that line:

currentDateTime.getDay()==dd

doesn't work, because in my case dd equals todays day of the month (e.g. 25), and currentDateTime.getDay() checks current day of the week (e.g. for saturday it's 6). Is there anyone who could help me with that issue? I know there are some other available solutions (other datetime pickers), but I cannot find any other that is as simple and elegant as this. Thanks!


How to get the text from a specific closest element?


I've been learning to code by my own and to do some fancy stuff with jquery library but I'm stuck here. This is what I got:

<span class='ccy'>San Diego</span><span class='dc'> X</span>
<span class='ccy'>San francisco</span><span class='dc'> X</span>
<span class='ccy'>Palo alto</span><span class='dc'> X</span>

I want to be able to click in the $("span.dc") and get only the text() of the < span> next to it (the name of the city), works fine if there is only one city in the html, but as long as I keep adding them up the result gets messy and I end up with a string containing all the city names and I only need one.

I know that the obvious thing would be give them a different id to each one but it'd get even messier 'cause the that html is dynamically generated depending on a previous event triggered by the user, the cities come from an array and I need the individual name of the city to delete from it if 'x' is clicked, I hope I've explained myself good enough.

jsfiddle here!! so you can see better what I mean


facing on Making voting system (Like /Unlike) Button for Q&A website in php , mysql using ajax


i have a Question & Answer website as a part of my graduation project , so am still fresh to such languages but i will try to be specific as much as i can ,,, well i got voting for both Question and answers at each special question page ,, i use the same voting code with changing queries to retrieve desired data ,, but the problem is one of the voting system only works (Question voting or Answers voting) i suppose the problem is action listener is listen to the same btn or the span or smth like that i tried to change values but without any mentioned result,, i will provide all the code am using and am ready to replay to any comment to make stuff clear so i hope you guys help me out to make both voting systems work in the same page ,, thnx you very much ... ^^

srip.js > script for questions

 $(document).ready(function(){
    // ajax setup
$.ajaxSetup({
    url: 'ajaxvote.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };

        // add disabled class with .item
        parent.addClass('.disabled');
       };
   });
});

ajaxvote.php for opertion inside the questions

<?php


include('config.php');
# start new session
dbConnect();
session_start(); /*  changes will occuar here */

if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    //if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query(" 
        SELECT rate
        from qa
        WHERE id = '{$postId}' 
        LIMIT 1" ); /*  changes will occuar here */

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['rate'];
        } else {
            $vote = --$data['rate'];
        }
        # update new voting score
        mysql_query("
            UPDATE qa
            SET rate = '{$vote}'
            WHERE id = '{$postId}' "); /*  changes will occuar here */

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
}
?>

printing code : QR.php

  <?php 

require ("coonection.php");

if(isset($_GET['start']) )
 {
  $FURL = $_GET['start'];


   $data=mysql_query("SELECT * FROM qa WHERE id=($FURL)");
   while($d=mysql_fetch_assoc($data)) { ?>
  <div class="item" data-postid="<?php echo $d['id'] ?>"  data-score="<?php echo $d['rate'] ?>">
        <div class="vote-span"><!-- voting-->
            <div class="vote" data-action="up" title="Vote up">
                <i class="glyphicon glyphicon-thumbs-up"></i>
            </div><!--vote up-->
            <div class="vote-score"><?php echo $d['rate'] ?></div>
            <div class="vote" data-action="down" title="Vote down">
                <i class="glyphicon glyphicon-thumbs-down"></i>
            </div><!--vote down-->
        </div>

        <div class="title"><!-- post data -->
              <p><?php echo $d['question'] ?></p>
          </div>
     </div><!--item-->
    <?php  } } ?>
    </div>

 </p>


                        </div>
    <div class="single-post-title" align="center">
    <h2>Answers</h2>
    </div>
                        <!-- Comments -->
     <?php



  require ("coonection.php");
    if(isset($_GET['start']) )
    {
        $FURL = $_GET['start'];
        $data=mysql_query("SELECT * FROM answers WHERE question_id=($FURL)");
        while($d = mysql_fetch_assoc($data))
        {



                echo'<div class="shop-item">';
                echo'<ul class="post-comments">';
                echo'<li>';
                echo'<div class="comment-wrapper">';
                echo'<h3>';
                echo  $d['answerer'] ;
                echo'</h3>';
                echo '</div>'; ?>
                 <div class="item" data-postid="<?php echo $d['answer_id'] ?>" data-score="<?php echo $d['rate'] ?>">
        <div class="vote-span"><!-- voting-->
            <div class="vote" data-action="up" title="Vote up">
                <i class="icon-chevron-up"></i>
            </div><!--vote up-->
            <div class="vote-score"><?php echo $d['rate'] ?></div>
            <div class="vote" data-action="down" title="Vote down">
                <i class="icon-chevron-down"></i>
            </div><!--vote down-->
        </div>

        <div class="post"><!-- post data -->
            <p><?php echo $d['answer'] ?></p>
        </div>
    </div><!--item-->
<?php
                echo'<div class="comment-actions"> <span class="comment-date">';
                echo  $d['dnt'] ;
                echo'</div>';
                echo'</li>';
                echo'</ul>';
                echo'</div>';            




          }

        }
    ?>

i got ajaxvote2.php and also got scrip2.js for settings in answer ,,, i think using the same code make the printing page confused and only listen to one of voting systems

i will add ajaxvote2.php and scrip2.js just in case some one need to look at them ...

ajaxvote2.php

 <?php


include('config.php');
 # start new session
 dbConnect();
 session_start(); /*  changes will occuar here */

 if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
 if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    //if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query(" 
        SELECT rate
        from answers
        WHERE answer_id = '{$postId}' 
        LIMIT 1" ); /*  changes will occuar here */

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['rate'];
        } else {
            $vote = --$data['rate'];
        }
        # update new voting score
        mysql_query("
            UPDATE answers
            SET rate = '{$vote}'
            WHERE answer_id = '{$postId}' "); /*  changes will occuar here */

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
} 
?>

scrip2.js

$(document).ready(function(){
// ajax setup
$.ajaxSetup({
    url: 'ajaxvote2.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };

        // add disabled class with .item
        parent.addClass('.disabled');
    };
 });
});


jQuery Slider that fades and slide at same time


I've been trying to find a jQuery Slider that fades and slide at the same time but no sucess so far, so I've decided to try and create my own. Well, so far, I've managed to make it slide and barely fade, by barely I mean that in bigger screens it might look like the content is blinking.

This is my HTML:

<div id="slider">
    <div class="slide">
        <h1>A Phrase</h1>
    </div>
    <div class="slide">
        <h1>A Phrase</h1>
    </div>
    <div class="slide">
        <h1>A Phrase</h1>
    </div>
</div>

This is my jQuery:

var slider = $('#slider .slide'),
    winWidth = $(window).width();

slider.css({
    width: winWidth
});
$(window).resize(function(){
    winWidth = $(window).width();
    $(args).css({
        width: winWidth
    });
});

var slideW = slider.width(),
    slidesQty = slider.length,
    sliderFullW = slidesQty * slideW,
    slideMvCheck = winWidth/2;

$('#slider').css({
    width: sliderFullW
});

function cycleSlides(){
    $('#slider').animate({
        left: -winWidth
    }, {duration: 2000, queue: false}).fadeOut(700).fadeIn(2000, function(){
        $('#slider .slide:first-child').appendTo('#slider');
        $('#slider').css({left: 0});
    });

}

var autoSlide = setInterval(function () {
    cycleSlides();
}, 4000);

I need help tweaking the code, I've tried a lot of different things in the past two days, I've ran out of ideas and I'm not very good with jQuery.


update jQuery to use with widget


I'm trying to upgrade a site template that uses mainly jQuery 1.08 to use 1.11, since a widget I want to connect to the subscribe form uses 1.11.

Here's the template I'm using:

http://ift.tt/1HD7NLQ

What's weird is if I use the following code, the header is there but the form doesn't work properly:

<script src="scripts/jquery-1.11.0.min.js"></script>

And if I use this code, the form works but the header disappears:

<script src="http://ift.tt/1g1yFpr"></script>

I can't use both either, because whenever I enter the second line the header disappears for some reason. What gives, can someone please help me? Thanks!


Open window in new tab without user event


Here I have two asp.net mvc websites . From first website i have one link to second website. So first website will call the second's action. I want to open on page in new tab and current tab should redirect to my first website. This action will return one view.

My approaches in view

  1.   $(document).ready(function (e) {
            window.open("/newpage");
            window.open("/site1", "_self");
    
      });
    
    

    Browser popup blocker will block this. Because there is no user event . So I tried different approach

2 $(document).ready(function (e) {

    $("#input").on("click", function () {


        window.open("/newpage");
        window.open("/site1", "_self");
    });
    $("#input").trigger("click");


});

test one

I have created triggered one event. But still its blocked. This two approaches is working fine if popup blocker is disabled. I want to open page in new tab without disable the popup blocker.

NOTE: This two website comes under same domain name . eg: abc.com\siteone and abc.com\sitetwo