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

Hello Experts,

I need help on modal form validation.

The following code inserts properly (only when all inputs are filled correctly).

I'm having trouble validating subject_taught and class_taught inputs.

More so, I want the form to clear all inputs (reset) after insert without error. The datatable should refresh afterwards.

The code:
<?php
include('../includes/connection.php');


if ( ! empty($_POST) ) {
	
    if ( empty( $_POST["initial"] ) || empty( $_POST["username"] ) || empty( $_POST["password"] ) || empty( $_POST["role"] ) || empty( $_POST["subject_taught"] ) || empty( $_POST["class_taught"] ) ) {

    	$response = '<div class="alert alert-danger">
		<span class="badge badge-danger">Empty Field(s) Detected!</span> All fields are required.</div>';

        die($response);
    }

    // Validation passed so let's deal with the DB stuff

	$initial = $_POST["initial"];
	$username = $_POST["username"];
	$password = $_POST["password"];
	$role = $_POST["role"];
	$class_assigned = $_POST["class_assigned"];
	

	$master_query = '';
	
	$stmt = $conn->prepare("SELECT Username FROM Users WHERE Username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $staffList = $stmt->get_result();

    if (mysqli_num_rows($staffList) > 0 ) {

    	$response = '<div class="alert alert-danger">
		The Username: <span class="badge badge-pink">'.$username.'</span> already exists. Try another one!</div>';

	die($response);
  

Open in new window

0
Free Tool: Port Scanner
LVL 12
Free Tool: Port Scanner

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

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I am making my Ajax Response. For this I take 3 variables in a while loop and save values of 3 database columns in them. As there are multiple records
in DB so I have concact the value like $value .= 'value from db'. After the loop I have put these three variables in an array and sent them by using json_encode.

Here is  the sample code
 
while($projects_row = mysqli_fetch_assoc($projects_result))
		{         
			$projects_name .= '<li id="project-id-5a01bffbcfbeb40a008b458a" data-id="5a01bffbcfbeb40a008b458a">
			<span class="li-txt" style="color:#ff0000;width: calc(100% - 90px);"><a id="myAnc" href="#">'.$projects_row['project_title'].'</a></span>
			<span class="thumb-container"><span class="thumb thumb-3" style=""></span> 
			<span class="thumb thumb-6" style=""></span> </span></li>';		

			$projects_detail .= $projects_row['project_detail'];			
			$projects_image .= $projects_row['project_image'];			
        }  

echo json_encode(array("message1" =>$projects_name, "message2" =>$projects_detail, "message3" =>$projects_image ));
		

Open in new window


In my Ajax Success function I am retrieving the values as:
  $.ajax({
                url:"myresponse.php",
                type: "POST",
                data:  {"country_id":country_id},
                dataType: "json",								
					success: function(data)
					{				
						console.log(data);
						//alert(data.message1);
						//alert(data.message2);
						jQuery("#project-list").html(data.message1);
						jQuery(".pr-cont-info").html(data.message2);												
					},
				
              });  

Open in new window


The issue is data.message1 and data.message2 contains data of all rows. I need to seperate the data of each row so that I can use any row data anywhere.
For example, in my case data.message1 contains data of 3 rows like 'USA Project 1 USA PROJECT 2 USA PROJECT'. I have print that data in a DIV and due <li> tags
one record is printed in one line. Now i want that if user click on USA Project1, then it only shows the details of Project1.  Currently it shows the details of all 3 rows.

So how to fix this issue?
0
I am using a JS library to drag the controls on my PAGE to perform different functions. Checkout the demo by clicking on this link:
http://iamfashionphotographer.com/del/cb-m-1/final.html

Open in new window


1) When the page loads, see the right side and click on the icon.
2) Then you will see a snippet there. Just drag it on the page.
3) After that a button will be visible on PAge. Click on it and fill the form fields and fill the data with integer values and click on save.
4) The values are stored in DB.

What I want:
1) When you click on Table or button, you will notice that some additional buttons/controls  will appear. Click on the last icon which is a delete icon. You will notice that control will be deleted from the page. But values are still saved in Database.

I want that if user click on delete icon then its data from the table must be deleted from the database.

Need code help that on which event I will set the ajax call to delete data against that control.

Note: If user drag a control on page then following event is called:
	$('.ui-droppable').on('sortstop', function(e,i) {
	});

Open in new window


Looking for expert opinion

