AJAX

12K

Solutions

13

Articles & Videos

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.

Share tech news, updates, or what's on your mind.

Sign up to Post

So, I am really trying to get my head around JSON and I have tried this which works but I wanted to know if there is a better way to do it or if this okay. I am actually playing around with developing a hybrid mobile app which uses a php and mysql backend. I have to use ajax to retrieve data and I want to also use JSON.

This is the jQuery/Ajax. The double dollar signs are not a typo, that is the correct syntax for the application but it is identical to jQuery as far as I know.

$$( "#submit" ).click(function(e){
		$$.ajax({
			url:"content.php",
			type:"POST",
			dataType:"json",
			success: function(data) {
				var len = data.length;
				for(var i = 0; i<len; i++) {;
					var user_name = data[i].user_name;
					$$( "#phpcontent" ).append(`
					<li class="item-content">
						<div class="item-inner">
						<div class="item-title">${user_name}</div>
						</div>
					</li>
					`);
				}
			}
		});
	});

Open in new window


This is the php for content.php

$stmt = $link->prepare("SELECT `user_name` FROM `users` ORDER BY `user_name` DESC");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
	while($row = $result->fetch_assoc()) {
		$user_name = sanitize($row['user_name']);
		
		$return_array[] = array(
		
			"user_name" => $user_name
		
		);
	}
}
$stmt->close();
echo json_encode($return_array);

Open in new window


What I have noticed in all the examples I have looked at is that the database results have to be put into an array in order to use json_encode. Am I correct in saying that or is it just a coincidence that every example I looked at did that?
0
Free Tool: IP Lookup
LVL 8
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I've got an AJAX form dynamic happening. Everything is working just like the client wants with the exception of what happens when a user goes to login and nothing is found in the database.

When the user clicks the "submit" button, here's the code that is called:

$('#findPortalUser').click( function(event){
			
			event.preventDefault();
			
			if (validateForm()) {
				$("#verify_form").hide();
				
				var out = {
					'usrDOB' : $('#usrDOB').val(),
					'usrEEID' : $('#usrEEID').val(),
					'cpID' : 574,
					'displayLinks' : $('#displayLinks').val()
					};
					
				$.post('api_bmcjax.php?p=verify&displayLinks=false&linkType=surveyevents', out, function(data)
				{
					$('#window').html(data);
				});
			}
		});

Open in new window


Notice the "$('#verify_form').hide()" command.

If nothing is returned, I need that div to be visible.

How?
0
I'm working on a page that I didn't write and I want to understand what I'm doing and what's happening.

Here's a portion of the code that has me puzzled. I want to explain to you what I comprehend and then ask whoever's willing to fill in the gaps.

