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

Dear Experts,
I'm new to Ajax and JQuery,
is it possible to post variables to another domain with below code?

How can I see the result of the below post code on my page? it posts on my site, through on my own domain.

    <script>
	
var xhr = new XMLHttpRequest();
xhr.open("POST", 'the URL', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);


	</script>

Open in new window

0
CompTIA Cloud+
LVL 13
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Using VB.NET I am filling in a one <input> element.  That element isn't part of a form... it is part of Ajax.

Upon entering text into the input element and hitting the Enter key Ajax posts the contents of the form to another page.

How can I do this using VB.NET.

If the data that I am entering into the input element is appending with Chr(13) or Chr(10) this doesn't help.
0
Hello everyone !

I ask for your help concerning a javascript script.
I do not really know myself and I am faced with a delicate situation.

So here I have a page that contains this piece of code :
function CALCUL_PRIX_DLVR() {
    var c_Weig = $('#Poidt').html();
    var c_Deli = $('#Dlvry').html();
    var c_Zone = $('#Zones').html();
    var c_Table;
    switch (c_Deli) {
        case "SIVOP":
            c_Table = null;
            break;
        case "DHL":
            c_Table = "tb_shop_prices_dhl";
            break;
        case "LA POSTE":
            c_Table = "tb_shop_prices_laposte";
            break;
        default:
            c_Table = null;
            break;
    }
    var data = {
        c_Weig: c_Weig,
        c_Deli: c_Deli,
        c_Table: c_Table,
        c_Zone: c_Zone
    };
    $.ajax({
            type: "POST",
            url: "_shop-calcul.php",
            cache: false,
            data: data,
            async: true,
            dataType: "json"
        })
        .done(function(reponse) {
            var erreur = typeof(reponse.Error) != 'undefined' ? reponse.Error : null;
            var result = typeof(reponse.success) != 'undefined' ? reponse.success : null;
            if (!erreur) {
                if (result != null) {
                    console.log('Resultat', result);
                    var v = "";
                    $.each(result, function(i, vx) {
                        $.each(vx, function(colonne, valeur) {
        

Open in new window

0
Looking to move audio player from development site.

Hi Guys, i was wondering if i could move the player thats here http://88.202.183.16/~iradiotest/ (when you hit play) to the main site https://iradio.ie (when you hit listen live)

I cant seem to find where the first player lives
0
 $('#email-attachment-form').submit(function (e) {
        e.preventDefault();
    
         alert("test");
    });

Open in new window


Just testing if submit is triggering.

how the form is created

   $html .=                        '<form id="email-attachment-form" name="email-attachment-form" class="email-act-form-validation"';
            $html .=                              'style="padding:20px 10%;border-top:1px solid #ccc;"';
            $html .=                              'enctype="multipart/form-data" novalidate>';
            $html .=                           '<div class="input-group cf mb-1">';
            $html .=                               '<input type="text" class="form-control" name="attachment-title"';
            $html .=                                       'id="attachment-title" placeholder="Title" required="">';
            $html .=                               '<div class="invalid-feedback">';
            $html .=                                   'Please provide file title.';
            $html .=                               '</div>';
            $html .=                          '</div>';
            $html .=                           '<div class="input-group cf">';
            $html .=                                '<div class="custom-file mb-5">';
            $html .=                                   '<label class="custom-file-label" for="attachment-file">Choose file...</label>';
            $html .=                                 

Open in new window

0
I am getting an error as below when i deploy the code in IIS where as in local it works fine.

I have a master page and master page has an update panel which display a popup on click of a button . Inside an update panel it has two buttons which on click is performing operations server as well as client side operations. It has a child page where <asp:ScriptManager>.. has been employed (i.e., AJax CDN toolkit ). Now the issue seems to be like whenever the child page is loading it is not allowing a postback from master page's Update panel , whereby giving an exception as below :

Uncaught TypeError: Cannot read property 'PRM_ServerError' of undefined
    at Sys.WebForms.PageRequestManager._createPageRequestManagerServerError (MicrosoftAjaxWebForms.js:6)
    at Sys.WebForms.PageRequestManager._parseDelta (MicrosoftAjaxWebForms.js:6)
    at Sys.WebForms.PageRequestManager._onFormSubmitCompleted (MicrosoftAjaxWebForms.js:6)
    at Array.<anonymous> (MicrosoftAjax.js:6)
    at MicrosoftAjax.js:6
    at Sys.Net.WebRequest.completed (MicrosoftAjax.js:6)
    at XMLHttpRequest._onReadyStateChange (MicrosoftAjax.js:6) 

Open in new window



i tried setting like this to supress it, but it did not help :
<script runat=server>
  $(document).ready(function () {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest( endRequest );
        });

        function endRequest( sender, e ) {
            if( e.get_error() ){
                document.getElementById("error").innerText =  e.get_error().description;
                e.set_errorHandled( true );
            }
    </script>

Open in new window


the issue is driving me nuts ! and i need a proper solution to make the button click in updatepanel work in Master page .
0
Hey

So i use Amazon S3 upload file to store uploaded Files,

Now what im trying to do is  a custom attach document to a email which i am using phpmailer to attach, my issue is im not sure how to get the file from Amazon S3 and attach it to the PHPMailer.

I have only front end and jq setup, where you click on a attachment which sends a ajax request to the backend which uses a file path to go to the S3 but im not sure how to bring back the file to pass into phpMailer.

any tips or advice ?
0
AJAX to call a page.  I have a button that when clicked it will download a csv doc.  I need to attache an AJAK Call so as to return/ download an additional CSV.  The AJAX Call to the page works but it is not downloading the CSV.

   <script>
                                                $(document).ready(function () {
                                                    $('#order_button').click(function () {

                                                        $.ajax({
                                                            url: '<?php echo base_url(); ?>download_order.php',
                                                            method: 'post',
                                                            data: {term: $('#download_child').val()},
                                                        })
                                                    });
                                                });
                                            </script>
                                            <form action="<?php echo base_url('download.php'); ?>" method="POST">
                                                <button type="submit" id="order_button" name="download_csv" class="download-csv-btn"><i class="fa fa-download"></i> Download All Data</button>
                                                <input type="hidden" value="True" id="download_child" />
                                            </form>

Open in new window


downlod_order.php
$db =

Open in new window

0
PHP FULLTEXT Search.  How do I do a FULLTEXT Search on 2 tables?

$sql = "SELECT * FROM main, order WHERE MATCH(main.company, main.name, main.email, main.address, order.size, order.color, order.manufacturer)
AGAINST('$searchTerm' IN NATURAL LANGUAGE MODE)";

Open in new window

0
I have an iframe in Masterpage updatepanel . It has an .html page as its source. So, there is a textarea where the html page is displayed .  When i modify the html page in the textarea and click on a button , it should update the html content back to html page. [Basically i want the updated dom of the iframe to be assigned back to the innertext of the html body of the html page . i am currently using htmlagility pack to achieve read and save of the .html page. The only thing not working is the updating of .html file dynamically .

Is it possible to do so ?
0
OWASP: Forgery and Phishing
LVL 13
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

How to get around the jQuery.ajax CORS and Jsonp callback problem?
I'm writing a solution in a WordPress plugin which requires an api GET call, and will later require POST too, from JavaScript.
My initial attempt resulted in a CORS policy block:
Access to XMLHttpRequest at 'https://app.xxxxx.com/api/pub/v1/contacts/528a34f9-dbc1-4c50-ad6b-a9f300e19ea9' from origin 'https://www.xxxx.co.uk' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Open in new window


This is what the jQuery looked like:

function generateCandidate(cuid){
    console.log('Generating New Candidate');
    var api = my_api()
    var candUrl = "https://app.xxxx.com/api/pub/v1/contacts/" + cuid;
    var da = {
        api_key: api,
    }
    jQuery.ajax({
        url: candUrl,
        data: da,
        type: "application/json",
        method: 'GET',
        success: function(resp){
            console.log(resp);
        },
        error: function(err){
            console.log('Ajax ERROR:');
            console.log(err.toString());
        }
    });
}

Open in new window


So I did some research and discovered plenty of people were getting around the CORS issue by specifying the 'jsonp' type instead of json. So I tried replacing
        type: "application/json",

Open in new window

with
dataType: 'jsonp',

Open in new window


But then I discovered I need to specify a callback somehow, because the error I get is this:

jquery.js?ver=1.12.4:4 GET https://app.xxxx.com/api/pub/v1/contacts/528a34f9-dbc1-4c50-ad6b-a9f300e19ea9?callback=jQuery1124036525732914578746_1550866428904&_=1550866428905 net::ERR_ABORTED 404

Open in new window


I've read about how the callback can be sent to a function, and handled that way to make it work. But I can't find out what the function should do, or how to write it.
And I'm not sure if that's what I should be doing anyway, or if there's any way I can solve the CORS problem in a way it can be used publicly, and not just in my own browser.

Can anyone assist, or point me in the right direction to get this solved.

Many thanks
Tim
0
I have mvc / razor app using ajax to make some transactions. everything is working fine.
But just we will add more parameters in data and It is going to super long list. so I want to find better way to handle this codes below.
I am thinking using json format passing value from front to the back. but do not know how to do it.

my question is:

1. is it best practice to use json format to pass list of value back and forth? If yes, can you show me how to do it with my codes below?
2. If json is not, can you suggest me what to do?
3. On the end - code behind. I do have lead class. and hope the best will be JsonResult CreateLead(Domain.Lead l) so I do not have to worry too much about list too long.


Thanks


$.ajax({
                                url: "/Home/CreateLead",
                                datatype: "text",
                                data:
                                {
                                    'firstname': document.getElementById("first-name").value,
                                    'lastname': document.getElementById("last-name").value,
                                    'phonenumber': document.getElementById("phone-number").value,
                                    'emailaddress': document.getElementById("email-address").value,
                                    'totalcountadult': document.getElementById("total-count-adult").value,
                                    'totalcountkid': 

Open in new window

0
I'm trying to "POST" data via jquery ajax to a back end perl script

If i change bellow method to GET it works

HTML
<html>
  <head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
         <script>
           var url = "cgi-bin/form.pl?list=123,456,789&foo=bar";
           $(function() {
           $("#PostBtn").click(function(){
            $.ajax({
            url: url, 
            type:"POST",
            dataType:"text",
            success: function(data, textStatus, jQxHr) {
            
            $("#res").html(data);
            },
            });
              });
          });
         </script>
  </head>
  <body>
    <div><button id="PostBtn" value="Post btn">Post btn</button></div>
    <div id="res"></div>
  </body>
</html>

Open in new window


cgi-bin/form.pl
#!C:\strawberry\perl\bin\perl.exe
print "Content-type:text/html\n\n";

use CGI;
 my $query = CGI->new;

my @Names = $query->param;
my $list = $query->param('list');
my $foo = $query->param('foo');

<p>data $data</data>
print <<HTML;
  <h1>Hello Posts</h1>
HTML
foreach my $name (@Names)
  {
    print "<p>" . $name . "[ " . $q->param($name) . "]</p>";  
    
  }

Open in new window


How do I receive the parameters in perl?
0
PHP Search Function.  Is there a PHP template used to perform a search of one DB table?  Is there a template for an AJAX Search?
I need to Search a table and am looking for the simplest / fastest way to implement a search function that searches a DB table if a row contains  the keyword and return each row.
0
I am using the AjaxFileUpload part of the AjaxControlToolkit.  I am trying to trigger a javascript function from the OnClientUploadComplete function.  I put in the name of the function in quotes next to the OnClientUploadComplete= inside the tag and all looks fine.  When I run it in IE 11 I get an error the the function is undefined and AjaxFileUpload model and a grid below it do not finish loading on the page.  Only in IE 11.  What am I doing wrong.  If I take this out, the file uploads fine but the grid below show all files uploaded does not reload with the new file showing.  Reloading the page shows the new file.  I tried putting "javascript: functionName" inside the quotes and it causes other Javascript below that to malfunction and show a panel I was hiding until I click a link to show it.  Very strange and frustrating.  This is a web forms site that use to run in VS 2010 and now running from VS 2017.  Had other issues but need this one corrected first.

See the area of code below.  Commented out the Update Panel as a stab but no luck.

    <script type="text/javascript">
        function OnFileUploadComplete(sender, args) {
            //if (sender._filesInQueue[sender._filesInQueue.length - 1]._isUploaded)
            __doPostBack('updatePanelAttachments', '');    // Do post back only after all files have been uploaded
        }

        function padDatePart(part) {
            return ('0' + part).slice(-2);
        }

        function OnlblStepErrChanged() {

Open in new window

0
I am trying to write a Javascript using AJAX to get and send the windows credentials to the server app for integrated windows authentication and have a web page returned that represents the roles of the user.  I am using red hat developer studio and wildfly 15.  I am tackling this one thing at a time.  The first step is to send the credentials.  This is what I have so far.  I am pretty new at developing, so I would appreciate any feedback.  I know I am missing the script tag to start it.  There are other things that are not relevant, so I did not include them.

var service_url = "http://192.168.20.200:8080"
$.ajax({
    type: "GET",
    url: service_url,
    dataType: "xml",
    data: "ParamId=" + FormId.value,
    processData: false,
    beforeSend : function(req) {
         req.setRequestHeader('Authorization',
               make_base_auth ('USERNAME', 'PASSWORD'));
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {  
         ajaxError(XMLHttpRequest, textStatus, errorThrown);
    },
    success: function(success); }
    function success()
    {<alert SUCCESS!> }
});
</script>
0
I am trying to access the properties of this object but i keep getting undefined. This is what i return from PHP json_encode($return, true);

i try to access results.message (undefined)
or results.status (undefined)

My jquery:

jQuery.ajax({

url: "order_sync.php",
method: 'post',
dataType: 'json',
data: {
  order: obj
},
error: function(){
    
},
success: function(results){


  if(results.status === '0'){


    $(order_button).closest('.error').show();

  } else {

$(order_button).closest('.success').show();

  }

}

})

Open in new window



This is the JS returned to me from PHP and an ajax call:

[  
   {  
      "status":"1",
      "message":"Some Message.",
      "order_id":"6336",
      "country":"United States",
      "customer_name":"Customer",
      "ship_method":"Fedex Ground (Fedex Ground)"
   }
]

Open in new window

0
jQuery Animation to build a visual display.  I want to build a visual display from info/data in my DB but I am not 100% certain on where to start.  It is just visual display but I need to calculate the results of data from my DB.  My question is, where would you start in developing this visual and what skills should be needed to complete this?  Any input is welcome.
I query the DB for results and that will be a few figures.  How would you translate those figures into graphics?  CSS? jQuery? SVG?
How To
0
This might be a stupid question but... if i am using Auth0 for authentication and i make an AJAX call to another file on my server, do i have to pass anything through to this file in the request? Or simply having the auth0 check inside the file that ajax request is going to will suffice because it will authenticate the user via the session data being stored on the server?

I guess im confused because if I dont have some sort of check in this php file anyone can technically send request to it, and if i do have some sort of check (like the auth0 check) how will it know it came from an authenticated user?

I am using PHP SDK btw.

Thanks
0
OWASP Proactive Controls
LVL 13
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

I use ajax to pass a variable to the another page

I have link which works perfectly fine.

xmlhttp.open("GET","getuser2.php?q="+stryeni,true);

however I'd like to add another parameter to the link?
the parameter is p=str,
I get the "str" variable from innerHTML.

how can I do that?

I tryied it like this but it didn't work. thank you

xmlhttp.open("GET","getuser2.php?q="+stryeni&p=str,true);
0
I have a setup I am re-writing that uses tabs for different functions. Two of those tabs are related forms that are submitted together. Another tab holds a table with pagination and column sorting. This creates a problem as every page change or change in sorting or row size in the paginated table requires a page refresh, which clears the forms. Ideally, I would just rewrite the table and use Ajax. The more expedient thing to do would be to just serialize the form on any form change, and refill the form from that serialized data if and when the user returns to the form in the same session.
$('#FormName').on('keyup change paste', 'input, select, textarea', function()
{
    // Do something here
}

Open in new window

What I am looking for:
1. I am not sure how best to store that serialized data (HTML5 local storage would be okay) or how best to refill the forms.
2. Perhaps there is a better way to do this altogether.
0
I'm trying to build a SPA using jQuery AJAX and .NET Web Services and I am stuck trying to figure out why my ajax call is returning a 500 internal server error.

Assume id = 0 and an instance of a shopping list is returned to the ajax call. For some reason it is always hitting the error handler and showing "something went wrong".

JS code:
function getShoppingListById(id) {
    console.info(id);

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "api/ShoppingList/" + id,
        success: function(result) {
            currentList = result;
            showShoppingList();
            drawItems();
        },
        error: function() {
            console.error("Something went wrong");
        }
    });
}

$(document).ready(function () {
    console.info("ready");
    $("#shoppingListName").focus();
    $("#shoppingListName").keyup(function(event) {
        if (event.keyCode === 13) {
            createShoppingList();
        }
    });

    var pageUrl = window.location.href;
    var idIndex = pageUrl.indexOf("?id=");
    if (idIndex !== -1) {
        getShoppingListById(pageUrl.substring(idIndex + 4));
    }
});

Open in new window


C# code:
        
public IHttpActionResult Get(int id)
        {
            var result = shoppingLists.FirstOrDefault(s => s.Id == id);

            if (result == null)
            {
                return NotFound();
            }

            return Ok(result);
       }

Open in new window

0
How come i cant get the length of this object/array in javascript?

I have any ajax call that returns json data and i have tried:

console.log(results.length);

Returns undefined

OR

console.log(Object.keys(results).length);

Returns 1  even though there are 6 items.

In my console when i console.log(result);

I see result: Array(6);

What am i doing wrong?

{results: Array(6)}
results: Array(6)
0: {ClientID: 3077, SumToday: 3, Client_Name: "1"}
1: {ClientID: 3089, SumToday: 2, Client_Name: "2"}
2: {ClientID: 2067, SumToday: 2,  Client_Name: "3"}
3: {ClientID: 3085, SumToday: 1,  Client_Name: "4"}
4: {ClientID: 2072, SumToday: 1, Client_Name: "5"}
5: {ClientID: 41, SumToday: 1,  Client_Name: "6"}

Open in new window

0
What is the cleanist way to make ajax calls on content that is dynamically generated? For example  i have a laravel controller that returns data organized into divs:

$counter = 1;
foreach($data_set as $data){
<div id="$counter" data-content="$id">$data</div>

$counter++
}

endforeach;

Open in new window


So if i return 3 results
<div id="1" data-content="45">$data</div>
<div id="2" data-content="66">$data</div>
<div id="3" data-content="22">$data</div>

Open in new window


Now i want to use an ajax call to drill further down into that data so i need an ajax call to grab the data-content field from id="1" which will then return me another subset of data

<div id="1" data-content="45">$data</div>
                       <div id="1a" data-content="45">$item</div>
                       <div id="1b" data-content="45">$item</div>
                       <div id="1c" data-content="45">$item</div>
<div id="2" data-content="66">$data</div>
<div id="3" data-content="22">$data</div>

Open in new window


What is the easiest way to do this with JAvascript if my ID's are being generated dynamically? Use a loop and a this keyword to get the array key of the element being clicked ?
0
I want to be able to fire a simple HTML request using ajax.
I don't have access to change the server I am requesting, but all it does is fire back OK as plain text if all is ok.

Here is my super simple code:

<!DOCTYPE html>
<html>
<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: "http://127.0.0.1:8000/press/bank/1/1",
         success: function(data)
         {
            console.log(data);

            if (data == "ok") {
               $("#div1").html(data);
            } else {
               alert("not ok :( - " + data);
            }
         },
         error: function(jqXHR, textStatus, errorThrown)
         {
            console.log("Oops: " + textStatus + errorThrown);
         }

      });
      return false;
   });


});


</script>

</head>

<body>

<div id="div1"></div>

<button>button</button>

</body>
</html>

Open in new window


The issue is that i get an error response:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/press/bank/1/1' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
untitled.html:36 Oops: error

When I look at the network tab in Chrome I still get the OK back....

Is there a way to avoid this error??
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.