Thanks
0
I am working on web page on a php/mySQL server.

My quote/order web page has several cascadingdropdowns which are not working.   Not sure why, but the code
I wrote using a widgit way back.   This was before jQuary was around.  It was leading edge back  then but now its not so great.

Can you point me to a good example that I can
0
I am getting 401 error with the below ajax call. How do I fix this issue?

full error: ..................................................................................................................
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64327' is therefore not allowed access. The response had HTTP status code 401.
/...................................................................................................................................

var call = $.ajax({
           
            url: "https://name.com/web/lists('Call Management')/items?$select=Item_x0020_ID,State,Description&$filter=(Item_x0020_ID eq %27BBB000126%27)",
            type: "GET",
            dataType: "json",
            crossDomain: true,            
            headers: {
                Accept: "application/json;odata=verbose"
            },
            success: function (result) {
                alert("it worked");
               
            }
        });
0
I've got a dropdown box which is populated with ajax according to what option i choose from another dropdown. I need to duplicate the dropdown box keeping the same options loaded via ajax, this is what i've done o far. Many thanks for your help

This is the code to get tha value from the first dropbox and then use it for ajax

$('#flatGroup').on('change',function(){
        var countryID = $(this).val();
        console.log(countryID);
        if(countryID){
            $.ajax({
                type:'POST',
                url:'../controllers/ctrl_admin_group_table_app/ctrl_admin_get_building_table.php',
                data: {

                  group_id: countryID

                },

                success:function(html){
                    $('#flatTable-1').html(html);
                    $(".bs-select").selectpicker('refresh');

                }
            }); 
        }

    });

Open in new window


This is the code i'm using to close the second dropbox that receive the option from ajax

