September 21, 2012

Ajax Give Response but not Executing the PHP Service

Question by Hatem

Am doing Ajax request to a file which sends a mail. It give me the correct response which is “Message Sent” but the mail not sent. When I try to execute that file from the browser with the same GET Headers , it send the mail.

So what’s the problem here ?

The ajax request working well and triggered using (success) keyword in jquery to make sure that it succeed.

Help me !

For ajax side :

function SendEmail(To, Subject, Message) 
{
 var URL = 'mail-service.php?to=' + To + '&subject=' + Subject + '&msg=' + Message;

$.ajax({
    url: URL,
    type: 'GET',
    success: function (res) {
        alert("Message Sent to : " + To);
    }
});
  }

for PHP side :

<?php
$url = "http://mydomain.com/mail/mail.php?to=".$_GET['to']."&subject=".$_GET['subject']."&msg=".urlencode($_GET['msg']);

$link = fopen($url,"r");

while($res = fread($link,100))
{
    echo $res;
}

fclose($link);
 ?>

Answer by Starx

You misunderstood the function, The success function of the AJAX request executes once the request is successful, it does not care about what the page requested to did or did not.

To ensure you receive correct messages, you have to setup your PHP processing file, to return the response.

In your script

success: function (res) {
    alert(res); //Display the response text
}

And make sure your PHP file, return the response text as output.

while($res = fread($link,100))
{
    echo $res; //Make sure this is like "Message sent" or "Message sending failed"
}
July 22, 2012

how to navigate from one tab to other by clicking on a hyperlink using jquery ui tabs

Question by Hardworker

Could any one help me on how to navigate from first tab to second tab by clicking a hyperlink in first tab using JQUERY UI tabs?

Answer by Shant

You can refer the jQuery UI Tabs documentation for your problem, its very well mentioned

var $tabs = $('#example').tabs(); // first tab selected

$('#my-text-link').click(function() { // bind click event to link
    $tabs.tabs('select', 2); // switch to third tab
    return false;
});

Answer by Starx

You can switch between tabs freely by following the indexes using select method.
An example:

$("#tabs").tabs('select', 1);

Attach this snippet to the click handler of the link on the content of first tabs.

Example:

For a link like this:

<a href="some.html" id="nextTab">Go to Next Tab</a>

jQuery:

$("#nextTab").click(function() {
     $("#tabs").tabs('select', 1);
});
May 16, 2012

Jquery, get label value inside a user control

Question by LuisEValencia

I need to make a calculation in an asp.net page with the value from a usercontrol label.

the user control label is:

 <asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>

I include it like this:

<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />

And my jquery function is something like:
Please see point 1 and 2.

<script type="text/javascript">
        $(document).ready(function () {
            alert('call function to do calculation here');
            // 1.   Find in the vehicle information user control the invoiced ammount label
            // 2.   Find the vat excluded value **after** it was typed in the textbox
            // 3.   If invoiced ammount is greater than zero, then
            // 3.a  Find Label Percentage 
            // 3.b  Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
        });
  </script>

HTML generated:UPdate1

For the label:

 <span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>

For the textbox:

<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />

Update 2:

<script type="text/javascript">
        $(document).ready(function () {
            alert('call function to do calculation here');

            $("#TxtVatExcluded").keypress(function() {
                var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
                var vatexcluced = $("#TxtVatExcluded").val();
                var lblPercentage = $("#MainContent_LblPercentage");
                if (invoiceprice > 0) {
                    lblPercentage.text((vatexcluced / invoiceprice) * 100);
                }
            })

            // 1.   Find in the vehicle information user control the invoiced ammount label
            // 2.   Find the vat excluded value after it was typed in the textbox
            // 3.   If invoiced ammount is greater than zero, then
            // 3.a  Find Label Percentage 
            // 3.b  Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
        });
  </script>

Answer by Imdad

var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);

UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code

var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
  $("#TxtVatExcluded").val(label_text);
}

Answer by Starx

You can use the rendered ID of the elements to get the values using jQuery

var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();

Later when the calculation is complet, you can update the label text as

$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");

Update:

To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event

