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 an ASP.Net webforms app with a GridView.  (The Gridview automatically generates the columns on binding because the data source is dynamic and the number of columns vary.)

I have code in place so when a cell in the GridView is clicked by the user it will display some data relative to the clicked cell in a Panel via the ModalPopupExtender control (from AJAX control toolkit).

The problem I have is the ModalPopupExtender fires BEFORE the GridView_RowCommand.   I need to run a query in the GridView_RowCommand event to collect the data to populate the labels in the Panel control, that is displayed via the ModalPopupExtender.   The query needs to run in the GridView_RowCommand event because this is where I get the needed Row and Cell index data for the query.

How do I get the ModalPopupExtender to fire AFTER the GridView_RowCommand event?

ASPX code (Pertinent):

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


    <style type="text/css">

   .modalBackground

    {

        background-color: Black;
        filter: alpha(opacity=90);
        opacity: 0.8;

    }

    .modalPopup

    {

        background-color: #FFFFFF;
        border-width: 3px;
        border-style: solid;
        border-color: black;
        padding-top: 10px;
        padding-left: 10px;
        width: 300px;
        height: 140px;

    }

        </style>


                        <asp:GridView ID="grdKanban" runat="server" 

Open in new window

0
Python 3 Fundamentals
LVL 13
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

I would normally just echo out the search results using php when doing an Ajax search but this time I am trying to use a json response instead. For seem reason I am getting duplicate results like:

result 1
result 2
result 1
result 2

when it should just be

result 1
result 2

DB Query:

    public static function searchContacts($searchText)
    {
        $searchTerm = "%{$searchText}%";
        
        $db = static::getDB();
        $stmt = $db->prepare("SELECT `id`, `first_name` FROM `contacts` WHERE `first_name` LIKE ?");
        $stmt->execute([$searchTerm]);
        return $stmt->fetchAll(PDO::FETCH_CLASS, get_called_class());
    }

Open in new window


Controller:

    public function search()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            
            $response = [];
            
            $searchText = trim($_POST['searchText']);
            
            $searchResults = Contact::searchContacts($searchText);
            $response['results'] = $searchResults;
            
            echo json_encode($response);
            
        }
    }

Open in new window


jQuery/Ajax

    $('#search').keyup(function () {
        var searchText = $('#search').val();
        if (searchText.length > 3) {
            $.ajax({
                    url: url + '/Contacts/search',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        searchText: searchText
                    }
                })

                .done(function (data) {

                    $.each(data.results, function (index, item) {
                        $('.search-results').append("<a href=' " + url + '/contacts/' + item.id + " '>" + item.first_name + "</a>" + "<br>").show();
                    });
                })

                .fail(function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus + ': ' + errorThrown);
                    console.warn(jqXHR.responseText);
                });
        } else {
            $('.search-results').hide();
        }
    });

Open in new window

0
AJAX and Javascript.  I have a function that creates an HTML Box.  However, the "dialog" is not placed in the box.  Here is the final script:

                self.options.dialogEl.dialog({
                    resizable: false,
                    draggable: true,
                    closeOnEscape: true,
                    width: data.error ? 320 : 640,
                    buttons: buttons
                });
                if (typeof self.options.onResponse == 'function')
                    self.options.onResponse(response);
            }

Open in new window


