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?