$("#myinputbox").keypress(function() {
    var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
    var tbox = $("#TxtVatExcluded").val();
    //... so on
}

Update 2:

Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.

        $("#TxtVatExcluded").keypress(function() {
            var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
            var vatexcluced = $("#TxtVatExcluded").val();
            var lblPercentage = $("#MainContent_LblPercentage");
            if (invoiceprice > 0) {
                lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
            }
        })
April 10, 2012

$.ajaxSetup does not set content type for Get requests

Question by Deeptechtons

Code 1

$.ajax({url:"1.aspx/HelloWorld",type:"GET",dataType:"json",contentType:"application/json"});

Request Response for Code1

Code 2

$.ajaxSetup({
   contentType: "application/json",
   dataType: "json"
});

$.get("1.aspx/HelloWorld","",$.noop,"json");

Request Response for Code 2

Code1 effectively sets both the content-type and datatype
Code2 does not set the content-type Is this Intended or Have i to do Voodoo stuff for making it work ?

Answer by Kevin B

I would just create a quick wrapper for the ajax method.

$.myAjax = function(url,data){
    return $.ajax({
        contentType: "application/json",
        url: url,
        data: data || {},
        type: "GET",
        dataType: "json"
    });
}
// used with
$.myAjax("foobar.asp").done(function(data){
    console.log(data);
}).fail(function(){
    console.log(arguments);
});

The reason that the header isn’t getting passed is that if the contentType isn’t specified for the given request and there is no data, the contentType is not set. It may be a bug since the contentType was set in the ajaxSetup, but I’m not positive on that.

Answer by Starx

$.ajaxSetup hold the default options for most of the all ajax request, but does not send an ajax request it self.

But $.ajax is the actual function that sends the request.


On Code 1:

It simply sends a GET Ajax request with comprehensive method $.ajax()

On Code 2:

The default options for all the ajax request are set before any request are sent. Then when the actual request is made using $.get, this parameters no longer have to be defined.


Update

This seems to be a bug. Such problem occurs when you are sending $.get request without any data. Check here. You need to see the request headers using firebug or similar.

Clear cookie via jquery?

Question by SOLDIER-OF-FORTUNE

I have a DNN installation but one of the portals is broken and the “logout” button doesnt seem to clear the cokoie. Is it possible to use jquery to clear a specific cookie? or a seperate ASP.NET page?

Answer by Starx

Sure, Using cookie plugin like this

$.cookie("name", null);

Update:

if($('a[href="webiste.co.uk/en-gb/admin.aspx"]').length) {
    $.cookie("name", null);
}

Update 2: Pure Js

function deleteCookie(name) {
    document.cookie = name+'="";-1; path=/';
}

var login = document.getElementById("loginlink");
login.onclick = function() {
  deleteCookie("name");
};
April 1, 2012

MailTo using Browser Options in new window IE 8

Question by abcdefghi

Below is the HTML

<a id="LnkEmail" onclick="doMailto('d@s.com');" href="javascript:void(0);">
<span id="LblEmail">ABC</span></a>

Javascript

<script type="text/javascript">
    function doMailto(EmailAddress) {
        document.location.href = window.open('mailto:' + EmailAddress, 'new window');
    }

</script>

In FireFox, it opens the image on clicking the span like below.

enter image description here
Query – In IE 8 – Nothing happens on clicking it. Any Idea ?

Answer by Starx

The mailing list is an utility features provided by Firebox only. You may or may not not find one software’s feature on another similar one. If you don’t, you should settle for a work around.

Try to remember that in firefox once the user selects a default mail client, you will not get the popup anymore. So there is no use of attempting to create a solution, that is not going to be permanent.

To trim down your requirement, you are trying to select the mail client of the user. But a website cannot changed the system settings of the user, its simply not allowed. Why? Because it opens many vulnerabilities to the user, if this was somehow allowed.

March 30, 2012

jQuery.html() not working well with Asp.Net innerHtml

Question by Umm….

So basically, I have a div which is runat=”server”

<div id="results" runat="server" class="results"></div>

Now, I add HTML to this using jQuery.

$('.results').html('Some crazy data');

However, when I try to access the data in this DIV using C#, it says the DIV has no contents.

string myResults = results.innerHtml;

myResults is empty.

Can someone help me out? I’ve never seen this behavior before.

Many Thanks!

Answer by amit_g

You may be looking for something like this…

<div id="results" runat="server" class="results"></div>
<input type="hidden" id="hiddenResults" runat="server" class="hiddenResults" />

$('.results').html('Some crazy data');
$('.hiddenResults').val('Some crazy data');

Now you can access the data on server

string myResults = hiddenResults.Value;

Answer by Starx

Instead of mixing up jQuery and Javascript. Try

var myResults = $(".results").html();

Just to verify everything is correct, see if your results is defined as below

var results = document.getElementById("results");
var myResults = results.innerHtml;

If you trying to get the value of results to the server, it is not possible through jQuery or Javascript unless send an AJAX request.

March 18, 2012

resize automatically iframe hieght

Question by adilahmed

i include a iframe in master page and i want to resize iframe height according to its contents inside.

when ever iframe content increase iframe height should be increase.

<div id="div_NotificationOuter" style="position: fixed; bottom: 0px; right: 15px;
            padding: 5px; background-color: White; background-image: url('../images/content_fixed_downup.png');
            background-repeat: no-repeat; min-height: 130px; text-align: left; display: block;
            border: 1px solid gray; width: 280px; overflow: hidden;">

    <asp:ImageButton ID="img1b" runat="server" ImageUrl="../images/close.png" 
                Style="margin-right: 2px;float:right;" OnClientClick="Hide_NotifyPopUp()" />

ALERTS

Your browser does not support iframes.

and iframe page is

<div id="iframe_content">
        <div style="overflow: auto;font-weight:bold " >
            <label id="lblNotifyMessage" runat="server" style="margin-left:15px;">

            </label>
        </div>
        <div style="font-size: 14px;margin-left:15px;">
            <asp:Label ID="lblCount_Followups" runat="server" Text=""
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="lblCount_Workflow" runat="server" Text="" 
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="lblCount_Inbox" runat="server" Text=""
                Style="margin: 2px"></asp:Label><br />
            <asp:Timer ID="Timer1" runat="server" Interval="111115000">
            </asp:Timer>

            <asp:Label ID="Label1" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="Label2" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="Label3" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />


            <asp:Label ID="Label4" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="Label5" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="Label6" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />


            <asp:Label ID="Label7" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="Label8" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />
            <asp:Label ID="Label9" runat="server" Text="Notification Message"
                Style="margin: 2px"></asp:Label><br />

        </div>
        </div>

Answer by Starx

You have to call a function on the parent page from the iframe to do this.

On parent page, create a similar function like this

function resizeIframe(var) {
    $("iframeid").height(var);
}

Now, from inside the iframe call the following snippet

$(window).load(function() { 
// ^ Once everything load. You can change this any event suitable
    parent.resizeIframe($(window).outerHeight());
});
March 12, 2012

How to determine the language of keyboard input using JQuery

Question by Maha Khairy

I have an application that accepts input in two languages (English and Arabic)
I’m validating the input textbox , the validation logic is not the same for English and Arabic, so I need to know what is the language the user is typing

all the solutions I came across determined the default language for the system and browser but nothing I found helped me determining the current input language

Answer by Starx

You can do this using Google’s AJAX Language API

var content = "your text";
google.language.detect(content, function(result) {
  if (!result.error) {
    var language = 'unknown';
    for (lang in google.language.Languages) {
      if (google.language.Languages[lang] == result.language) {
        language = lang;
        break;
      }
    }
    // Now use the variable `language`
  }
});
March 1, 2012

$find returning null

Question by Dhaval Shukla

I have radGrid in .ascx page in which I want to find the control using $find but it returns a null to me. Below is my code which I am using to get the object (written in .ascx).

<script type="text/javascript">
    $(function () {
        var Rates_gridID = $find('<%= gridRates.ClientID %>');
        alert(Rates_gridID);
    });
</script>

Here, I am getting Rates_gridID as null in alert. Interesting thing which I noted is when I change the jQuery version to 1.2.6 from 1.6.4 I am getting Rates_gridID object. I have googled this a lot but not getting any solution. I think the problem is with $(function().

Answer by Starx

You are using the incorrect syntax. Try

$("body").find('<%= gridRates.ClientID %>');
...

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