March 31, 2012

I want to INSERT VALUES but I don't want user to navigate to this page

Question by user1304328

I want to INSERT VALUES after user has clicked OK on the confirmation box. Now the confirmation box works well. The only problem I can see is that when the user clicks ‘OK’ I want the INSERT VALUES to happen on a seperate page (insertQuestion.php) but I do not want the form to be navigated to that page. I want the form to navigate the way it is doing which is either submit to its own page or submit to create_session.php depending on the situation ($action).

So how can I INSERT VALUES into the database without navigating the user to that page (insertquestion.php) after the user has clicked ‘OK’ in the confirmation box?

below is the javascript code where the confirmation box appears and if confirmation is ‘OK’, it submits the form:

 function showConfirm(){

             var confirmMsg=confirm("Do you want to Proceed" + "n" );

             if (confirmMsg==true)
             {
             submitform();   
         }
    }

 function submitform()
            {

        var QandAO = document.getElementById("QandA");

          QandAO.submit();

            }

Answer by Starx

Post the form using an ajax request.

A simple example using jQuery

$("#yourbutton").click(function() {
   var fieldvalue = $("#inputname").val(); //grab the form value
   $.post("yourpage.php", //send it to yourpage.php
       {
          field1: fieldvalue
       }, function(data) {
         //do something on success
       }
   );
});

Remove duplicate commas and extra commas at start/end with RegExp in Javascript, and remove duplicate numbers?

Question by Mohammad

Assume we have a string like the following :

,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56

How can we convert it to the following string with RegExp in Javascript ?

34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56

Actually, I wanna remove repeated items and first and last , char

Answer by ninjagecko

[edited] To turn these into a set of unique numbers, as you are actually asking for, do this:

function scrapeNumbers(string) {
    var seen = {};
    var results = [];
    string.match(/d+/g).forEach(function(x) {
        if (seen[x]===undefined)
            results.push(parseInt(x));
        seen[x] = true;
    });
    return results;
}

Demo:

> scrapeNumbers(',1,22,333,22,,333,4,,,')
[1, 22, 333, 4]

If you had an Array.prototype.unique() primitive, you could write it like so in one line:

yourString.match(/d+/g).map(parseBase10).unique()

Unfortunately you need to be a bit verbose and define your own parseBase10 = function(n){return parseInt(n)} due to this ridiculous hard-to-track-down bug: javascript – Array.map and parseInt

Answer by Starx

No need for regex. Few tricks

text = ',34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56';
text = text.replace(/,+/g, ','); //replace two commas with one comma
text = text.replace(/^s+|s+$/g,''); //remove the spaces
textarray = text.split(","); // change them into array
textarray = textarray.filter(function(e){ return e.length});
console.log(textarray);                                       


// Now use a function to make the array unique
Array.prototype.unique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(this[i] in u)
         continue;
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

textarray = textarray.unique();
text = textarray.join(','); //combine them back to what you want
console.log(text);

Demo

If you are familier with jQuery

text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);

Demo

User specific stylesheet?

Question by user1305075

I have a website where a user chooses a template of their choice for their web page.

Once they’ve selected the template, I want them to be able to change some of the styles such as the font colour etc?

Is there a way I could do this?

I thought of perhaps storing the user specified stuff in a field in a database and then retrieve it and display as internal CSS?

Answer by Monojit

You may use a user.css (initially empty) for each user and then add data provided by user with !important override.

Answer by Starx

Yes

It is possible. But you will have to rely on Javascript to add the stylesheet, url selected.

Assuming you would be using a link to change the theme, using jQuery, you would do

$('#red').click(function (){
   $('#linktagid').attr('href','user_red.css');
});

How to calculate driven distance using latitude & longitude in php?

Question by hazem

Given something like this:

//$unit="K";
//$unit="m";

$driven_distance ($lat1, $lng1, $lat2, $lng2, $unit);

How I can I get the time between these two points?

Answer by Starx

A pick out function [Source]

