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

My PHP script returns an SQL error:
SQLSTATE[HY000] [2002] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
whenever it cannot connect to the database to fetch the expected result.  This SQL error always comes up on my webpage and I would like to present it with something nice to my page  visitors. But my Ajax seems not to be working as it always comes up with that error each time I lost db connection. Below is my ajax:

function feedUpdate() {
    //$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: 'functions/feedUpdate_New.php',
        success: function(data) {
            if (data) {
                document.getElementById("homeFeed").innerHTML = data;
            } else {
                document.getElementById("homeFeed").innerHTML = "We are not able to get the feed at this time";
            }
        }
    });
    //});
}
feedUpdate();

Open in new window


NOTE: The PHP script is - feedUpdate.php and it contains the expected result. The above ajax returns the required result from the script if I have db connection. But once the db connection is lost, it pops up the sql error on the web page. Please how can I pick that sql error and present something like:
We are not able to get the feed at this time
0
[Webinar] Cloud and Mobile-First Strategy
LVL 11
[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

I have problem after migrate to another server.

When i click on menus page, "add to menu" loading, but not effect. Loading (spinning icon) stay all the time. And there is two more problems, in revolution slider when click save, says ajax error! error, and in WP Bakery when I want to edit content and click on edit button, loading but not showing anything.

I was change wp-config.php and increase memory limit, now in backend on status I can say green, just SQL version is red. When I was migrating I need to export SQL custom to MySQL40, because when I importing shows error with utf8mb4_unicode_520_ci. In phpmyadmin I cant see that collation. Now I changed all collation to utf8_general_ci. Maybe this causes problem?

Hosting provider is hostgator, shared hosting.
0
We have used ajax call with "async: false" through out our web application, now in Safari browser(in Windows and Mac OS both) if response gets delayed more than 5 seconds Safari browser throws dom timeout exeption.

$.ajax({
	type: "POST",
	contentType: "application/json; charset=utf-8",
	url: "Web method url",
	data: jsonData,
	async: false,
	success: function (data) {
	},
	error: function (data) {
	},
	complete: function () {
		
	}
});

Open in new window


The straight solution we found through different blogs is to set "async: true" or implement setTimeout() logic, that will fix the issue we have already tested that.

But we are looking for another solution that is there any way like by any property in configuration or AJAX call or any browser setting we can increase JavaScript Execution time for Safari browser.
0
We have an ASP.NET MVC 5 Question.  

What's is the best way to POST to an API.  Should this be done from the VIEW as an AJAX call OR should the POST be done from within the MVC Controller?
0
I have a modal div on a view, with a textbox and a button.  here is the javascript for the button click:

    $("#Search").on("click", function (e) {
        e.preventDefault();
        var address = $("#txtSa").val();
        var sa = address.replace(/ /g, "-");
        var frmData = new FormData();
        frmData.append("StreetAddress", sa);
        var url = "/Residents/SearchAddress"; ///" + sa;

        $.ajax({
            type: "POST",
            url: url,
            data: frmData,
            success: function (response) {
                alert(response);
            }
        });
    });

Open in new window


When this code executes I get the following script error:
jquery-3.1.1.js:8400 Uncaught TypeError: Illegal invocation
    at add (jquery-3.1.1.js:8400)
    at buildParams (jquery-3.1.1.js:8387)
    at Function.jQuery.param (jquery-3.1.1.js:8420)
    at Function.ajax (jquery-3.1.1.js:9010)
    at HTMLButtonElement.<anonymous> (Index:361)
    at HTMLButtonElement.dispatch (jquery-3.1.1.js:5201)
    at HTMLButtonElement.elemData.handle (jquery-3.1.1.js:5009)
add @ jquery-3.1.1.js:8400
buildParams @ jquery-3.1.1.js:8387
jQuery.param @ jquery-3.1.1.js:8420
ajax @ jquery-3.1.1.js:9010
(anonymous) @ Index:361
dispatch @ jquery-3.1.1.js:5201
elemData.handle @ jquery-3.1.1.js:5009

Open in new window


I am calling a controller action below, but it never reaches the controller:
[HttpPost]
        public ActionResult SearchAddress(string StreetAddress)
        {
            string result = "no";

            string address = StreetAddress.Replace("-", " ");

            Resident res = db.Residents.AsNoTracking().Where(r => r.StreetAddress.Equals(address)).FirstOrDefault();

            if (res != null)
            {
                result = "yes";
            }

            return Content(result);
        }

Open in new window


I don't know what I'm doing wrong here.
0
Hi,

I have a problem showing the Data Tables searchfield. I have tried everything I can think of, but it does not show.
What am I doing wrong.

The page is this: http://kroweb.dk/gfdev/ft_raw2/

I have this main code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Folketællinger</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">


    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css" />


    <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>

  <script type="text/javascript" src="jquery.dataTables.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        $('#myTable').dataTable( {
          responsive:true
            "language": {
                "url": "dataTables.danish.lang"
            }
        } );
    } );
