AJAX

12K

Solutions

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

I have a form that posts via javascript / jquery / ajax

I am trying to validate some fields server side before actual submission I was doing this to set the variable

myVar=$('#myVarFormID').val();

Open in new window


when I check the console, my variable is set appropriately and shows as intended, but when I go like this after setting it
nextFunction(myVar);

Open in new window


The function thinks the variable is [htmlInputElement]

I dont understand why the output shows fine but the script function wont take it in.  Is there something extra I need to do to pass this form element into a different function?
0
Free Tool: ZipGrep
LVL 9
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Hi

In my call to API using AJAX, I get the response in HTTP Status code as shown below.

response.png
In my code, when I get any status code that starts with 4 it goes into error function. Is there a way in error function to identify the value sent back in response? So that, i can display different error message for different status code.

I did try adding this below code,

          statusCode: {
            202: function() {
              $formRoot.find('.form-validation .message').html(successMsg);
              $formRoot.find('.email-link-form').hide();
              $formRoot.find('.form-validation').show();
            },
            429: function() {
              showResult(validationError.tooMany);
           },
            422: function() {
              showResult(validationError.contact);
           },
            404: function() {
              alert ('404 error');
           }
         }

but this doesnt even get called.

any help appreciated.

Thanks.
0
I need to execute an async function for a set of data values.  I thought that the way to go would be to use Promises.  I have some of a sample of using what seems like a framework that I could modify to call my function with.  Here is the "framework". It doesn't run and tell me that Promise is not defined.

Any advise on this would be greatly appreciated.

Here is the "almost working" framework.
<!DOCTYPE html>
<html>