function getDistance($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
   $theta = $longitude1 - $longitude2;
   $distance = (sin(deg2rad($latitude1)) *
   sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
   cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
   $distance = acos($distance);
   $distance = rad2deg($distance);
   $distance = $distance * 60 * 1.1515;
   switch($unit)
   {
      case 'm': break;
      case 'K' : $distance = $distance *1.609344;
   }
   return (round($distance,2));
}

This functions rounds the result to two decimal places.

Now use exatly the way you are using

$driven_distance = getDistance($lat1,$lng1,$lat2,$lng2,$unit);

Update:

If you want to find out the driven distance the best bet is to use google’s geocode api.

$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=true_or_false
');
$details = json_decode($json, TRUE);
var_dump($details);

Entry Of Duplicate Rows in Mysql

Question by dotman14

Please I need your help with my script. I’m trying to insert values into maintable, but before I insert, I have to check if a row have an exact match compared to the one I’m inserting. If there’s a match then it should echo Record Exists, and if not it should go ahead and insert into the table. The problem is that it is returning 0 for $duplicate, when actually there is a row that matches the entries that I’ve entered in the HTML page, thereby it goes ahead and inserts the duplicate.
Please what could the problem be?

{
    $query = mysql_query("SELECT m.matric_no, m.course_code, m semester_name, m.level, m.session 
                          FROM  maintable AS m 
                          WHERE m.matric_no = '".$matric_no."'
                          AND m.course_code = '".$course_code."'
                          AND m.semester_name = '". $semester_name."'
                          AND m.level = '".$level."'
                          AND m.session = '".$session."'") ;

    $duplicate = mysql_num_rows($query);

    if ($duplicate > 0 ) 
        echo "$duplicate" ;
    {
        echo "Record Exists"     
    }
    else
    {

        $query = "INSERT INTO maintable (matric_no, course_code, semester_nam,          session, level) 
                   VALUES ('".$matric_no."', 
                       '".$course_code."',
                       '".$semester_name."',
                       '".$session."', 
                       '".$level."')" ;
        mysql_query($query) or
            die (mysql_error());   

        echo"Record Inserted"; 
    }

Please forgive my formatting, I typed on a mobile, I didn’t mean disrespect to this community.

Answer by Jamie

Your formatting’s a bit all over the place, which is why you’re finding it so hard to spot errors when they occur. Try sticking to a consistent format style. This should do the trick:

$check = mysql_query("SELECT * FROM maintable WHERE matric_no = '$matric_no' AND course_code = '$course_code' AND m.semester_name = '$semester_name' AND m.level = '$level' AND m.session = '$session'");

if(mysql_num_rows($check))
{
   echo 'Record exists!';
}
else
{
   $query = "INSERT INTO maintable (matric_no, course_code, semester_nam, session, level) VALUES ('$matric_no','$course_code','$semester_name','$session','$level')";
   mysql_query($query) or die (mysql_error());
}

Answer by Starx

You are counting rows, which may return 0 if no records matching your query were found. However you are mixing if code block

if ($duplicate > 0 ) 
    echo "$duplicate" ;
{
    echo "Record Exists"     
}

Should be

if ($duplicate > 0 )         
{
    echo "$duplicate" ;
    echo "Record Exists"     
}

I have checked your code, and it seems valid. Try to simplify it

$result = mysql_query("SELECT * FROM maintable WHERE matric_no = '$matric_no' AND course_code = '$course_code' AND m.semester_name = '$semester_name' AND m.level = '$level' AND m.session = '$session'");

if(!mysql_num_rows($result))
{
   $query = "INSERT INTO maintable (matric_no, course_code, semester_nam, session, level) VALUES ('$matric_no','$course_code','$semester_name','$session','$level')";
   mysql_query($query) or die (mysql_error());
}

How to make a link navigate to another page and also mailto an email?

Question by Doug Firr

I’d like a link where if someone clicks a mailto link they are also shown a different page.

What would the html look like? Currently:

<a href="mailto:someone@mail.com">email</a>

Any ideas?

Answer by Starx

Use Javascript’s window.location on the click event of the link

<a href="mailto:someone@mail.com" onclick="window.location=another.html">email</a>

Update:

If you have to stack up lots of code in the onclick event, create a function instead

function handleClick() { 
   _gaq.push(['_trackEvent', 'emails', 'clicked', 'lead']); //first this
   window.open = 'anotherpage.html'; //or window.location for redirection
}

HTML

<a onclick="handleClick()" href="mailto:someone@mail.com">email.com</a>

getting the child text from a div in a .each loop

Question by randy

this is just a couple of lines of code that i have in my page.
I am using the jquery ui drag and drop. These are two of the items of many

when the saved button is press i need to get all the IDs and the text in the group_name div

This function gets the ID ok but i can not figure out how to get the $(‘group_name’).text() from the current LI in the each loop.

   function saveChanges(){
        $("li.ui-state-default").each(function() {
            var $divitem = $( this );
            console.log($divitem.attr('id'));
        });
    }

this is the html snippet

<li id="5" class="ui-state-default">
<div class="group_name">Classes</div>
<div class="group_footer">
      <a title="Delete this group" class="mytrash-icon" href="#">
         <img border="0" src="trash.png" class="mytrash-img"></a>
      <a title="Manage Subfolders" class="subfolder" href="#">   
         <img border="0" src="Folder-Icon.png"></a>
    </div>
</li>
<li id="6" class="ui-state-default">
<div class="group_name">Coaching</div>
<div class="group_footer">
        <a title="Delete this group" class="mytrash-icon" href="#">
          <img border="0" src="trash.png" class="mytrash-img"></a>
        <a title="Manage Subfolders" class="subfolder" href="#">
          <img border="0" src="Folder-Icon.png"></a>
    </div>
</li>

Thanks for any help!

Answer by Starx

One way would be to use .find()

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($divitem.find(".group_name").text());
});​

Another would be to use .children()

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($divitem.children(".group_name").text());
});​