// start repeating form tabelle
        //Start repeating form group add limit
        var maxGroup1 = 5;
        //add more fields group
        var fieldGroup1= $(".fieldGroup1").clone();

        $(".addMore1").click(function() {

          var fgc1 = $('body').find('.fieldGroup1').length;

          if (fgc1 < maxGroup1) {

            var fieldHTML1 = '<div class="form-group fieldGroup1">' + fieldGroup1.html() + '<div class="col-md-1"><label 

Open in new window

0
I'm trying to include a live test for unique email and name.    The concept is to initially disable the submit button, and then re-initialize it if the credentials check-out to be unique. At this point clicking the submit button would initial the signup.php routines. Otherwise, the user would receive an error message to try again.

I have include the code "name_check' : 1," and "email_check' : 1," as ajax({ data arguments; because I've seen them in other code found online. But I don't understand what they mean: Is username_check a standard ajax function? I couldn't find any reference in the documentation.  Does this code assign the value 1 to username_check?

$('document').ready(function(){

    let name_state = false;
    let email_state = false;

    $("input[type=submit]").attr('disabled','disabled');


    // Verify user name is unique in database
    //
    $('#name').on('blur', function(){
        let name = $('#name').val();
        if (name == '') {
            name_state = false;
            return;
        }
        $.ajax({
            url: 'check_credentials.php',
            type: 'post',
            data: {
                'username_check' : 1,
                'name' : name,
            });
            .done function(response){
                if (response == 'taken' ) {
                    name_state = false;
                } else if (response == 'not_taken') {
                    name_state = true;
                }
            }
        });
    

Open in new window

0
Hey all I am using the following code on my local machine to give me a temporary WCF service:
    using System;
    using System.Windows.Forms;
    using System.ServiceModel;
    using TestService;
    
    namespace TestClient
    {
        public partial class Form1 : Form
        {
            IService1 patientSvc = null;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2202/PatientService"));
                NetTcpBinding binding = new NetTcpBinding();
                ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
                patientSvc = factory.CreateChannel();
            }
        }
    }

Open in new window

And the class1:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.Runtime.Serialization;
    
    namespace TestService
    {
        [ServiceContract()]
        public interface IService1
        {
            [OperationContract]
            Patient GetPatient(Int32 index);
    
            [OperationContract]
            void SetPatient(Int32 index, Patient patient);
        }
    
        [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
        public class PatientService : IService1
        {
            Patient[]

Open in new window

0
FORM: 'application.php'
ELEMENT:  a listbox named: 'lstgroup'

when the user select a item, the value (group_id)  is needed in sql WHERE clausule  (application.php)
variable 'group_id' is send with AJAX to application.php

-Function postgroupid() works fine
-$AJAX works fine
-Call php function sendgroupid() works fine

But the $_POST['group_id'] is empty and echo returns :"Hello php! But no group_id"
I spend a week to find a solution with all kind of suggestions from internet, but nothing helps me
Here is my code:

<script type="text/javascript">

   function postgroupid() {
   
    var x = document.getElementById("lstgroup").selectedIndex;
    var y = document.getElementById("lstgroup").options;
    var group_id = y[x].value;
    document.getElementById("edtgroupid").value=group_id;
       $.ajax({
                    type: "POST",
                    url : 'application.php';
                    data: { 'group_id' : group_id }
                   }).done(function(response){alert('succes');
                  }).fail(function(jqXHR, textStatus, errorThrown){
  alert('FAILED! ERROR: ' + errorThrown);
});
 
var result="<?php sendgroupid();?>";
alert(result);
return false;
  }
 
</script>

Open in new window

<?php
function sendgroupid()
{
if (isset($_POST['group_id']) && !empty($_POST['group_id'])) {
    echo $_POST['group_id'];
  }
   else
   {
   echo 'Hello php! But no group_id';
   }
}
?>

Open in new window

0
I am using a @foreach() loop in razor view to pass variables to a table cell as shown below. using ajax calls, i want to fetch different values from a database and display them on the table cells on a button click event. The ajax calls are successful and i can return the right data to the model but the cell values do not change after initial load. How can i make the cell values update automatically every time the model changes
code sample
0
Cloud Class® Course: CompTIA Cloud+
LVL 12
Cloud Class® Course: CompTIA Cloud+

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

Hello Experts,
I am using one validation file for multiple forms on a page. Code below.
They way that is done is wrong because it validates all the forms on the page all together. So I am trying to identify the form ID and include it to the submit function?
I would be happy if someone can help

$(document).ready(function() {

	"use strict";	

	var form = $('#contactForm, #brochureForm, #enquiryForm, #guideform');	
	
$("input[validate], textarea[validate]").each(function() {
	$(this).on("blur", function() {
			if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 3)) {
					var errorMsg = $(this).attr('errormessage');
					if (errorMsg === undefined) {
						errorMsg = "Please fill in this field";
					}
				$(this).attr("placeholder", errorMsg);
				$(this).addClass("error");
			} else {
				$(this).removeClass("error");
				$(this).attr("placeholder","");
			}
	});
});	
	
	$(form).on("submit", function(evt) {
		evt.preventDefault();
		if (validate()) {
			submitForm();
		}

	});

	function submitForm() {
		var formData = $(form).serialize();
		$.ajax({
			type: "POST",
			url: "https://url....",
			dataType: "json",
			data: formData,
			complete:function() {
				$(form).hide();
				$(".msgSubmit").show();
			}
		});
	}	
	var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);	
	
	// fields validation function
	var 

Open in new window

0
I am trying to cause external links on a different page to open content in the tab pane on another page (other than the pane with the active class).
Please note that the tab panes have its contents loaded via data-url (like an ajax load) when their correseponding anchor tags (li a) are clicked.



Please find my code below:  

MARK UP:

<div id="dashTab" class="tabbable">
   <ul id="dashboard-menu" class="nav nav-pills nav-stacked">
       <li class="dummy-li" style="text-transform: uppercase;">Investor Dashboard</li>
       <li class="active"><a href="#investment-planner" data-toggle="tab" data-url="https://server.xxxxxx.com/widgets/factory.ashx?handle=portfoliobuilder&sid=xxxxxx&mod=raw">Investment Planner</a></li>
       <li><a href="#portfolio-checkup" data-toggle="tab" data-url="https://server.xxxxxx.com/widgets/factory.ashx?handle=portfolioanalyzer&sid=xxxxxx&mod=raw"> Portfolio Checkup</a></li>
       <li><a class="accordion">Portfolio Manager</a>
             <ul class="panel">
                   <li><a href="#create-new-e-portfolio" data-toggle="tab">Create a new e-Portfolio</a></li>
                   <li><a href="#link-e-portfolio" data-toggle="tab">Link e-Portfolio</a></li>
                   <li><a href="#manage-my-e-portfolios" data-toggle="tab">Manage my e-Portfolios</a></li>
                   <li><a href="#buy-sell-shares" data-toggle="tab">Buy/Sell Shares</a></li>
            </ul>
       </li>
        <li><a href="#find-a-stockbroker" 

Open in new window

0
I need help in how to call my web method from ajax while using dnn. I can post the ajax method, but the function isn't called. I need to know what my ajax url needs to be to find the web method within my dnn module. Example of what I am talking about is below:

var result = $.ajax({
                    type: "POST",
                    url: ???????/SaveImage",
                    data: dataurl,
                    contentType: "text/plain; charset=UTF-8",
                    dataType: "text",
                    success: succeeded,
                    failure: function (msg) {
                        alert(msg);
                    },
                    error: function (xhr, err) {
                        alert(err);
                    }
                });
            function succeeded(msg) {
                alert(msg.d);
            }

AND codebehind

<ScriptService()>
Public Class test
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub
    <WebMethod()>
    Public Shared Function SaveImage(dataurl As String) As String
        Return dataurl
    End Function
End Class
0
I want to parse the JSON Data in to grid


I want to make a ajax call and get the json values and display in to  grid


could you please help me  the pseudo code
0
Hello, want to change the current notification with SignalR notification. The current code is like below in javascript:

this.poll = function(){

$.ajax({
             url: _getmessage,  //This is controller and function where it hits database and get message status and message
             cache: false,
             success: function (data){
                //Send message to the client

             //setup next poll recursively every 30 seconds
             setTimeout(poll, 30000);
            },
          dataType: "json"
        });
}

Please help
0
We have a production and staging website. Both running on IIS. The production website is running on http and staging we recently installed a SSL certificate to test https. Allw as working fine till, we hit a roadblock with one of the function giving the error 500 for type xhr.


It is an event registration form which upon submitting gives the error.
500-error.JPG
500-error1.JPG
0
I want to track page links by saving them in a json file in the background with out user noticing. I am using jquery .ajax for the front end and trying to send the link value to a php page for insertion into the json file. I can get the value of the link fine on the front end and am using the right code to add to a json file on the back end in php. I just can't seem to get the value of the link to transfer to php and be saved in the json file. I'm also not sure I have the right if condition in the php to start the php code running. http://webdevcei.com/app/track.html
0
I have a Live chart page that contains multiple Dundas charts and the page is refreshed every few minutes, depending on the setting. Normally, it runs fine. But when the chart is run 24x7, only sometimes the following error occurs and the further refreshing of the page/charts fails.

The target 'myCTL$mSnap5$zj4kzq2zcmbfipjchti4ylg_1656564000_Chart_5' for the callback could not befound or did not implement ICallbackEventHandler

I am creating the chart control in page_load event. Below is the code for Page_Load, chart's callback event handler 'AllCharts_Callback', and code of control LC02_LiveChartControl.ascx.

---------------------------------------------------------------Page_Load-------------------------------------------------------------------
try
        {
            //check if user has the right to start
        if (!Page.IsCallback && !Page.IsPostBack &&
            (string.IsNullOrEmpty(Request.QueryString[QLR.QC.ParamMenuKey]) ||
             !QLR.Rights.DB.UserHasRightsToStart(UserID, Request.QueryString[QLR.QC.ParamMenuKey])))
        {
            //user (rolid) has not the right to start
            RealtimeCharts_Panel.Visible = false;
            NoRights_Panel.Visible = true;
        }
        else
        {
            if (!cbFavLoad.IsCallback &&
                !cbFavAdd.IsCallback)
            {
         //If the chart has not been started using Favorites tab
       QLR.LiveCharts.Basics.CreateDockingContainers(
               …
0
hi,

We have one PHP (Cake Framework) page with no. of records with Paging. We are showing paging 1,2,3 in web page.
Now requirement is that
1) Web page should show as showing
2) Mobile version should use lazy loading means if customer uses thumb to up the page then then next set of records will pull and show.

Please suggest the best way to do so.
0
Cloud Class® Course: Microsoft Exchange Server
LVL 12
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

I  have validation.php?ID=<?php echo htmlentities($row['id']);?> page. I want redirect this page using ajax and jquery.
Here is my ajax code:

$('.product_delete').click(function(){            
        var formdata=new FormData($('#product_detail')[0]);		
        $.ajax({
                url:'validation.php?ID=<?php echo htmlentities($row['id']);?>',
                method: "POST",
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                data : formdata,
            success:function(answer_from_actionpage){
                if(answer_from_actionpage == 1){
                    $('.error').html("<div class='alert alert-success'>Successfully Product Deleted</div>");
                    //$('.form-control').val("");
                }else{
                    $('.error').html(answer_from_actionpage);
                }
            }
        })
 });

Open in new window

How can i redirect.
0
Good Morning,

I hope someone will be of great help :)

I Just want to know how i will write the JavaScript :)

I currently have text field, and a button, but i want the button to send the message box info to an email address onclick, but im not quite sure how to do the JavaScript part, i want to know how i can call my Java Class in the JS and then then do the onclick function to send the Email.

Thanks so much in advance


public class SendMailTLS {

public static void main(String[] args) {

    final String username = "diamantengoud@gmail.com";
    final String password = "********";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("diamantengoud@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("jp.pretorius@bmgi.co.za"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

    

Open in new window

0
Hi, I'm creating some charts and some of them will take a few seconds to be displayed. What I'd like to do is to show a 'loading' .gif while the data is been collected.
The chart is created when I select a value from a dropdownlist: 'ddlExam'. This dropdown is outside the update panel.
This is what I have so far but the .gif wont appear although the chart loads fine.

Any suggestions??

Thanks



<div class="row">
            <div class="col-md-6">
                <asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional" >
                    <ContentTemplate>
                        <asp:Chart ID="Chart1" runat="server" Width="750px" Height="400px" Visible="false" EnableViewState="true">
                            <Series>
                                <asp:Series Name="Markings" ChartType="Column" BorderWidth="1" MarkerBorderWidth="1" Font="Verdana, 8pt, style=Bold"></asp:Series>
                            </Series>
                            <Series>
                                <asp:Series Name="Avg" ChartType="Line" BorderWidth="2" Color="Orange"></asp:Series>
                            </Series>

                            <ChartAreas>
                                <asp:ChartArea Name="ChartArea1">
                                </asp:ChartArea>
                            </ChartAreas>
                            <Legends>
                                <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="true" 

Open in new window

0
Where i can download a sample or demo application which has the following..Any link would be useful

1. Source code
2. Sample SQL file to populate the data in mysql table or json to populate NoSQL
3. Uses Ajax in the front-end to send and receive responses
0
This is a spin-off of another thread: I am needing a way to add markers to Google Map, based-on geo-coordinates from an external JSON file.  The JSON file is stored locally on my web server and is being called to display information within a map window.   Additionally, I am looking for a similar method for calling a url to display a custom marker for each location.  The URL would also be stored in the same JSON file.

Below, is my code:

function initMap() {
        var hc = {lat: 40.466442, lng: -85.362709};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: hc
        });

        var infowindow = new google.maps.InfoWindow({
            content: obj
        });

        var iconBase = "http://icons.wxug.com/i/c/k/cloudy.gif";
            var marker = new google.maps.Marker({
                position: hc,
                map: map,
                title: 'Hartford City',
                icon: iconBase
            });

        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
    }

    var downloadJSON = function() {
        $.getJSON( "ajax/GeoObs.json?_="+new Date().getTime(), function( data ) {
            var items = [];
            items.push( "<li id='Weather'>Station: " + 

Open in new window

0


https://www.mkyong.com/spring-boot/spring-boot-ajax-example/

Please go through the above link

1. Don't type any name and hit search button - Bad Request - It Comes to Error Function of Ajax - User Can't be Empty - Form Validation. Ajax response is error in this case.

2. Type "Somu" in name field and hit search button - Business Error - Returned with Success Function. Ajax response is success in this case.

3. Assume i have thrown a run time exception in getSearchResultViaAjax() as below

AjaxResponseBody result = new AjaxResponseBody();
       
        if(1==1) {
              throw new RuntimeException();
        }

The same Ajax error block is getting called.

error: function (e) {

            var json = "<h4>Ajax Response Error </h4><pre>"
                + e.responseText + "</pre>";
            $('#feedback').html(json);

            console.log("ERROR pp : ", e);
            $("#btn-search").prop("disabled", false);

        }

So for Bad Request and Any Exception which comes Out side the box comes in error block

Which one is the right approach in the follow ? If both of them is incorrect, help me with the best practice

One
====
1. Throw form validation errors as as Ajax Response is ERROR with failure message to display
2. Throw Business validation errors as Ajax Response is SUCCESS with failure message to display
3. Throw any other exception as Ajax Response…
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.