<head>
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" data-semver="3.1.1" data-require="jquery@*"></script>
    
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
      alert('hi');

      $('#btnWait').click(function() {
        doAsync().then(function(response) {
          alert(response);
        });
      });


    });



    // Code goes here
    function timeoutPromise(time, s) {
      return new Promise(function(resolve) {
        setTimeout(function() {
          resolve(Date.now() + " " + s);
        }, time);
      });
    }

    function doSomethingAsync(a, p) {
      return timeoutPromise(a, p);
    }

    function doSomethingElseAsync(b, p) {
      return timeoutPromise(b, p);
    }

    function doMoreAsnycStuff(c, p) {
      return timeoutPromise(c, p);
    }


    function doAsync() {
      try {
      
        //var promises = [doSomethingAsync(1000), doSomethingElseAsync(2000), 

Open in new window

0
Any idea how to fire the onfocus event of the Ajax toolkit HtmlEditorExtender?
I need to show hide the toolbar when I focus  on the editor.
I tried
 $("#HtmlEditorExtender2").focus(function () {
                    alert("Focused");
                });

Open in new window

but it did not work..
0
POST 500 Internal Server ErrorProblem :
This is what I want :
When the link “Register” i.e “1” is clicked, a modal window opens. Therein after filling all the details and after pressing button “Signup” i.e “2” all data should be saved into database and the place where “Please wait…” is shown, it should show “Done” which will happen only when the process completed successfully
This is what’s happening :
After all the required details are filled and when the “Signup” button is clicked, a message is flashed on the screen showing “Something is wrong”. After through checking I came to the conclusion that “ajax part is not working”.  The same code is working perfectly on my localhost ie on my system but after uploading it is showing error : " 500 Internal Server Error". Code is shown below :
						<div class="modal-footer form-group">
							<div class="col-xs-8">
								<div id="regmesg" class="supmsg pull-left"></div>
							</div>
							<div class="col-xs-4">
								<button class="btn btn-default" data-dismiss="modal">Close</button>
								<button type="button" id="btnmodsignup" class="btn btn-primary" onclick="InsSignup()">Signup</button>
							</div>
						</div>

Open in new window

Code of InsSignup() function :
			function InsSignup(){	// Sign up Button 
				alert("1");
				$('#cboxtc').prop("checked", false);
				$('#btnmodsignup').attr("disabled", "disabled");
				$('#regmesg').html('Please wait....');
				alert("2");
				var catg = $.trim($('#catgddl').val()); 

Open in new window

0
I have an application which allows users to drag & drop files to a zone which is working well.  The problem is I want the form data to be sent to a WEB API 2 controller and I can't work out how to do this.

.NET:
        public void Upload(HttpPostedFileBase file)
        {
//Just a point to debug
            var test = "test";
        }

Open in new window


JS:
function UploadFiles() {
    var formData = new FormData();
    formData.append("file", viewModel.FilesToUpload()[0], 'test.jpg');
    
    $.post("/api/ApiDocument/Upload", formData)
                    .done(function (data) {
                        alert('done');
                    })
                    .fail(function (e) {
                        alert('fail');
                    });
}

Open in new window


Form:
upload.png
0
I have a web part page displaying 5 web parts. Four of the web parts (Efforts, Phases, Capture Points & Areas) are "provider" web parts, and come from lists that are the sources of 4 lookup columns in the 5th "consumer" web part (Lessons Learned).

The provider web parts are displaying the Title column from the lists.

The Using Javascript/jQuery, I "connected" the 4 provider web parts to the consumer web part, such that when you click on a Title column value, the consumer web part is filtered to show only those records that have the clicked value in the relevant metadata column.

All that is working very nicely.

Now, my requirement is to go one step further, and display the number of items that will be displayed if you click on a Title column value in any of the 4 web parts. If there are none, a "0" should be displayed.

I've constructed a lists service query that successfully returns the number of items that exist for a given, hard-coded, metadata value:
[SiteURL]/_vti_bin/listdata.svc/[ListName]/$count?&$filter=Effort/Title eq 'AAA'

So, the goal is to display such an item count beside the corresponding provider web part value, such as:
Efforts web part:
AAA (10) //assuming there are 10 items in the consumer web part tagged with Effort 'AAA'

Now, I'm bumping up against the current limit of my abilities.

I know that I need code (javascript, rest, ajax, json) for each provider web part with looping to cycle through all of the TD cells that have …
0
Im working with ajax toolkit tabs it is working properly but when i am adding bootstrap css files the tabs css  overwrite
Can u Help me to SOlve this problem?
Thanks in advance
0
in my partial view, I have used some jquery code for submitting my form.but I got this error.
The required anti-forgery form field"__RequestVerificationToken"
is not present. as you see I have added @Html.AntiForgeryToken() in my partial view and as well I have added [ValidateAntiForgeryToken] on my controller. but I got the error again.I have read all of the questions on the internet but they couldn't help me.

@model Dentistry.Areas.ViewModels.UserViewModel

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
    </button>
    <h4 class="modal-title custom_align" id="Heading">ویرایش کاربران</h4>

</div>

@if (Model != null && Model.UserId != string.Empty)
{
    <div class="modal-body" id="editModal">
        <form id="#myForm">
          @Html.AntiForgeryToken()
            <div class="form-group">
                @Html.HiddenFor(a => a.UserId)
            </div>
            <div class="form-group">
                <label>نام کاربری</label>
                @Html.TextBoxFor(a => a.UserName, new { @class = "form-control" })
                @Html.ValidationMessageFor(a => a.UserName)
            </div>
            <div class="form-group">
                <label>نام</label>
                @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
                @Html.ValidationMessageFor(a => a.FirstName)
          

Open in new window

0
Hi,
I am making a http patch request using an  ajax call on chrome to url - https://api.github.com/repos/owner...
My page url is localhost:8080.
This call is failing. In the network tab i see an option request being made in red.
I read some places that patch request that  is cross origin will be preflighted.
Which i think means that it will be first checked with github that patch is allowed in cross origin.
But github docs says its open to cross origin request.
How do i achieve my goal ?
Also please mention some good video or articles on cross origin / preflight etc.

Thanks
0
Free Tool: Port Scanner
LVL 9
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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 actually been able to get this working on the editor in pages and posts using the code below. But haven't been able to get it to work for the new editor added to text widgets. I read that wordpress is using jQuery now for those text widgets, but even trying this without a hook, just adding the script sitewide to test doesn't work:

<script type="text/javascript">
jQuery( document ).on( 'tinymce-editor-setup', function( event, editor ) {
    if ( editor.settings.toolbar1 && -1 === editor.settings.toolbar1.indexOf( 'blockquote' ) ) {
        editor.settings.toolbar1 += ',blockquote';
    }
});
</script>

Open in new window


I tried that just to see if the new method wordpress says you can use to add more buttons would even affect the editor in the text widget, but it doesn't even add the blockquote icon as expected. So of course I can't poke around to try to figure out what would target the link option.

This is the code that does work for the editor in pages and posts:
<?php
function newtablink()
{
 ?>
<script type="text/javascript">
    jQuery(function () {
       jQuery('input#wp-link-target').prop('checked',true);
    });
</script>  
<?php
}

add_action( 'before_wp_tiny_mce', 'newtablink' );
?>

Open in new window


Anyone have any thoughts or suggestions on how to go about this for the widget? Below is a screenshot for a visual of where and what I'm trying to work with.
(If you wonder why we want to do this: we have some sites that have more external links than internal. So we want the people adding or editing content or widgets to be able to just enter the url without having to open in extra settings box. We don't want to add a plugin that automatically tries to auto add the target="_blank" as pages render because we want to still have individual control. Some of the people editing have very limited skills, so we want to try to simplify anything we can for some of the sites.)

Screenshot of the box that opens when adding a link in the editor.
0
Hello,

I have piece of code here. I am trying to create something like a quiz application. In  <h4>Add question</h4> part, I can add a question if I want to and I store all the details I entered into the database by making an ajax call. Upon success, this piece of code gets replaced by the same code with other data so that the user can enter all the details. What I am trying to do is once I add a question in 'Add question' part, then I should be able to display it throughout the quiz. How can I do a post for new_questions in ajax and send it to the controller?

Can anyone suggest me how to do proceed with this?

Any kind of suggestion would be helpful.
   
<?php
foreach($substeps as $row) {
 ?>
 <div id='img_div'>
      <h2 id="stepslist_<?php echo $row->stepid;?>" class="step"><p><?php echo $row->stepname;?></p></h2>
      <img src='http://localhost/project/uploads/<?php echo $row->image; ?>'>
</div>
<?php } ?>
 <?php
      foreach($questions as $each){
      ?><br><br>
      <input type="text" name="questions[]" class='form-control' id="questions_<?php echo $each->questionid; ?>"  value="<?php echo $each->questionname; ?>" disabled/><br/>
   
    <h4>Add question</h4>
    <input type="text" class="form-control" name="newquestion[]"  id="new_questions_<?php echo $each->questionid; ?>" /><br>
    <h4>Answer:</h4>  <select class="form-control" name="answer[]" id="answer" required>
 <option value="">Select</option>
 <option value="no">no</option>
 <option 

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
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
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
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
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
<script>
  function myFunction() {
     var query = '?';
     var str = $("form").serialize();
     $("#results").text(query += str);
     var x = $("#results").text();
     return x;
 }
  $( "input[type='sel'], input[type='text']").on( "click", myFunction);
  $( "select" ).on( "change", myFunction);

  //window.alert(myFunction());
 //query += '&' + value + '=' +  value +'.value';
 var jsonString = JSON.stringify(myFunction());
 console.log(jsonString);
 $.ajax({
    url: 'insert_value.php',
    data: jsonString,
    
    contentType: 'application/json; charset=utf-8',
    type: 'POST',
  }).done(function(resp) {
    $('#result').html(resp)
  });
  
</script> 
    

Open in new window




This is not showing values on the console only "?Gender=Male&id=" after editing values on the controls it is not changing values and giving above message on the console it giving something like this   [Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.
0
On Demand Webinar: Networking for the Cloud Era
LVL 9
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

we are generating dynamic controls like dropdown and textboxes so how we need to get data and assign those values to array and creating query string and pass that to one variale using ajax
please let me know the answer for this question
dyn_html.php
0
Hello,

I have spent about 10 hours trying to figure this out.

So this form worked on another server 2 days ago, I moved it to a new server and now the form will not submit. I tried to look if there were any errors but no errors are recorded.

I am afraid that I don't have the correct tools, can someone that is familiar with js take a look and see if they see where the error is being reported, I am assuming there is a way to check it in the browser.

http://tinyurl.com/mux3tml

Thanks!
0
JS on child page:
GetRadWindow().BrowserWindow.refreshGrid(args); ---Does not refresh the grid on the master page.

vb on child page:
 Protected Sub DetailsView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsView1.ItemCommand
        If (e.CommandName = "Update") Then
            ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind();", True)
        ElseIf (e.CommandName = "Insert") Then
            ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", True)
        Else
            ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CancelEdit();", True)
        End If

    End Sub

Open in new window

0
Dear All,
I have a textbox in a asp.net web page .
When the user click inside the textbox I need to open a panel that contain 3 textboxes and a confirm button.
the user will then b able to write in these 3 textboxes(with jquery autocomplete) and I will concatenate the strings to a final string in the parent textbox.
I tried to use a ajaxtoolkit:PopupControlExtender and it did the trick but it will close every time the user select an option from the autocomplete. Any Idea how to keep this popup opened after selection done and close it only when confirm button click?
0
ColdFusion CFSelect will not bind and return the Selected Value in ColdFusion 11.... It works fine in ColdFusion 8 and 9, but when put on CF11 it will not work

Here is the code.

<cfselect name="Field1" id="Field1" value="" bind="cfc:cfc_Field1DrillDown.lookupField1({Field1Desc},'#vField1Category#')" bindonload="YES" />

The CFC:

<cfcomponent output="false">
      
      <!--- Lookup used for auto suggest --->
      <cffunction name="lookupField1" access="remote" returntype="array">
            <cfargument name="vField1Desc" type="string" required="true">
            <cfargument name="vField1Category" type="string" default="" required="false">
            <!--- Define variables --->
          <cfset var data="">
          <cfset var result=ArrayNew(2)>
          <cfset var i=0>
            
            <!--- Do search --->
            <cfquery datasource="#Request.FieldDSN#" name="data">
                  SELECT QueryFieldID, QueryField
                  FROM FieldNames
                  WHERE (SICDefinitionID = '#ARGUMENTS.vField1Desc#')
                  ORDER BY QueryField
            </cfquery>
            
            <cfif data.recordcount IS 1>
                    <cfset result[1][1]=data.QueryFieldID>
                      <cfset result[1][2]=data.QueryField>
                        <cfset result[1][3]=IIF(ARGUMENTS.vField1Category eq data.QueryFieldID,DE(true),DE(false))>
            <cfelse>
                  <cfset result[1][1]="N/A">
                <cfset result[1][2]="">
                  <cfloop index="i" from="1" to="#data.RecordCount#">
                    <cfset result[i+1][1]=data.QueryFieldID[i]>
                        <cfset result[i+1][2]=data.QueryField[i]>
                        <cfset …
0
When a site is  using jquery/XMLhttp requests we were able to get active ajax calls in the back end using "jQuery.active".
But when a site is using Aurelia fetch for ajax calls(Fetch complete: POST), how to get number of active fetch calls in the back end?
0

AJAX

12K

Solutions

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.