$.post('api_woodward.php?p=verify&displayLinks=false&linkType=surveyevents', out, function(data)

This is a JQuery AJAX form function. The first part is the URL the form content is being posted to (woodward.php). The second part, "out" - I've no clue. The last part, function(data) - I'm looking at https://api.jquery.com/jquery.post/ and it seems like this is code to display what happens in the event of a successful form transmission.

As far as "out" is concerned, I think I know what it is, but I want some other eyes on it.

When the content is posted to the api_woodward.php page, "p=verify" steers the content to a specific function on the page. Within that function, there's another piece of syntax that kicks into gear based on the linkType being "surveyevents." If that's the case, you have this:

        if ($linkType == 'surveyevents') {
            $result['usrID'] = encryptVals($result['usrID']);
            $out .= <<<OUT
				<script>
				$('#verifyUseryes').click(function($event){		
					//event.preventDefault();
					$.post('api_woodard.php?p=d11', {'ui':'{$result['usrID']}', 'ei':'{$result['empID']}'}, function(data){
						$('#window').html(data);
					});
				});
				

Open in new window

0
My sample site URL : My working Site URL

I am trying to find a solution that will allow me to plot the GPS coordinates of many moving objects "live" on a Google Map.

The GPS coordinates of each object will constantly be updating into a MySQL database, and I'd like to know whether it is possible to read each updated coordinate, maybe once every couple of seconds, and re-plot the marker coordinates on the Google Map, without the user having to refresh the page.  Can this be done,?

would it also be possible to make each marker different, and each marker clickable to get more information on the particular object?

My map based on Jack Dougherty's FusionTable-Map-2-layers Template and running nicely on my hostgater server.

I have Traccar Open Source GPS Tracking Platform hosted with Amazone AWS and able to get tracker data to the mysql database, this database update every 30 second with live tracker data

# my db name “newTraccar” & all tracker data update for table `positions`

// -------------- Table structure for table `positions` ---------------------//

CREATE TABLE IF NOT EXISTS `positions` (
  `id` bigint(20) NOT NULL,
  `address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `altitude` double DEFAULT NULL,
  `course` double DEFAULT NULL,
  `latitude` double DEFAULT NULL,
  `longitude` double DEFAULT NULL,
  `other` 

Open in new window

0
// Cotroller
[HttpPut]
        public HttpResponseMessage Put([FromUri]string oldPwd, [FromBody]Hotel_Login Hotel_Login)
        {
            using (Hotel_ShowEntities entities = new Hotel_ShowEntities())
            {
                try
                {
                    var entity = entities.Hotel_Login.FirstOrDefault(e => e.Password == oldPwd);
                    if (entity == null)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Customer with that Password=" + oldPwd.ToString() + "not found");

                    }
                    else
                    {
                        entity.Password = Hotel_Login.Password;
                        entities.SaveChanges();
                        return Request.CreateResponse(HttpStatusCode.OK, entity);
                    }
                }
                catch (Exception ex)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
                }
            }

        }

//Ajax call

 $(document).ready(function () {
                $("#btnSubmit").click(function () {
                    var CurrentPwd = $("#CurrPwd").val();
                    var Newpwd = $("#NewPwd").val();
                    console.log(Newpwd);
                    $.ajax({
                        type: "Put",
                        url: "http://localhost:16580/api/ChangeForgetPass/Put?oldPwd=" +…
0
Hello,
I am trying to add a header and tabs with info about the XML data file to .xml file in SAS code. How exactly this can be done? Please see what I have currently I have for my SAS code. I can see the XML data file as my output but the Header (tab and tab2) with all info about the XML file does not show up yet in the XML file.
 
libname xmldir xmlv2 '/basepath/examples/XMLData.xml' xmltype=generic;

/* Req. 1: Macro variables to provide appropriate tab spacing. */
%let tab="    ";
%let tab2="        ";

/* Req. 2: XML file information and header*/
data _null_;
   file xmldir;
  
    put '<?xml version="1.0" encoding="UTF-8"?>';
    put '<Schema Name>';
    put &tab. '<Header>';
    put &tab2. '<SampleDate>2017-06-14</SampleDate>';
    put &tab2. '<CaseCount>30</CaseCount>';
    put &tab2. '<Action>Initial</Action>';
    put &tab2. '<YearPeriod>2017</YearPeriod>';
    put &tab. '</Header>';
    put &tab. '<Payload>';
run;

/* Req. 3: Writing two SAS datsets to xmldir library and creating XMLData.xml data file*/ 
data xmldir.dataname1(label="dataset name1 from sashelp library");
       set sashelp.dataset1(obs=10);
run;

data xmldir.dataname2(label="dataset name2 from sashelp library");
       set sashelp.dataset2(obs=20 keep=var1 var2); 
run; 

libname xmldir clear;

/* Req. 4: XML File End*/
data _null_;
   file xmldir mod;

    put &tab'<Payload>';
    put '</Schema Name>';
run;

Open in new window


So, currently only Req. 3 is working.
Any comments or suggestions will be greatly appreciated!
0
I have an asp.net application in which i'm uploading file into the database. In Aspx i have a Updateprogress with Postbacktrigger in UpdatePanel. It is working fine when i remove my Localhost from the Compatibility View in IE11 but when i add localhost in compatibility view UpdateProgress does not appear.

i'm also using Following JavaScript Function to make Updateprogress appear:

<script type="text/javascript">
        window.onsubmit = function () {

            var updateProgress = $find("<%= UpdateProgress1.ClientID %>");
            window.setTimeout(function () {
                updateProgress.set_visible(true);
            }, 100);

        }
    </script>
0
Hello experts,

I am trying to call the ajax function only if there are values in 'stepname' and 'altmethod' else show and alert. When I include the following code, the else part gets executed all the time though there are no values. Could anyone kindly help me with this.

$(document).on("click", '#nextstep', function(e) {

    e.preventDefault();
 var stepname = $('#stepname').val(); 
 var chosen_altmethod = $('#chosen_altmethod').val();
 var altmethod = $('#altmethodname').val();

 
var formData = new FormData();
formData.append('stepname',stepname);
formData.append('altmethod',altmethod);
formData.append('chosen_altmethod',chosen_altmethod);
 formData.append('action','nextstep');

 console.log(stepname,"stepname");
console.log(altmethod, "altmethod");
console.log(chosen_altmethod,"chosen_altmethod");

if((stepname=="undefined") && (altmethodname=="undefined")){
  alert('please choose a step');
}else{
        $.ajax({
             type: 'POST',
            url: "<?= base_url() ?>index.php/variants/fetchstep1/",
             data: formData,
             processData: false,
      contentType: false,
             success: function (data) {

   $("#steplist").remove();
 $("#replacelist").html(data);
   $('html, body').animate({ scrollTop: 0 }, 0);
             }
         });
}
     });

Open in new window


Thank you in advance
0
Hi,
Using these codes

        public static List<HouseData> GetHouseList()
        {
            List<HouseData> houseList = new List<HouseData>();
            using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn3"].ConnectionString))
            {
                using (SqlCommand sqlCmd = new SqlCommand("SELECT house_name, address1, address2, price, price_curr, raised_by_user_id FROM house_tab", sqlConn))
                {
                    sqlConn.Open();
                    sqlCmd.CommandType = CommandType.Text;
                    SqlDataAdapter sqlAd = new SqlDataAdapter(sqlCmd);
                    DataTable sqlDt = new DataTable();
                    sqlAd.Fill(sqlDt);
                    sqlConn.Close();
                    if (null != sqlDt)
                    {
                        houseList = sqlDt
                                        .AsEnumerable()
                                        .Select(dataRow => new HouseData
                                        {
                                            house_name = dataRow.Field<string>("house_name"),
                                            address1 = dataRow.Field<string>("address1"),
                                            address2 = dataRow.Field<string>("address2"),
                                            price = dataRow.Field<decimal>("price"),
                                            price_curr = 

Open in new window

0
I am trying to validate using remote options, but it is always validate as failed
<div class="row">
										<div class="col-sm-12 col-xs-12">
											<input type="text" name="userName" placeholder="Username" class="form-control input-lg" required="required" data-bv-remote="true"/>
										</div>
									</div>

Open in new window

 userName: {
                message: 'The username is not valid',
                validators: {
                    notEmpty: {
                        message: 'The username is required and can\'t be empty'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: 'The username must be more than 6 and less than 30 characters long'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_\.]+$/,
                        message: 'The username can only consist of alphabetical, number, dot and underscore'
                    },

                    remote: {
	                    url: '/includes/website.cfc?method=checkusername',
	                    message: {
	                        en_US:  "This usenrame is already taken, please choose another one",
	                    },
	                    data: {
	                        type: 'userName'
	                    },
	                    type: 'POST',
	                    delay: 1000
	                }


                }
            },

Open in new window

<cffunction name="checkusername" output="true" returntype="any" access="remote" returnformat="JSON" >
          <cfargument name="username" required="true" type="string" />
          <!--- set the default value to false --->
          <cfset var emails = StructNew() />
          <cfset emails.valid = "false" />


          <!--- code to check email in system --->
          <cfquery name="findemail" datasource="#request.datasource#">
               select username
               from users
               where username = <cfqueryparam  value="#arguments.username#" cfsqltype="cf_sql_varchar" />
          </cfquery>
          <cfif findemail.RecordCount eq 0>
               <cfset emails.valid = "true" />
          </cfif>
          <cfoutput>#SerializeJSON(emails)#</cfoutput>
     </cffunction>

Open in new window

0
Independent Software Vendors: We Want Your Opinion
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I have a user form that is created in extjs framework. The user form has many user fields which are being passed as part of request payload to the REST controller. I am trying to add a grid panel(most likely in a tabular format with multiple rows & columns) to the user form. But I am not sure how to pass the grid panel data as part of request payload to the REST controller. I will post more code if any more details are needed. Any help would be appreciated. Thanks.

Ext.define('soylentgreen.view.admin.UserForm', {
    extend : 'Ext.form.Panel',
    alias : 'widget.userform',
    bodyStyle : 'padding:5px 5px 0',

// some userform elements like firstname,lastname, go here.....

name : 'userTeamGrid',
  xtype : 'gridpanel',
id : 'userTeamGrid',
itemId : 'userTeamGrid',
multiSelect : true,
selModel : Ext.create(
        'Ext.selection.CheckboxModel',
        {
          injectCheckbox : 'first',
          mode : 'MULTI',
          checkOnly : false
        }),
anchor : '100%',
width : '700px',
height : 250,
flex : 1,
store : 'userTeamStore',

var user = form.getRecord();
form.updateRecord(user);
user.save({
        callback : function(records, operation){
          //reset the (static) proxy extraParams object
          user.getProxy().extraParams =  {
            requestType: 'standard'
          }
          if(!operation.wasSuccessful()){
            var error = operation.getError();
0
Having a problem with getting fn2 to fire after fn1.  I am sure it is because the google call is asynchronous but not sure how to resolve.

Sample here

    function fn1(searchMethod, searchValue) {
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?' + searchMethod + '=' + searchValue + '&key=someGoogleKey',
            dataType: 'json',
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            },
            success: function(googleData, searchMethod) {
                alert('google done');
                console.log(googleData);
            }

        }).done(function(locData) {
            dfd.resolve();
        });
    }

    function fn2() {
        alert('second function')
    }

    var dfd = $.Deferred();
   
    (function() {
        //function one passes 2 parameters
        //in this case address telling to search for the New York ZIP 12345
        $.when(fn1('address', '12345')).done(function() {
            fn2();
        });

    })();
0
In my wordpress site, Ajax Load more plugin is not working for the specific page. Itz working in some of the pages. But not working in the rest of the pages. Below are the urls that can give you a clear description.
Working Page : "http://www.stockimagesafrica.com/people"
And not working in http://www.stockimagesafrica.com/downloads/category/southern-africa/
0
hi , i'm working on a web application (a platform for conferences in a company )
i want to integrate a video chat system inside this website . that's mean that any one registered on the site can have an online chat with somebody else (registered also )
any suggessions please
0
Hello All;

OK, this is code that I found a while back, and posted here.
ASP Classic - Insert text, Line breaks and Code

The issue that I had, or am still having now, is that I am giving the user the option to choose the tags they want to use.
They can have as many tags as they need in their post.

The issue with the code in the link above is that it will only do one tag hard coded.
So, that I have done is added an REGGEX into it, and it works GREAT! for the highlighting,
However, adding this in, has messed up the main function of this code FUNCTION, and that is.
It adds the line breaks to everything OUTSIDE of the Code tags.

The REGGEX that I used and works is this.

Function Reggex(strString, strPattern, strReplace)

	Dim RE: Set RE = New RegExp

	With RE
		.Pattern = strPattern
		.Global = True
		.IgnoreCase = True
		Reggex = .Replace(strString, strReplace)
	End With
	
End Function

fString =   Reggex(fString, "\[code=(.*?)\](.*?)\[\/code=(.*?)\]", "<pre class=""line-numbers"" id=""code""><code class=""language-$1 demo"">$2</code></pre id=""code"">")

Open in new window


The original code is this. (Modified to work in my project)

 	CodeTags(1,1,1) = "[ code=sql]" ' Remove the space between the bracket, 
 	CodeTags(1,2,1) = "[/ code=sql]" ' Remove the space between the bracket, 
 	CodeTags(1,1,2) = "<pre class=""line-numbers"" id=""code""><code class=""language-sql demo"">"
 	CodeTags(1,2,2) = "</code></pre id=""code"">"

Open in new window


This is the entire script.


Open in new window

0
Hi ,

I am using masterpage and masterpage is having Ajax ModalPopupExtender Control. Also page uses Frames. ModalPopup shows always in the top frame and top frame is greyed out. Bottom frame is not greyed out. how to to show modalpopup window in the center of the page and both frames are greyed out.

Masterpage.aspx
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="AdminMasterPage.master.cs" Inherits="CoreTeamFeedback.Administration.MasterPage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

   <asp:ContentPlaceHolder id="head" runat="server">
   </asp:ContentPlaceHolder>
<style>
 .modalBackground

    {
        background-color: #cccccc;
        filter: alpha(opacity=50);
        opacity: 0.6;
    }

    .modalPopup
    {
        background-color: #FFFFFF;
        width: 300px;
        border: 3px solid #507F70;
        border-radius: 12px;
        padding:0
    }

    .modalPopup .header
    {
        background-color: #285C4D;
        height: 30px;
        color: White;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        border-top-left-radius: 6px;
        border-top-right-radius: 6px;
        font-family:Verdana;
        font-size:8pt;
    }

    .modalPopup .body
    {
  

Open in new window

0
I have created a bootstrap popup login page . When the client click on the login button it will launch the popup and the client will be asked to either login or register. Once login button is clicked I need to validate the credentials and log them in. If the login is not successful I Need to keep them on the same page and show the error message.

Also   I have 2 options forgot user name and forgot password I need to incorporate that within the same popup so it slides and another form is shown
<li class="login-link"><a href="#" data-toggle="modal" data-target="#myModal">Login</a></li>

<div id="myModal" class="modal fade" role="dialog">
			<div class="modal-dialog">
			    <!-- Modal content-->
			    <div class="modal-content">
			    	<div class="modal-header">
			        	<button type="button" class="close" data-dismiss="modal">&times;</button>
						<h2 class="modal-title">Account Login</h2>
			    	</div>
					<div class="modal-body">
						 <form data-toggle="validator" role="form">
			        	<h3>Welcome to I Drive Smart. Please log-in to access your account.</h3>
			        	<div class="form-group">
			        		<input class="modal-username" type="text" name="firstname" class="form-control" data-error="Please enter name field." placeholder="Username" required="required">
			        			<div class="help-block with-errors"></div>
			        	</div>
			        	<div class="form-group">
			        		<input class="modal-password" type="password" 

Open in new window

0
Hi,

I am hoping someone can help me with an issue I am having whilst using Jquery and Classic ASP.

This code works perfectly..


  <script type="text/javascript">

    $(document).ready(function() {
             $('ul.sf-menu').sooperfish();
    });

</script>


BUT as soon as I add in the code for my ajax form submit it does not work..


  <script type="text/javascript">
    $(document).ready(function() {
       
        
         $('#submitButton').click(function() {
    $.ajax({
            type: "POST",
            url: "test.asp",
            data:  $("#form1").serialize(),
            cache: false,
            dataType: "html",
            success: function(responseText){
                alert(responseText);
            },
            error: function(resposeText){
                alert(resposeText);
            },
        });

    return false;
});

        
             $('ul.sf-menu').sooperfish();
 
    });
0
I"m starting in the shallow end of the pool here and trying to work my way into some more complicated / practical usages of AJAX.

I'm using this as a starting point (W3 Schools [https://www.w3schools.com/jquery/jquery_ajax_load.asp]):

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt");
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

Open in new window


Because of the project I'm working on, I wanted to take this same example, but use a <select> to trigger the code.

I tried this:

<select onchange="selectFunction()">
<option></option>
<option>change text</option>
</select>

...with the new Javascript being:

function(selectFunction() {
$("#div1").load("demo_text.txt");
}

It worked, but only if I put the JavaScript code at the bottom of the page. Prior to that I was getting an error that said "selectFunction is undefined."

Here's the code:

<html>
<head>
<title>Health Summary</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<style>
 
body {
font-family: Arial, Helvetica;
font-size:12pt;  
 
 }

</style>
</head>

<script>
$(document).ready(function() {

function selectFunction() {
$("#div1").load("demo_text.txt");
}
});
</script>

<html>

<body>

<div id="div1">and...</div>
<br><br>
<select id="mySelect" onchange="selectFunction()">
<option></option>
<option>change text</option>
</select>

</body>

<html>

Open in new window


Based on my limited understanding of JavaScript, it's not uncommon to get these types of errors if the script goes looking for an id or a div and the page hasn't completed loading yet. THAT is why I get the error that says "selectFunction is undefined."

On the other hand, if I code it like this:

$("#mySelect").change.function(){
$("#div1").load("demo_text.txt");
});

...it works just fine.

The reason - and tell me if I'm accurate - is because when you code it that way, you're now using the XMLHttpRequestObject and benefiting from the AJAX dynamic. Beforehand, you were simply coding it using JavaScript and things were getting lost prior to the page being loaded.

Correct?
0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I have a javascript function to upload images to my application.  The upload part works perfectly.  The problem is that when it returns it wants to refresh the whole page.  Here is my code:
    function SavePhoto(pid) {
        var form = $('#frmPost');
        var file;
        var pid;

        // read the file inputs and stop at the first one found.
        var inputs = $("input:file");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type.toLowerCase() == 'file') {
                if (inputs[i].files.length > 0) {
                    file = inputs[i].files[0];
                    break;
                }
            }
        }

        if (!file) {
            return;
        }

        // create the formdate object and append items to it.
        var fd = new FormData(form);
        fd.append("file", file);
        fd.append("pid", pid);

        $.ajax({
            type: "POST",
            url: '/Residents/UploadFile/' + pid,
            contentType: false,
            data: fd,
            processData: false,
            success: function (data) {
                //$('#divPets').load('/Residents/GetPets/' + RID);
                //alert(data);
            }
        });

    }

Open in new window


How do I keep the whole page from reloading?  I just want the div that holds the image to update.
0
Oh the wonderful MVC world....

I am trying to setup a timeout script for my website. Currently it seems to work but if the user wanted to extend the timeout time then move to another page it seems to have lost all of my session varibles I had saved.

FilterConfig.cs code:
public class IsAuthenticatedAttribute : ActionFilterAttribute  
    {  
        public override void OnActionExecuting(ActionExecutingContext filterContext)  
        {  
            if (rowCnt >= 1) //Making sure user has permissions to even view this site  
            {  
                System.Diagnostics.Debug.WriteLine("Current timeout: " + HttpContext.Current.Session.Timeout);  
                System.Diagnostics.Debug.WriteLine("Session timeout: " + HttpContext.Current.Session["timeoutDate"]);  
  
                if (HttpContext.Current.Session.Timeout == 20) //20 is the default timeout setting  
                {  
                    //It's the first time the user has visited the page so set timeout!  
                    filterContext.HttpContext.Session.Clear();  
                    filterContext.HttpContext.Session.RemoveAll();  
  
                    HttpContext.Current.Session.Timeout = 1;  
                    HttpContext.Current.Session["sessionVars"] = new initSessionVars().getSVars;  
                    sessionVars sVars = HttpContext.Current.Session["sessionVars"] as sessionVars;  
  
                    //Send them to the main page in order to populate the sessions and 

Open in new window

0
I have a strongly typed view with a drop down list(see sample below).
 I populate the name/value list for the dropdown with an ajax call which produces following html. also, say the user can select multiple items in the dropdown.

Now if i want to pass the selected value back to controller via
1. mvc post -
   Question -  is there a way to bind the selected userids, to the model using try update model. in the controller. or do i have to pass the
    List<int> userids as a parameter in the controller function.

2. ajax call
    Question - if i want to call a controller function with selected value ids, how would i send that to controller.

//HTML
<select id="x.UserIds" name="x.UserIds" >
   <option value=""></option>
  <option value="1">User 1</option>
  <option value="2">User 2</option>
</select>

//view
@model UserModel
Html.dropdownlistfor(x => x.UserIds)

//Model
public class User {  public List<int> UserIds { get; set; } }

//controller
      public ActionResult Update() {
             TryUpdateModel( model,  new string[] { "UserIds" });      
      }
0
jQuery('.progress', form).css('width', '0');
jQuery.ajax({

        xhr: function () {

            var xhr = new window.XMLHttpRequest();
            xhr.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    percentComplete = parseInt(percentComplete * 100);
                    jQuery('.progress', form).text(percentComplete + '%');
                    jQuery('.progress', form).css('width', percentComplete + '%');
                }
            }, false);
            return xhr;
        },
        type: 'POST',
        url: badnc_ajax.ajaxurl,
        data: data,
        success: function (data) {
            jQuery("div[id='results']", form).css('display', 'block');
            jQuery("div[id='loading']", form).css('display', 'none');
            jQuery("div[id='results']", form).html(unescape(data));
        }

    });

Open in new window


This code is showing a progress bar when I submit the form. The only problem is progress bar shows after receiving the response.

I mean progress bar shows after displaying the message from PHP file.

I want to show the percent counter increasing and whenever it reaches 100% then show the response.
0
i made used of an ajax calendar in asp.net it was working well until just now where it is distorted.

I check in an old back up and its still working fine there.

i do not recall changing anything

Any idea about what is causing this issue?

Good calendar
good.png
Distorted calendar
bad.png
 <td class="auto-style2"><asp:TextBox ID="txtDateBooking" runat="server" Visible="true"></asp:TextBox><asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDateBooking" OnClientDateSelectionChanged="checkDate" Format="dd-MM-yy"></asp:CalendarExtender>

              <%--  <asp:CompareValidator ID="cfvDOB" ControlToValidate="txtDateBooking" Type="Date" Operator="LessThan"
                            ErrorMessage="(DoB cannot be within the last 18 years)" Display="Dynamic" SkinID="fielderror"
                            runat="server"></asp:CompareValidator>--%>
                    <script type="text/javascript">

                        function checkDate(sender, args) {
                            if (sender._selectedDate < new Date()) {
                                alert("You cannot select a day earlier than today!");
                                sender._selectedDate = new Date();
                                // set the date back to the current date
                                sender._textbox.set_Value(sender._selectedDate.format(sender._format))
                            }
                        }
    </script></td>

Open in new window

0
Hi, I am having a compatiblity issue with javascript "onclick" event. I think it has something to do with page load, but I can not put my fingur on it. It is working in a PC and android tablet or ipad, but not in adnroid phone nore in iphone. Could you please help.

<a class="btn btn-success fa fa-play" id="btnList"  href="#" target="_top" title="GoToListPage"></a>

<script type="text/javascript">
document.getElementById("btnList").onclick = function() {
location.href = "list.php";
};
</script>
0

AJAX

12K

Solutions

13

Articles & Videos

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.