But the one I like is neither

$("li.ui-state-default").each(function() {
    var $divitem = $(this);
    console.log($(".group_name", $divitem).text());
});

Tools like LESS

Question by noahklein94

I recently started using LESS and I love it. Are there any other useful tools that expand CSS and/or HTML with more functionality?

Answer by Starx

FIRST of all they are not TOOLS

They are extensions to original CSS, they allow you to create style sheets in a very efficient pattern. Give programming like feature in CSS.

Second, SASS is a perfect alternative to LESS and quite popular one to.

Why doesn't the jQuery script set the width of an element?

Question by JamesCharless

James here. I’m working on a site that I want to have the same number of posts no matter what the screen resolution. I’m trying to use this script, but it’s not working. It SHOULD get the width of the page document, subtract 400px, divide that number by 4, and then set the CSS of the element .entry to that math equation. Can anyone help me figure out what’s wrong? I’m new to jQuery, so it’s surprising I was able to even get this far.

EDIT: I solved my problem using this code in the end:

$(function() {
            var cwidth = $(document).width() - 100;
            var pwidth = cwidth - 150;
            var ewidth = (pwidth - 150)/5;
            $("#container").css("width", cwidth);
                $("#posts").css("width", pwidth);
                $(".entry").css("width", ewidth);
                $(".photo").css("width", ewidth);
});

So thank you all quite a bit for helping. However, I’ve ran into a few more problems. For some reason even though the script divides by 5, there are only 4 posts per row and the posts overflow out of the div they’re in. Example: http://jamescharless.tumblr.com/ – I think this is because the div the entries are in doesn’t have a width set in the CSS since it’s added with jQuery. Does anyone know how to fix this? Also, I tried implementing masonry by David Desandro, and it just messes up the whole page. I think this is also because the div #posts and the div .entry doesn’t get a width via CSS. Can anyone help me with either of these issues?

Answer by Jack Franklin

You need to do:

$(document).width()

Not

$("document").width()

Working JSFiddle: http://jsfiddle.net/WsZry/

$(function() {
    width = ($(document).width()-400)/4;
    $(".entry").css("width", width);
})​;

As document isn’t a HTML element, it’s a JavaScript property.

Answer by Starx

You quoted the document inside double quotes $("document")

$(function() {
    var width = ($(document).width() - 400)/4;
    $(".entry").css("width", width);
});

jQuery sliding animation not working

Question by Jake Zeitz

I have three divs stacked on each other but offset so that a part of each div is visible. When one of the bottom divs is clicked I want the top div to animate out and back into the stack at the bottom, then the div that is clicked will appear at the top. So far I only have the code for when the middle div is clicked, but I cannot get it to work properly. What am I doing wrong? (I also realize that the code I wrote is probably terrible, this is the first jQuery code I have written.)

The css is very very simple:

    .first {
        z-index: 3;
    }
    .second {
        z-index: 2;
    }
    .third {
        z-index: 1;
    }

The basic html is this:

    <div class="first"></div>
    <div class="second"></div>
    <div class="third"></div>

Here is my code:

    $("div.second").click(function () {
        $("div.first").animate({
            left: "-=200px"},
            {duration: "fast",
            complete: function () {
                $("div.first").removeClass("first").addClass("third").animate({left: "+=350px", top: "+=60px"}, "fast");
            }
        });
        $("div.second").animate({
            left: "-=24px", top: "-=30px"},
            {duration: "fast",
            complete: function () {
                $("div.second").removeClass("second").addClass("first");
            }
        });
        $("div.third").animate({
            left: "-=24px", top: "-=30px"},
            {duration: "fast",
            complete: function () {
                $("div.third").removeClass("third").addClass("second");
            }
        });
    });

I can get the div.first to move to the side and back. But now I can’t get the classes to stay changed. What keeps happening is the div.second will remove it’s class and add .first in the animation, but when the animation is complete, it acts like it still has a class of .second.

Answer by Starx

That coding style is very inefficient.

Use something like this, It applies to every div

$("div").click(function() {
   var first = $(".first");
   var fleft = first.css("left");
   var ftop = first.css("top");           

   var $this = $(this);
   var tLeft = $this.css('left');
   var tTop = $this.css('top');
   var tClass = $this.attr("class");

   first.animate({
      left: tLeft,
      top: tTop
   }).attr("class", tClass);

   $this.animate({
       top: ftop,
       left: fleft
   }).attr("class", "first");        

});

Demo

...

Please fill the form - I will response as fast as I can!