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 the following ajax codes, and want to send Json data to MVC Controller.
Can you show me how to do that  on MVC Controller?
Thanks

function Submit(domain) {
    //alert("Thank You");
    var x = $('#formdiv *').serializeArray();      
    var data = {};
   $.each(x, function (i, field) {
        data[field.name] = field.value;
   });
    var json = JSON.stringify(data);   
    alert(json);
    $(document).ready(function () {
        $.ajax({
            url: domain + "/Api/ReceiveJson",
            type: "POST",
            data: {json},
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (data) {alert('Success');},
            error: function (msg) { alert(msg); }
        });
    });
    return false;
}

Open in new window

0
Why Diversity in Tech Matters
LVL 13
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Hi Guys,

We are having an issue with trying to connect to a 3rd party application from our website

We  have tried sending requests to the Azpiral sandbox server using Ajax GET and POST methods but i am getting a CORS error access control allow origin not present. CORS is installed on our domain https://ohehirsstudents.ie/.
Azpiral sandbox url for testing: http://sandbox.azpiral.com/PBPartnerWS/PBPtnrServices_1_11.asmx
WSDL file and docs are present in the attached Sligo IT zip file.

I can provide if really nescessary, i have spoke to their support and they are telling me that they hav enever seen an issue like this
0
Hi Experts

My client has Google Analysts for 2 primary domains, and I have a custom carts in other sub domains.

How do I go about and send purchase info to Google Analytics? Do I need to setup the Product IDs within Google? And, is this even possible considering I'm using sub domains.

The intention is to keep the existing code.
0
Client has asked me to provide some idea about how to duplicate the http://playspent.org/ gamification system.

If someone knows of a system like this in the wild which might be used to duplicate a similar site, let me know.

Something beyond simple systems like https://github.com/mulhoon/score.js providing layout of badges + count accumulation buckets in a response style system.

Maybe some sort of bolt onto score.js using SVG graphics for presentation.