The line :  self.options.dialogEl.html(text);  Creates the box   But the Dialog / Buttons are not there.  Can anyone offer insight?
Most of the code:
 text = self.interpolate(templates.success, interpolateData);
                    buttons = [
                        {
                            'text': 'Apply Recommendation',
                            click: function () {
                                self.options.enabled = false;
                                hidePageSubmitIndicator();
                                jQuery(this).dialog("close");
                                jQuery(self.options.formFields.Address1).val(data.recommended.Address1);
                                jQuery(self.options.formFields.City).val(data.recommended.City);
                                jQuery(self.options.formFields.State).val(data.recommended.State);
                                

Open in new window

0
AJAX JSON Return.  Right now in my script that I am working on, the script returns a JSON response of a variable $response.  I want to also include $verifyResponse.  I'm not 100% sure how to write it.  This is what is in the code:

<?php
 comMember_activity_log::post('asa_address_validate', array('response' => $response, 'verifyResponse' => $verifyResponse));


// Respond
  header('Content-Type: application/json');
  echo json_encode($response,  JSON_PARTIAL_OUTPUT_ON_ERROR);

Open in new window

The var $response has half of the info I need.  $verifyResponse has the rest.  This is what the info looks like from the Network console of the JSON return:

{"error":false,"message":"","address":{"Address1":null,"Address2":"Blah Blah Court","City":"Hammond","State":"MS","Zip5":"1111","Zip4":null},"recommended":{"Address1":"Blah Blah Court","Address2":"","City":"Hamond","State":"MS","Zip5":"1111","Zip4":null},"verifyResponse":null}

Open in new window

There is info in the verifyResponse I need.
0
Hi,
I am using XmlHttpRequst to send a request.

function loadData() {
  // Create an Xhr Object
  const xhr = new XMLHttpRequest();

  xhr.open('GET', 'data.txt', true)
  xhr.onload = function() {
    console.log('ReeadyState', xhr.readyState);
    console.log(this.status);
    if (this.status === 200) {
      console.log(this.responseText);
    }
  };
  xhr.send();

Open in new window


If I run the above code, I get the following result:
ReeadyState 4
200
Some Plain Text Data

But when I use the arrow function, I get 'undefined'
xhr.onload = () => {
    console.log('ReeadyState', xhr.readyState);
    console.log(this.status);
    if (this.status === 200) {
      console.log(this.responseText);
    }
  };

Open in new window


ReeadyState 4
undefined

Why am I getting incorrect result with an arrow function here?
0
Hi,

I have a main easyhttp.js file as below:
function easyHTTP() {
  this.http = new XMLHttpRequest();
}

easyHTTP.prototype.get = function (url, callback) {
  this.http.open('GET', url, true);

  self = this;
  this.http.onload = function () {
    if (self.http.status === 200) {
      callback(null, self.http.responseText);
    } else {
      callback('Error: ' + self.http.status);
    }
  };
  this.http.send();
}

Open in new window

And I execute it on the following app.js file.

const http = new easyHTTP();

http.get('https://jsonplaceholder.typicode.com/posts',
  (err, posts) => {
    if (err) {
      console.log(err);
    } else {
      console.log(posts);
    }
  })

Open in new window


Now what i don't understand is in app.js when we create a callback function, we pass 2 parameters (err, posts) right?
How come we pass only one argument when we call callback function as below?
callback('Error: ' + self.http.status);

Open in new window


Also, in callback function declaration, we pass 2 parameters and in 'if' statement, we pass only one like if(err).
How this function knows that which one is err and which one is posts when only one parameter is passed.
0
Hi experts,

I have a question regard to sending data with PHP curl POST, GET vs jquery or javascript ajax request with post and get. Are there any differences in using one over the other as in securely passing data between client and server? I see most examples were dealing with ajax request by sending data over to the server with either GET or POST and obtain data in json instead of using curl to perform this task.  Thanks!
0
I have a jQuery DataTable with columns added for filtering. I'm trying to figure out how to get the select drop-downs to update to match the visible rows whenever the table is filtered on some other row.
The DataTable is setup like this:
<table id="TrainingSchedule" style="width:95%" >   
    <thead>   
        <tr class="filterrow">
            <th><select class="filterSelect" id="filter_Day_0"></select></th>               
            <th><input class='filterInput' id="filter_Date_1" /></th> 
            <th><input class='filterInput' id="filter_StartTime_2" /></th> 
            <th><input class='filterInput' id="filter_EndTime_3"  /></th>  
            <th><input class='filterInput' id="filter_Title_4" /></th> 
            <th><select  class="filterSelect" id="filter_Location_5"></select</th>
            <th><input class='filterInput' id="filter_Room_6" /></th> 
            <th><input class='filterInput' id="filter_Course_7"   /></th>  
            <th><input class='filterInput' id="filter_CourseNumber_8"  /></th>  
            <th><input class='filterInput' id="filter_SectionNumber_9"  type="text" /></th>  
            <th><select class="filterSelect" id="filter_Instructor_10"></select></th>
            <th><select class="filterSelect"  id="filter_Type_11"></select></th>
            <th><select class="filterSelect" id="filter_Ignore_12"></select></th>             
            <th><input class='filterInput' id="filter_DateAdded_13"  /></th>  
        </tr>      
    

Open in new window

0
Screen-Shot-2019-03-22-at-15.18.32.png
so the image is my message editor which i am using ckeditor to create templates,

this text is wrapped in paragraph tags ,

the text within the curly brackets refers to a property,

so when you insert this template on a users profile those id within the curly brackets displayed their info so in this image first name and last name,

is their s way i can read these id within the curly brackets ? im using php
0
Hi,

If I run the following code, I get
READYSTATE 4
200
Some Plain Text Data

However if I don't use 'this' on 'this.status' and 'this.status', the result will be
READYSTATE 4
it doesn't display the state and responseText. But it displays xhr.readyState even though we dont use 'this' like this.xhr.readyState. (actually I am getting an error if I use 'this' here. Uncaught TypeError: Cannot read property 'readyState' of undefined
    at XMLHttpRequest.xhr.onload)

Can you please explain why do I need 'this' in some places and don't in some other places?

document.getElementById("button").addEventListener("click", loadData);

function loadData() {
  // Create an XHR object
  const xhr = new XMLHttpRequest();

  // Open 
  xhr.open('GET', 'data.txt', true);
  xhr.onload = function () {
    console.log('READYSTATE', xhr.readyState);
    console.log(this.status);
    if (this.status === 200) {
      console.log(this.responseText);
    }
  }
  xhr.send();
}

Open in new window

0
Rowby Goren Makes an Impact on Screen and Online
LVL 13
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Dear Experts,
I use PHP and Javascript.

this is the GET method that I use, and it works perfectly fine.

however, I neen to use POST method,
how can I convert it to POST method?
thank you
function showUser(str) {
	
	var x = 4;
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
         xmlhttp.open("GET","getthe.php?q=" + str + "&p=" + x,true);
        xmlhttp.send();
		
		
    }
}
</script>

Open in new window

0
Dear Experts,
I'am using PHP 7.2
I'm getting data from another page using Ajax,
it works perfectly fine, however, the html shows up on the page but actually it is not on the page as source code.

It is not seen when I use browser option "view source code". But it is on the page whic is fine by me.

However, But I bring back some html as results from the page get.php.

For example an hidden HTML input like below.

I want to post this hidden input to another page, but it is not posted.

My code is below.

I pass the parameter to p and q to get.php and got some data like this including an hidden input.

<input type=hidden id=Id name=Id value='$Id'>
<input type=radio class='active'  name=not checked='' value=0 style='width: 17px; height: 17px;' >

I can see everything that brings back on the page. But when I post it to another page, not radio button option, nor hidden input posted.

what should I do?

function showUser(str) {
	
	var x = 4;
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                

Open in new window

0
Good Evening Everyone

I am trying to do a registration MODAL to post using php and get back a confirmation result, I have it working in the normal submission method POST using php, which passes the variables and reloads the page to registration.php after submission.

This is the MODAL below :
           <!--Body-->
                    <div class="modal-body">
                        <form method="POST" action="/registration.php">
                      <div class="md-form form-sm mb-5">
                        <i class="fas fa-user prefix" style="color: dodgerblue "></i>
                          <input class="form-control" id="fname" name="fname" type="text" placeholder="&nbsp First Name"><br>
                      </div>

                      <div class="md-form form-sm mb-5">
                        <i class="prefix"></i>
                          <input class="form-control" id="lname" name="lname" type="text"  placeholder="Last Name"><br>
                      </div>

                      <div class="md-form form-sm mb-4">
                        <i class="fas fa-address-book prefix"></i>
                          <input class="form-control" id="address" name="address" type="text"  placeholder="Address"><br>
                      </div>
                        <div class="container">
                        <div class="form-check-inline">
                            <label class="form-check-label">
                                <input type="radio" 

Open in new window

0
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
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
Javascript - Character's Remaining.  I have a character's remaining script that is not working. The character count does not diminish and one can put in as many characters as they desire.

      
<script>
<!--
var limit = 300;
var left = limit;

function chlimit(what){
        var count = what.value.length;
        left = limit - count;
  
        if (left < 0) {
                what.value = what.value.substring(0,limit)
                placeholderobj.innerHTML = lengthleft
        }
        document.getElementById("div1").innerHTML="Characters Left = " + left;
}
// -->
              </script>
      
    </p>
            <p><h3>Post A Notice</h3>
<?php 

// Need the form functions script, which defines create_form_input():
require ('./includes/form_functions.inc.php');	
?>
</h3>
	
    <form action="PostANoticeYE.php" method="POST" accept-charset="utf-8">
        
         <p><label for="description" class="SmallHeading"><strong>Description</strong></label>
Please enter a brief description. You have up to 300 characters.
      <div id="div1">Characters Left = 300</div>
<?php create_form_input('description', "textarea", $PostANoticeYE_errors,"maxlength='300' onkeyup='return chlimit(this)' "); ?>

Open in new window

0
Announcing the Winners!
LVL 13
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

Save CSV  file to temp directory.  How do I save these 2 files to a temp director?  I am saving 2 files and then want to zip them for download.  This is where I am but it's not working yet.

This file, download.php is called by an AJAX call.

I'm not writing the CSV files correctly and that is where I am stuck

 function download() {
        $con = getdb();

        $query = "SELECT * FROM ItpSurgeon";

        $output = fopen("test.csv", "w");

        $output = array('ID', 
            'Record ID ', 
            'Parent ID', 
            'User ID',
        );

        $result = mysqli_query($con, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            fputcsv($output, $row);
        }
         $write = fopen("test.csv", "w");
         fwrite ($write,$row);
         fclose ($write);
         
    }
      function download_b() {
        $con = getdb();

        $query = "SELECT * FROM ItpChild";

        $output_b = fopen("test_b.csv", "w");

        $output = array('ID', 
            'Record ID ', 
            'Parent ID', 
            'User ID',
        );

        $result_b = mysqli_query($con, $query);
        while ($row_b = mysqli_fetch_assoc($result_b)) {
            fputcsv($output_b, $row_b);
        }
         $write_b = fopen("test_b.csv", "w");
         fwrite ($write_b,$row_b);
         fclose ($write_b);
         
    }
    download();  
    download_b();  

    $zip_name = 'csv.zip';
$zip = new ZipArchive;
$zip->open($zip_name, 

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

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.