</script>

    <script type="text/javascript">
    $(function(){
        $('#ft_items').on('click', '.toggle', function() {
            

Open in new window

0
On the codeigniter side the post data isn't being received.  PHP is however receiving it.

Here is the ajax call
   
    var postData = {
        'partNumber' : '45367'
    }
axios.post('http://localhost/stuff/index.php/admin/reactTestaroo', postData)
        .then(response => renderTheTestData(response.data))

Open in new window


Here is what is in my PHP/CI controller:
    function reactTestaroo(){
        $entityBody = file_get_contents('php://input'); // just as a test I used this and it returns "{'partNumber':'45367'}" which seems to indicate it's being passed fine
        $pastNumber = $this->input->post('partNumber'); // returns NULL, this is the problem.. it should show the part number value.  
    }

Open in new window


I can use jQuery ajax all day long and it works fine like this:
    $.ajax({
        url: 'http://localhost/stuff/index.php/admin/reactTestaroo',
        data: postData,
        type: 'POST',
        success: function(response) {
        var parsedJSON = $.parseJSON(response);
        renderTheTestData(parsedJSON.part_name)
        },
        error: function(response){
            alert('nope');
        }
    });

Open in new window

With jQuery it works every time but I want to ditch jQuery and use react and a ajax plugin like axios but clearly I'm having an issue with it.  Can someone help me get the ajax via axios working?
0
I have an ASP.NET MVC Web API project using an AJAX script that POST data to my database.  This script includes a simple "success" and "error" function that returns a console.log message so I know if the script worked.  

This AjAX call works and the data from the form is being Posted (Inserted) into the database.  Great!

However... The AJAX code executes the "error" function even when the post is successful for some reason and I cannot figure out why.

Here's my code...

AJAX
$.ajax({
                    url: "/api/simpleEvents",
                    method: "post",
                    data: formData,
                    success: function (data) {
                        console.log("Yeah!  It worked.");
                        console.log(data);
                    },
                    error: function (result) {
                        console.log("Something unexpected happened.");
                        console.log(result.status + ' ' + result.statusText);
                    }
                });

Open in new window


Here's my controller.
        // POST /api/SimpleEvents
        [HttpPost]
        public IHttpActionResult CreateNewSimpleEvent(SimpleEventDto simpleEventDto)
        {
            if (!ModelState.IsValid)
                return BadRequest();

            var newSimpleEvent = Mapper.Map<SimpleEventDto, SimpleEvent>(simpleEventDto);

            _context.SimpleEvents.Add(newSimpleEvent);
            _context.SaveChanges();

            simpleEventDto.Id = newSimpleEvent.Id;

            return Created(new Uri(Request.RequestUri + "/" + newSimpleEvent.Id), simpleEventDto);
            
        }

Open in new window


What am I doing wrong?
0
<script>

         $(document).ready(function()  {
                    $('#importSubmit').on('click',function(){
                    var phone1=document.getElementById('phone').value;
                    //alert(phone1);
                    var msg=document.getElementById("message").value;
                    // alert(msg);
                    var opt=document.getElementById("opt").value;
                    //alert(opt);
                    var impt=document.getElementById("importSubmit").value;
                    //alert(impt);
   
                   
                    $.ajax({

                    type: 'GET',

                    url: 'http://localhost/whatsapp_message_sender/importData.php?',

                    dataType: "json",
                     //data:'foo='+ bar+'&calibri='+ nolibri,
                    data: 'importSubmit='+impt+'&phone=' +phone1+'&message='+msg+'&opt='+opt,    

                    success: function(data){
                    //alert(data);
                    $('#lkct').html(data);
                   

                                              },
                error: function(jqXHR, textStatus, errorThrown)

                {

                  alert("Error: "+errorThrown+" , Please try again");  

                }      

      });

        });
});
   //});
</script>


where I went wrong here  I'm getting this error  please help me to solve problem
0
This validation is working but I just wanted to check if it is actually acceptable practice to do what I am doing.

I have a Ajax.php file which is a controller within my controllers folder.

In there I have an Ajax class with an addAccom method which looks like:

      
public function addAccom()
	{
		$response = array();
		$message = '';
		
		if($_POST['category'] == '') {
			
			$message .= "Category required <br />";
		}
		
		if(empty($_POST['name'])) {
			
			$message .= "Name required <br />";
		}
		
		if(empty($_POST['description'])) {
			
			$message .= "Description required";
		}
		
		if($message) {
			
			$response['success'] = false;
			$response['message'] = $message;
			
		} else {
			
			$response['success'] = true;
			$response['message'] = "All good";
			
		}
		
		echo json_encode($response);
	}

Open in new window


I then have some jQuery in my scripts.js file being called in the footer. The jQuery appends the data to divs I have in the view. It is working fine but I just wanted to check that this is okay using PHP and MVC or if I am breaking some rules?

I do plan on sending data to the model and performing a database insert as well.
0
Concerto's Cloud Advisory Services
LVL 5
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

I'm attempting to fire multiple URL's from Javascript using Jquery's AJAX function, based upon an array of URL's.

I'm finding that the "success" function of the AJAX call only succeeds on the last call.  It seems to ignore all the others.... but it still seems to fire all the other URL's okay...  

Should I be concerned about this working all the time?

        pixelLength = pixel.length;
        for (i = 0; i < pixelLength; i++) {
            timestamp = Math.round((new Date()).getTime() / 1000);
            pixelUrl = pixel[i] + timestamp;
            console.log("Pixel # " + i + " = " + pixelUrl);
            $.ajax({
                url: pixelUrl,
                success: function (result) {
                    console.log("Pixel #" + i + " fired Successfully: " + pixelUrl);
                }
            });
        }

Open in new window

0
Hi,

we need to Load external web site and show it as a live website tile in our application where x-frame-options set to same origin for the external website.

We followed below approaches but nothing is working.

Please help us to know any framework/approach to achieve this.

Iframe : < iFrame src="www.xyz.com">

Ajax Approach : Ajax HttpGet Call to the external web siteand get the html and render on our website.But replacing the image, css and html links from html is not working properly.


Web Request Approach : Server side HttpGet Call to the external web siteand get the html and render on our website.But replacing the image, css and html links from html is not working properly.
0
I attached illustration there is result of  code snippets below: string with user names (ivan4joni) and two users avatars .
I have two users : ivan4 and joni. As I have a while loop in php, I get names together as one string.

What would be the code for ajax to get a javascript variable as array [ ivan4 , joni]?
I don't need  users to be displayed as array on main page but as a array which will be then used in js functions.

  $.ajas x({
  method:"POST",
  url: '/wp-content/themes/net4/usersOnMainPageAjax.php',
  data:  {
      "querry2":1,
      "actualproject": whichProjectToSave
   },
   datatype: 'text',
    success: function(strdate){
   
  $('#usersWindowID > p').html(strdate);
     },
     error: function(error, txtStatus) {
      console.log(txtStatus);
      console.log('error');
    }
  });  

Open in new window


<?php
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$partners_username=...............;
$partnersHTML=...............; 
echo $partners_username;
}
echo $partnersHTML;  
?>

Open in new window


In general I need to learn how to get two variables with ajax from php.
partners.png
0
Hi I am trying to move the db and table parts of this page: http://kroweb.dk/gfdev/ft_raw2/index_test.php to Ajax.  

I get this error saying that there is undefines indexes which I don't quite understand since it is working when having it all in the same php file.

Notice: Undefined index: query_start in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 32

Notice: Undefined index: sogn in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 33

Notice: Undefined index: amt in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 34

Notice: Undefined index: type in /var/www/kroweb.dk/public_html/gfdev/ft_raw2/ajaxFtHtml.php on line 35


I really need a little help to get this setup right :) :)

I have this primary file (index_test.php):
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="utf-8">
                        <title>Folketællinger</title>

                        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
                        <link rel="stylesheet" type="text/css" href="style.css">

                        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                    

Open in new window

0
I have an ASP.NET MVC form that I'm trying to validate using JQueryVal.   The API controller works as I've tested in Postman successfully.  My problem is this.

The field validators work, however when the form IS valid it does not POST to the API and create a new record in my database table.

Instead it redirects you to the same page with the Form data in the querystring as parameters.

Here's my View that includes my AjAX/Jquery script.

@model ClienteManagment.ViewModels.IntakeFormViewModel

@{
    ViewBag.Title = "IntakeForm";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

<h2>Intake Form</h2>

<form id="newIntake">

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.ItemName)
        @Html.TextBoxFor(m => m.Intake.ItemName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.ItemName)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.ItemDescription)
        @Html.TextBoxFor(m => m.Intake.ItemDescription, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Intake.ItemDescription)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Intake.Segment)
        @Html.DropDownListFor(m => m.Intake.SegmentId, new SelectList(Model.Segment, "Id", "Name"), "Select Segment", new { @class =

Open in new window

0
<!DOCTYPE html>
<html>
<body>

<h2>JSONStringFromJavaScriptObjectUsingStringfy_7</h2>

<p id="demo"></p>

<script>

var obj = { "name":"Gary", "age":30, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

</script>

</body>
</html>

Open in new window


i am looking at above example

what is java script object there ?

is below is java script object?
var obj = { "name":"Gary", "age":30, "city":"New York"};
or above is json object? or we can call it as both?
please advise
0
what is meaning of below
document.getElementById("demo").innerHTML

is it html or javascript or ajax or what syntax?

when we say document which document?
what it mean by innerHTML is there is somethong like outerHTML
what is getElementById

how do we give id to element
what are elements
if no id then what happens

please advise
0
Newbie question.  Sorry.

Looking for suggestions (best practice) regarding RESTful API implementation.

What are the pros or cons (if any) in calling a API method from within a MVC Controller?  It this the best approach?

Or should the API call be made strictly within the VIEW page via AJAX?

Thanks, in advance, for your help.
0
Hi - I need help.  I'm new to MVC development and RESTful API architecture and could use some help.

Here's an an example of my URL:

www.mysite.com/customer/details/1

In the details View I want to make a GET AJAX call to my web API that passes that "1" parameter to the GET method.  

How do I pass that parameter (1) to the VIEW to call the API to GET the data?
0
Concerto Cloud for Software Providers & ISVs
LVL 5
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

hi,

i am trying below

https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_table

where the html table data coming from

i am not clear on what below code doing either


<!DOCTYPE html>
<html>
<body>

<h2>Make a table based on JSON data.</h2>

<p id="demo"></p>

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<table border='1'>"
        for (x in myObj) {
            txt += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        txt += "</table>"        
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

</body>
</html>

Open in new window


what is dbparam why we need to stringify json and send that

dbParam = JSON.stringify(obj);

please advise
0
hi,

i was trying to understand below ajax json example using xmlhttpobject to get file data from server
https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

i am not sure what is happening here.

<!DOCTYPE html>
<html>
<body>

<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>

<p id="demo"></p>

<script>

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

</script>

<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>

</body>
</html>

Open in new window


what it means by below?
target="_blank

where is the server path?

what is meaning of below lines


var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
when is onreadystatechange related function called and what is 4 and 200 here?
why we need to use JSON.parse
and
document.getElementById
and
myObj.name;??

please advise
0
Hi Experts,

How Do I Call PHP from JS/JQuery?  I'm thinking AJAX?

A common example is "Load More Results", where without refreshing the page, I use a jquery listener to call a PHP function (or, if I cannot be as specific, then a PHP page), that would return to the JS a JSON object.

In theory, this should  be  possible with AJAX, but how? as well, how wold I stop everything else from firing until this process is complete.

Thank  you!
0
Is there any way that I can modify this page so that the results will appear without clicking "View"?

http://www.gopherstateevents.com/results/fitness_events/results.asp?event_type=5&event_id=682&race_id=1201

Thank you!
0
How can I make the hidden div with the gif visible on submit at http://www.gseannouncer.com/'

Please note that the page submits to itself.  If I can't make the div visible onsubmit then I understand that I will have to use ajax/jquery.  The key is that I need it to happen as quickly as possible.

Thank you so much!
0
I have a paging system on my app that allows the user to click a link, an ajax call is made to get data, and that data is displayed. I'd like to make it so that the user can only click the link once, then somehow "disable" the link, execute my ajax call, then re-enable the link. I thought I could use bind() / unbind(), but am having trouble getting it to work. This is what I have:

    $('#btnNext').click(function (e) {
        if (currentPage == totalPages)
            e.preventDefault()
        else {
            $('#btnNext').unbind();
            move('next');
            $('#btnNext').bind("click", handler('next'));
        }
    });

    var handler = function ( direction ) {
        $('#dvResults').hide();
        move( direction );
        $('#dvResults').fadeIn(600);
    }

function move( direction ) {
....
}

Open in new window


for whatever reason, it pages twice (if i'm on page 1, it goes to 2, then 3), then i lose all functionality from the link.

Is this the best way to do this, or is there another way to do it?
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.