Thanks.
1
I need to create dynamic Google Charts which gets the data from a DB stored procedure. I have managed to spit out the actual table with the function below.
var ajax = new XMLHttpRequest();
            var method = "GET";
            var url = "data.php";
            var asynchronous = true;
            ajax.open(method, url, asynchronous);

            //sending ajax request
            ajax.send();            

            // receiving response from data.php
            ajax.onreadystatechange = function()
            {
                if (this.readyState == 4 && this.status == 200)
                {
                    //converting JSON back to array
                    var dataTable = JSON.parse(this.responseText);
                    console.log(dataTable); // for debugging

                    // html value for <tbody>
                    var html = "";
                    // looping through the data
                    for (var a = 0; a < dataTable.length; a++)
                    {
                        var categoryValue = dataTable[a].Category;
                        var monthJan = dataTable[a].Month1;
                        var monthFeb = dataTable[a].Month2;
                        var monthMar = dataTable[a].Month3;
                        var monthApr = dataTable[a].Month4;
                        var monthMay = dataTable[a].Month5;


                        // appending at HTML
                        html += "<tr>";
                        html += 

Open in new window

0
I'm trying to scrape an ASPX page within the browser using JavaScript. From research, I can see that to traverse through the pages I need to submit forms. Is this possible to do without refreshing the initial page the code is running on? In other words, is this something that can be done within the browser?

I'm using the Artoo library, which has an ajaxSpider() function, which is based on jQuery's Ajax function. I can retrieve other pages from the same domain, but I don't know if it is possible to submit a form with this tool.

For more context I have to post variables such as __EVENTTARGET and __VEIWSTATE.
0
I have the following at the top of my .aspx page:
Response.AddHeader("Access-Control-Allow-Origin" , "*");

Open in new window

When I access the file directly via a browser, I can see the header:

CORS1.jpg
If I access via Ajax, the header is not there, and therefore is blocked:

CORS2.jpgAny ideas?
0
Does any one have some sample code for a BIND in coldfusion?
I'm trying to have my DB update with pulling down an option in a form without a submit button
0
Coldfusion 2016

Why do binds not work?

I have 2 Select boxes, and I'm trying bind the contents of 1 input to the value to another input and it will not work in CF 2016.

It used to do this asynchronously in CF 2010.

Can anyone assist
0
I have the following functions in my Woocomerce child themes functions.php file.
But every time the cart is updated I need to reload the cart page for the functions to run.

How can I execute the functions automatically when the shopping cart is updated?

add_action( 'woocommerce_before_calculate_totals', 'add_custom_weight', 10, 1 );
function add_custom_weight( $cart ) {
    
	if (($_SESSION["kilo_rate"]) && ($_SESSION["cart_items_count"]) > 0 ){
	
	$each_cart_item_weight = ($_SESSION["kilo_rate"]/$_SESSION["cart_items_count"]);
    foreach ( WC()->cart->get_cart() as $cart_item ) {
         //very simplified example - every item in cart will be 100 kg
        $cart_item['data']->set_weight( $each_cart_item_weight );
    }
   
	}
    // print_r( $cart->get_cart_contents_weight() ); // Only for testing (not on checkout page)
}

add_action('woocommerce_cart_contents_weight', 'set_cart_contents_weight');
function set_cart_contents_weight( $weight ) {        
    $weight = $_SESSION["kilo_rate"];    
    return $weight;     
}

add_action('woocommerce_cart_collaterals', 'myprefix_cart_extra_info');
function myprefix_cart_extra_info() {

	echo '<div class="cart-extra-info">';
	echo '<h2>Delivery Information</h2>';
	echo '<p>Weight: '. $_SESSION["kilo_rate"].'Kg (Pallet plus Products)';
	echo '</br> Items in Cart: '.$_SESSION["cart_items_count"];
	echo '</br> Pallet Size - Length '.$_SESSION["max_length_cart"].'m Width '.$_SESSION["max_width_cart"].'m</p>';
	echo 

Open in new window

0
CompTIA Network+
LVL 13
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Javascript and AJAX to validate an Address.  The following is the Script that is used to validate an address withe USPS.  The form passes all of the info and everything works except the SUCCESS AND FAIL messages from the AJAX don't print on screen.  I think I need to use an append, or HTML to make a popup box?  Is there an easy solution here?

<script>
 var asaAddressValidate = function(options){
     
    var self = this;
    self.options = jQuery.extend({
      enabled: true,
      formEl: null,
      formFields: {
         Country: '',
        Address1: '',
        Address2: '',
        City: '',
        State: '',
        Zip: ''
        },
      onResponse: null
    }, options);
     
    
    this.interpolate = function(text, data, parent){
      var reg, tmp = String(text), key;
      for(var i in data){
        key = (parent ? parent+'.' : '') + i;
        if (typeof data[i] == 'object'){
          tmp = self.interpolate(tmp, data[i], key);
        }
        else {
          reg = new RegExp('\#\{'+key+'\}', "g");
          tmp = tmp.replace(reg, String(data[i]).replace(/\$/, '&DS;'));
        }
      }
      return String(tmp).replace(/&DS;/g,'$');
    };
    jQuery(self.options.formEl).submit(function(){
        
      if (!self.options.enabled)
        return true;
      if (typeof self.options.dialogEl == 'undefined'){
        jQuery('body').append('<div style="position:absolute; z-index:1000; top:50%;left:50%; " id="asaAddressValidateDialog" 

Open in new window

0
I need to submit a form prior to running Ajax to ensure the data is committed to the database when the Ajax command runs, how can I do this.

Originally, I thought I could set the focus on the submit button and click it, but this does not run sequentially and thus the Ajax command seemed to execute prior to the form data being committed.  What is the proper way to handle such a situation (save without closing modal and run next command in the sequence)?
0
I want to create a button to email an ASP.NET MVC view. More specifically, I want to send content that is inside a div tag on the view. I have been searching for the past few weeks and am running into roadblocks. The best I came up with is using jquery and ajax. If you need to see the model, I can provide that as well. I'm sure I just screwed up the syntax or am trying to do something jquery and ajax can't do.

Portion of SupplyRequest view:

@model Intranet.Models.Product

@{ViewBag.Title = "Supply Request";}

<div class="col-md-12" id="Envelopes">
    <h2>
        Envelopes
    </h2>

    <p>
        Please enter the quantity and click submit email to send an email to the appropriate purchasing department.
    </p>
    <p>
        <table class="table" id="EnvelopeTable">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>@Html.DropDownList("Products", "Select Products")</td>
                    @*<td><input type=""</td>*@
                </tr>
            </tbody>
        </table>
    </p>
    <div>
        <p>
            <script>
            $(function () {
            //send email button click event
                $(".button").click(function (emailEnvContent) {
                //get the div content
                var divvalue = "<div id=Envelopes>" + $(".div").html() + "</div>";
          

Open in new window

0
AJAX not working.  I'm not sure what I am doing wrong here.  If someone clicks "Bookmark This Page" I am sending an ajax request to store the url that was bookmarked.  Here is what I have but I don't believe I am passing the variable correctly.

<script>
 var urldata = window.location.href;

        $('#bookmark-this-page').click(function () {

            $.ajax({
                url: 'https://URL/js/bookmark.php',
                method: 'post',
                data: urldata,
            }).done(function () {

            });
        });
<?php>
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // turn on exceptions


$url = isset($_POST['data']) ? $_POST['data'] : "";

$date = date('m-d-Y');
//var_dump($url); die();
try {

    $sql = "INSERT INTO bookmark ( date, url) VALUES (:date, :url.);";

    $returns = $db->prepare($sql);

    $returns->execute([
        ':url' => $url,
        ':date' => $date,
    ]);
} catch (exception $e) {
     $e->getMessage();
}

Open in new window

0
I use bootstrap controls with ajax update panel in Modal

if I use the  postback the controls lose the css  , and the dropdownlist the search is disabled

this is the controls befor postback

this is the controls after postback
0
I am trying to build a Url.Action by passing the selected value in my dropdown.  How can I concatenate the url.action in the javascript section of my html file and have the browser recognize it as the relative path?

 url: '@Url.Action(selectedDDValue, "ListManager")' => does not work

var selectedDDValue = $("#SelectedDDLOptions :selected").val();

            $.ajax({
              url: '@Url.Action(selectedDDValue, "ListManager")',
                data: { listManager: selectedDDValue },
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",  
                error: function (err) {
                    alert(err.statusText);
                },
                success: function (result) {
                    var row = '';
                    $("#ddlNameColumn").html(selectedDDText);
                    $("#ddlNumberColumn").html("#");
                    $("#DDLList tbody").empty();

                    $.each(result, function (i) {

                        row += "<tr>" +
                            "<td>" + (i + 1) + "</td>" +
                            "<td style='display: none;'>" + result[i].ID + "</td>" +
                            "<td>" + result[i].Value + "</td>" +
                            "<td><a href='#' class='btn btn-danger btn-sm' onclick='DeleteListItem(\"" + result[i].ID + "\")'><i class='glyphicon glyphicon-trash'></i></a><a href='#' class='btn btn-warning btn-sm' 

Open in new window

0
I'm trying to use jQuery UI's "sortable" with Ajax. I have a test table With the columns ID (the auto-incrementing ID), sampleText (like "test item 1", "test item 2" etc.) and displayOrder which, theoretically, is an integer for the order the item should be displayed in. My code gets the information from the database and loops over it. When I drag and drop or use the up/down arrows, DevTools shows that the appropriate URL is being pinged but the table isn't updating and I'm not getting an alert (that the attempt was successful/there was an error.) This is the code for the page:

<cfquery name="qGetStuffToOrder" datasource="#APPLICATION.ds#">
	SELECT * FROM test_reordering 
	ORDER BY  displayOrder
</cfquery>
<table class="table table-striped">
	<tbody id="tabledivbody">
		<cfoutput query="qGetStuffToOrder">
		<tr class="sectionsid" id="sectionsid_#ID#">
			<td>#sampleText#</td>
			<cfif CurrentRow NEQ recordCount>
				<td><a href="javascript:void(0)" class="movedownlink"> <span class="glyphicon glyphicon-arrow-down">down</span></a></td>
			</cfif>
			<cfif CurrentRow NEQ 1>
				<td><a href="javascript:void(0)" class="moveuplink" > <span class="glyphicon glyphicon-arrow-up">up</span></a></td>
			</cfif>
		</tr>
		</cfoutput>
	</tbody>
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> 
<script>
		 $("#tabledivbody").sortable({
        items: 

Open in new window

0
I used to use a lot of JQUERY AJAX calls in our code, but recently I have been moving to using modern plain Javascript, such as fetch and promises.

A typical API block would look something like this:
$.ajax({
     url: '/piece.json',
     type: "GET",
     dataType: "json",
     success: function (data) {
         alert(data);
     }
});

Open in new window


I want to start writing my API calls using Promises, but I am a little confused, especially when it comes to chaining and error checking.

Could someone show me an example using chained promises that does the following psuedocode?

Example Login Functionality
let username = "john";
let password = "123";

if username doesn't exist
-- doesn't exits
     show message, return false
-- it exists
     check password. Is it correct?
     -- No
         Show error message, return
    -- Yes
         send then on their way to dashboard or something

Open in new window


So I know the basics of Promises, but when it comes to chaining something like that...

I know how to check them individually ( I think I am doing it correctly anyways ):

let getUserName = function(email){
    return new Promise(function(resolve, reject){
        // Apply any logic here, call our API
       //  Mock response
        if(email == "john@gmail.com"){
            resolve("found");
        }

        reject("Not found!");
    });
}

Open in new window


Then I could use my Promise like this, right?

getUserName("john@gmail.com").then((response) => {
    alert("Your username was: " + response);
    }, (e) => {
        // Handle error if we want to. BUT what error???
    alert("Error: " + e);
});

Open in new window


So even here, I am unsure of what error I am trapping. Am I just catching the reject here? Anyways...

Let's say I want to use that Promise, or something similar, but chain it as I described above. How?

Can someone help me with an example of a Promise based login using my psuedocode example code, to help me get going? Seeing it sure would help I think.

Thanks!

John
0
What are your advices and technologies to design a Web portal UI for our customers to be robust, reliable, light and modern?
Note: The web portal will integrate with another Web applictions.
0
Learn Ruby Fundamentals
LVL 13
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Hello Experts!

Please I want the ENTER KEY to perform the same function as the Submit button in the code below.

I've tried this:
$('.chat_message').keypress(function (e) {
	 var key = e.which;
	 if(key == 13)  // the enter key code
	  {
	    var to_user_id = $(this).attr('id');
        var chat_message = $('#chat_message_'+to_user_id).val();
        if (chat_message == ""){
            toastr.error("Your message is empty");
            return false;
         }
        var to_username = $('#to_username_'+to_user_id).val();
        $.ajax({
            url:"../controllers/insert_chat",
            method:"POST",
            data:{to_username:to_username, to_user_id:to_user_id, chat_message:chat_message},
            success:function(data)
            {
                $('#chat_message_'+to_user_id).val('');
                $('#chat_history_'+to_user_id).html(data);
            }
        })
	    return false;  
	  }
	});

Open in new window

Each time I press ENTER KEY, the page reloads and bootstrap modal disappears.

modal_content += '<input name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" placeholder="Type your message here ..." type="text" class="form-control chat_message" autocomplete="off"><span class="input-group-btn"><button name="send_chat" id="'+to_user_id+'" class="btn btn-sm btn-info no-radius send_chat" type="button"><i class="ace-icon fa fa-share"></i>Send</button></span></div></div>';

Open in new window


AJAX:
$(document).on('click', '.send_chat', function(){
        var to_user_id = $(this).attr('id');
        var chat_message = $('#chat_message_'+to_user_id).val();
        if (chat_message == ""){
            toastr.error("Your message is empty");
            return false;
         }
        var to_username = $('#to_username_'+to_user_id).val();
        $.ajax({
            url:"../../insert_chat",
            method:"POST",
            data:{to_username:to_username, to_user_id:to_user_id, chat_message:chat_message},
            success:function(data)
            {
                $('#chat_message_'+to_user_id).val('');
                $('#chat_history_'+to_user_id).html(data);
            }
        })
    });

Open in new window

0
Actually, Iam new to JQuery. I have a question that when we click the button. it doesn't go to that demo_test.txt file.Actually i had created demo_test.txt file locally.But for button click event the control doesn't went to there.
could you please help in regarding this.


<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "demo_test.txt", success: function (result) {
                        $("#div1").html(result);
                    }
                });
            });
        });
    </script>
   
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

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

    <button>Get External Content</button>
</body>
</html>
1
Hello Experts!

I need help on how to effectively upload image to the folder and insert the directory in MySQL Database.

I've tried in many ways. I was able to upload and insert but I don't like the way my code is handling it. I couldn't validate the image properly. I don't know how.

I tried the following but no response:

my html form (modal):
<div class="modal fade" id="modal-media">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Profile Picture</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
            </div>
            <form id="profilePic" action="user_img_controller.php" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="col-md-12 text-center">
                        <img class="img-circle hs-img-disp profile-image" src="../assets/img/no-photo-3.png" alt="Profile Picture">
                        <div id="updateError"></div>
                        <input type="file" name="fileToUpload" id="fileToUpload" class="profile_img" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
                        <button id="fileSelect" class="btn btn-primary">Select 

Open in new window

1
Is there any working solution to block AJAX popup divs in Chrome and Firefox?
0
I would like to create a button on a php page that would table the records from the file on the server and load it into a mysql table.

This is a php page. It has records in the form of a table on the page. I will have the button id, the same as the file I would like to load into the mysql table. The files already reside on the server in a folder called uploaded.

Here is what I can do so far.

1. Capture the name of the file on the table with the id using jquery and ajax to push the file name to a php file that is to write the rows in the the csv file to the table.

A simple example with a field or two would be very helpful. All my fields are text as there is some characters that make the input from the csv file a little unpredictable.  

Please note the first row will have the field headings in the csv, so would need to start at row 2 and loop through the rest of the rows.
0
I'm trying call this following function in this ajax call,  var myReturn = processLinkedDocuments(reportId, localInvoiceFormatType); but is skipping it at every single time. Not sure if it's because I have it between some if/Statement but no luck... It never call the processLinkedDocuments function

 $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: '@Url.Action("PrintInvoiceStoreData", "InvoicePrinting")',
                    data: data,
                    success: function (response) {
                        if (response.Success) {
                            reportId = response.Message;

                            var reportCount = 0;
                            if ($('#s3foCallAheadList').prop('checked')) {
                                reportCount++;
                                var url = '@printInvoicesCallAheadReportUrl'.replace("CBNR", reportId);
                                console.log("test1");
                                window.open(url);
                            }

                            if ($('#s3foSchedule').prop('checked')) {
                                reportCount++;
                                var url = '@printInvoicesScheduleUrl'.replace("CBNR", reportId);
                                console.log("test2");
                                window.open(url);
                            }

                            if ($('#s3foWorksheet').prop('checked')) {

Open in new window

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.