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.

I have a simple form:
<div id="notify-alert"></div>
<form method="post">
<input type="hidden" name="memberID" value="5">
<input type="hidden" name="requestID" value="23">
<input type="button" name="submitNotify" value="Notify" onclick="SubmitNotification();">
</form>

Open in new window


the SubmitNotification function is as follows:
function SubmitNotification(){
	//these next four lines were to check what was going on
	var thisData = $(this).closest('form').serialize(); 
	console.log('begin');
	console.log(thisData);
	console.log('end');
	$.ajax({
		type: "POST",
		url: "ajax-notify.cfm",
		data: $(this).closest('form').serialize(),
		dataType: "text",
		success: function(data, status) {
			$('#notify-alert').html(data);
		},
		error: function(data, status) {
			$('#notify-alert').html(data);
		}
	});
};

Open in new window


$(this).closest('form').serialize(); is just returning an empty string. I've found several questions about how to serialize the surrounding form of a button and this appears to be to the correct way... where is this going awry? (I've also tried $(this).parent('form') with the same issue. Incidentally, I'm not using an ID for this because there are multiple forms on the page created by a loop.) Thanks!
0
I would like to get an ajax call working for an autocomplete text field, it fetches players' names.  In the same query that gets the names I can retrieve the phone number of each player.  

What I want to do, is that when the user picks the player from the list, I want to flag up if the chosen player has no number stored. I don't want to show the number on the screen at all.

What I have done so far can be tested at http://www.col-b.uk/fines_text.php

I have little knowledge of javascript, so I have included first_name, surname and tel_mobile fields as one string of data to be returned from the selection.  

1. I need to show/hide the 'No number stored' message at the right times.
2. I never want to show the number on the screen.
3. In this test data, the only person with no number is Steve Johnson.

Data
DROP TABLE IF EXISTS players;

CREATE TABLE players (
  id                int AUTO_INCREMENT NOT NULL,
  first_name        varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  surname           varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  tel_mobile        varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci,
  /* Keys */
  PRIMARY KEY (id)
) ENGINE = MyISAM;

INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Alan','Johnson','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Albert','Johnson','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES 

Open in new window

0
I have an Ajax call;

  var xhr= new XMLHttpRequest();
        // this executres when the ajax request in completed, i.e. the results
        // are sent back from php
        xhr.onload = function (){
           document.getElementById("myLocationImage").src=this.responseText;
        }
        xhr.open("POST", "latLongToMap.php");
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send("lat="+$latitude+"&lon="+$longitude);

Open in new window


This sends latitude and longitude coordinates from an autosuggest drop down box to my php code at latLongToMap.php.

latLongToMap.php does a load of processing and creates an image file that is returned to the ajax request by

echo ($img);

Open in new window


This code then changes the img src of

  <img id="myLocationImage" src="worldmap-withdot.jpg" width="150" height="150">

My problem is that the ajax request does work, and does change the file on the server. But for me to see the image, I have to CONTROL-F5 my browser.

What do I need to do so I see the new image file without having to manually refresh my browser?

I have attached an animated gif (I hope it works) showing my problem. When the gray image appears, I have to CONTROL-F5 to see the new image.

My ajax problem in real time
Please help, I've played around with various ideas I've found on the internet, but with no joy.

Thankyou
James

PS: Note I'm aware it always says 'Toulouse' by the label, I haven't done that bit of my code yet...
0
This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method. I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):

$(document).ready(function () {
        $('#PurchaseOrderLineItemAddId').click(function () {
            var aPurchaseOrderViewModel = @Html.Raw(Json.Encode(Model));    
            var selectedVendorText = $('#ddlvendors option:selected').text();
            var selectedVendorValue = $('#ddlvendors option:selected').val();  
            var LineItemReqJsonObj = {};

            LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
            LineItemReqJsonObj.VendorText = selectedVendorText;
            LineItemReqJsonObj.VendorValue = selectedVendorValue;

            var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';

                $.ajax(
                    {
                        type: "POST",
                        //data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
                        //data: aPurchaseOrderViewModelStr,
                        data: dataToPass,
                        url: '@Url.Action("PurchaseOrderAddItem")',
            

Open in new window

0
I m sending an ajax call in below method after return the success message i want to clear the form in same page so form also get cleared and success
 message also print in jsp page please help me out on this thanx a ton in advance.
 
 
 
 $(document).ready(function() {
	$("#data").click(function(evt) {
		evt.preventDefault();
		 if(save()){
			$.ajax({
				url: "Test.jsp",
				type: "post",
				data: {
				pS:$('#pS').val(),
				pType:$('#pType').val(),
				pCode:$('#pCode').val(),
				mYear:$('#mYear').val(),
				pDate:$('#pdate').val(),
				ppDate:$('#ppdate').val(),
				bDate:$('#bdate').val()},
				success: function(responseFromServer) {
	            	$.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
	                    $('#content').html(resultMessageKey);
	                });
	             },
	            error: function() {
	                alert(" Ajax call Failed to Update Values into Database");
	            }
			});
		 }
		 else
			 {
			 
			 }
	});
});

Open in new window

0
Hi Experts

Could you point why a Controller method code is subtly returning to a jquery ajax without running and returning OK to JS ?

Accordingly to:

Vitrine.prototype.salvar = function(){
    
  console.log ('JS salvar');
  
  $.ajax({
    url: '/vitrine/salvar',
    
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};

Open in new window


and Controller method:


 public function salvar(Request $request){
   
	 //Forcing an error
	 //aaa;
	
	
	// Otherwise subtly exit with no traces.
	info('xxx');
   
	dd('aaa');

	$id=$request->input('id');
	$url=$request->input('url');
	$inicio=$request->input('inicio');
	$termino=$request->input('termino');

	$titulo = $request->input('title');
	$descricao = $request->input('description');
	$pontuacao = $request->input('points');

	try{
		if($id != '' &&  $id > 0){
		  $vitrine = Vitrine::find($id);
		}

		if(empty($vitrine)){
		  $vitrine = new Vitrine();
		  $vitrine->created_at=new \DateTime();
		}
			
		$vitrine->title = $titulo;
		$vitrine->description = $descricao;
		$vitrine->points = CustomFuncs::brancoParaNulo($pontuacao);
		$vitrine->url = $url;
		$vitrine->validity_start = empty($inicio) ? null : CustomFuncs::formatarDataUS($inicio);
		$vitrine->validity_end = empty($inicio) ? null : CustomFuncs::formatarDataUS($termino);
		$vitrine->updated_at=new \DateTime();
		
		info($vitrine);
		
		
		$vitrine->save();

	} catch (\Exception $e) {
		return response()->json(new Resultado(true,'','Erro ao salvar o vídeo'), 400);
	}

	return response()->json(new Resultado(false,'','Vídeo cadastrado com sucesso'));

}

Open in new window



The forced error:

img015
Thanks in advance!
0
I have a HTML5/js web page that was working fine and stopped working a short time ago.  I have placed this web page temporally at: https://www.barnwellmd.com/temp/test.html so I can delete it after I close this question (it saves files on my server and sends me an email).  

The problem is when a user clicks on "Send to Dr. Office" a popup shows "<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>" and nothing is sent.

That button calls the sendCanvas() function:
function sendCanvas()
{
      if (checkFields()) return;
      clearGray();
      createPrint();
      var testCanvas = document.getElementById("imageView");  
      var canvasData = testCanvas.toDataURL("image/png");
      //alert(canvasData);
      var ajax = new XMLHttpRequest();
      //alert ('https://www.barnwellmd.com/Uploadroutines/uploadbase64.php?name=' + document.form.ptname.value.replace(/ /g,"_"));
      ajax.open("POST",'https://www.barnwellmd.com/Uploadroutines/uploadbase64.php?name=' + document.form.ptname.value.replace(/ /g,"_"),false);
      //ajax.open("POST",'https://www.barnwellmd.com/Uploadroutines/uploadbase64.php',true);    
      ajax.setRequestHeader('Content-Type', 'canvas/upload');
      //ajax.setRequestHeader('Content-Type', 'application/upload');
      ajax.onreadystatechange=function()
      {
            if (ajax.readyState == 4)
            {
                  alert(ajax.responseText);
                  …
0
Hi,

I'm creating a search page

1. on the page there is a multiselect dropdown list
2. I select some options from the list
3. I click on the submit button
4. after submitting the page my selection will get cleared out

How can I get my selection back once I click on the submit button?


 $('#SelectedVersion').multiselect({
            onInitialized: function (option, checked) {
                var dropdown = $('#SelectedVersion').siblings('.multiselect-container');
  
               //Here I want to reselect the options that I have already selected after submitting my form
               onInitialized: function (option, checked) {
                var values = [];
                var $SelectedOptions = $(this).find('option:selected');
                $SelectedOptions.each(function () {
                    values.push($(this).text());
                });
            },

            enableFiltering: true,
            buttonWidth: '350px',
            maxHeight: 200,
            enableCaseInsensitiveFiltering: true,
        }); 

Open in new window




<td>
                       @Html.DropDownListFor(m => m.SelectedVersion, new SelectList(Model.VersionList, "Value", "Text"), new { @multiple = "multiple" } )
                    </td>

Open in new window

0
What is the best way to retrieve a variable list of text inputs and values and send via jQuery AJAX to MVC controller as a virtual ICollection on a parent object?

My markup will look something like this:  (but the number of inputs will be dynamic)

<div class="questionPanel">

.<!-- ..other markup and elements here  -->

<input name="item.answerChoiceText" class="form-control txtAnswerChoice text-box single-line" type="text" value="Red" >
<input name="item.answerChoiceText" class="form-control txtAnswerChoice text-box single-line" type="text" value="Blue" >
<input name="item.answerChoiceText" class="form-control txtAnswerChoice text-box single-line" type="text" value="Green" >
</div>

Open in new window


Then my jQuery AJAX call:  ( $(this) refers to the .questionPanel div)

$.ajax({
	type: 'POST',
	cache: false,
	async: false,
	url: '/Question/Insert',
	dataType: 'json',
	data: {
		questionId: $(this).attr('questionid'),
		questionText: $(this).find('.txtQuestionText').val(),
		questionType: $(this).find('.selQuestionType').val(),N
		showCommentsBox: $(this).find('.ckShowCommentsBox').prop('checked'),
		answersRequired: $(this).find('.txtAnswersRequired').val(),
		isActive: $(this).css('display') == 'none' ? false : true,
		order: $(this).css('display') == 'none' ? 0 : orderCount,
		surveyId: $('#surveyBuilderWrapper').attr('surveyid'),
		AnswerChoice: ????????	NEED TO SEND LIST HERE  ??????
	},
	success: function (result) {
	},
	error: function (xhr, ajaxOptions, error) {
	}

Open in new window


And my MVC controller is expecting a Question object, which contains a collection of Answer Choices:

public JsonResult Insert(Question question, int order, int surveyId)
{
        // process the insert here..
}


public partial class Question
{
	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
	public Question()
	{
		AnswerChoice = new HashSet<AnswerChoice>();
	}

	public int questionId { get; set; }

	[Required]
	[StringLength(500)]
	public string questionText { get; set; }

	public int questionType { get; set; }

	public bool showCommentsBox { get; set; }

	public int? answersRequired { get; set; }

	public bool isActive { get; set; }

	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
	public virtual ICollection<AnswerChoice> AnswerChoice { get; set; }

}

Open in new window


Thanks!
0
i have basic HTML form
Included one text box and one box for upload file

Do you have a sample code I can read to
Use JavaScript and Ajax to post both data into Mvc controller in net?

Thanks
0
Below ajax code working but now I have to add file upload together.
Is it possible to submit form data such as text box and upload jpg in one ajax call?


<div class="row">
                <div class="col-fs-12">
                    <input type="file" />
                </div>
            </div>

$.ajax({
                                url: ApiName,
                                datatype: "text",
                                data:
                                {
                                    'blogid': blogID,
                                    'blogsubject': blogsubject,
                                    'blogbody': body.replace("'"," "),
                                    'createdby': '@System.Configuration.ConfigurationManager.AppSettings["MemberIDDefaultContentWriterName"]',
                                    'createdon': blogdate,
                                    'stage': blogStage,
                                    'actiontype': blogActionType,
                                    'blogurl': blogFileName,
                                    'memberid': '@System.Configuration.ConfigurationManager.AppSettings["MemberIDDefaultContentWriter"]',
                                    'blogtype': 'Event',
                                    'eventtype': eventType,
                                    'eventid': eventID,
                                    'eventIcon': eventIcon
                                },
                                

Open in new window

0
I have written an autosuggest function in Javascript (plain javascript).

This autosuggest is a single box that searches a database table of about 3.5 million cities (including towns and villages) - the database actually also details region, and country but this isn't important.

Asking AJAX requests to search such a database takes many seconds per request and this is obviously too slow.

My immediate thoughts on how to speed this up as as follows:

Create separate database tables corresponding to each letter of the alphabet, i.e. 26 tables.

If the first letter the use types is 'a', consult the table with places beginning with 'a' from that point on.

In theory this would make the request 26 times faster?

My first question is:

Is the a sensible approach or am I missing something?

Furthermore, if that is still not fast enough,

take the table, for example all places beginning with 'a', and split that into a further 26 tables; i.e.

All places beginning with aa, ab, ac, ad........ az

My second question is:

Is this a sensible and logical approach? Is there a limit to the number of tables on can have in mysql (there would be 26x26 = 676 tables in this case)?


I am aware of indexing tables to speed them up, so the approach above would be 'on top of' indexing the tables.

I look forward to hearing from you.

thank you
James
0
Hi,

I have a textarea with the following list in it 736 4937 587 795 955

1. enter this list in a textarea 736 4937 587 795 955

2.. run my jquery: the output will be this   736, 4937, 587, 795, 955

   var str = $('#ItemList').val();
            str = $('#ItemList').val().replace(/(?:\r\n|\r|\n|\s)/g, ', ');
            $('#ItemList').val(str);

Open in new window



3.  now the user decide to run my jquery again: the user will get this output for running my query again   736,, 4937,, 587,, 795,, 955

4. How can I fix the jquery to say:

if the data in my textarea already has a comma and space between them then don't do anything.

only separate my list if there is no comma followed by a space between them.

I just don't wont the double comma if the user kept on clicking the button.


Thank you for your help,

Lulu50
0
I am trying to pass in the value ASC to the database for a query but the error I get is:

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ASC''
Here is what I am sending via Ajax for testing:

var sort = 'ASC';
$.ajax({
        url: url + '/Admin/test',
        type: 'POST',
        dataType: 'json',
        data: {sort: sort}
    })

Open in new window


Controller:

    $data = [

        'sort' => $_POST['sort']
    ];

$reminders = $this->Model->Sort($data);

Open in new window


DB Query:

$this->db->query("SELECT fields
FROM tables
ORDER BY name :sort ");
$this->db->bind(":sort", $data['sort']);
$results = $this->db->resultSet();
return $results;

Open in new window

0
My login form opens in a modal window (Lightview, which is a jQuery modal). The author has abandoned support, but the modal works great for multiple needs.

I keep a variable, which holds the full path to the current page. On successful login, which is authenticated with an AJAX script, I simply do a relocate to the current page as "parent". That page needs to refresh in order to note the user is logged in and provide a logout button. But it also needs to pull up another model with menu selections for the logged in user. In order to open that menu, I sent a variable to the url, which is picked up in the footer. This all works fine in other browsers, but not in IE11.

So, the process is
1. User presses login button. This brings up the login form in Lightview. (Full path of CurrentPage is held in variable
2. Form is submitted to an AJAX authentication.
3. On success, location is directed back to the current page using
   window.parent.location.href = data.CurrentPage+"?Exp=1";

Open in new window

In browsers other than IE11, this closes the model window, refreshes the current page, the Exp is picked up by a javascript function, and the logged-in menu appears in another modal.

I have tried every way imaginable, including replace, assign, window.top ... nothing seems to work in IE11. It simply does nothing, The page does not relocate and the url does not go to the address bar. Even tried history.go(-1). Any known solutions to this problem?
0
So I have a login area which only seems to work in Firefox

its setting the variables but I appear to be losing the session somehow

from the login page, I do an AJAX call to the login.php file which checks the database and the status of the user, if all is good, I return true and AJAX changes the page location to the secured area. at the top of each page in the secured area, I check for $_SESSION['userID'] if its not set or empty it brings you back to the login page which is happening in every browser except for firefox ???
0
Im posting 2 variables using formdata via ajax

my php does what it needs to do and then tries to re-direct header('location: someotherwebsite.com')

Ajax is returning an error. page does not re-direct

Im not expecting any results

what im basically doing in the script is unsetting session variables session_destroy() then moving them away from the current page back to the home page
0
i have 3 fields in tabular formate like below

<tr>
    <th>Check/UnCheck</th>
      <th>MYear</th>
      <th>P Date</th>
      <th>Q Date</th>
      <th>B Date</th>
  </tr>
  <tr>
    <td align="top">
      <input type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="1" value="" size="50">
    </td>
    <td align="left">
      <input class="inputText row1" type="text" name="mYear" id="mYear"  value="2020">
    </td>
    <td>
      <input class="date row1" id="pDate1" name="dob" type="date" value="2020-01-01" />
    </td>
    <td>
      <input class="date row1" id="qDate1" name="dob" type="date" value="2020-01-01" />
    </td>
    <td>
      <input class="date row1" id="bDate1" name="dob" type="date" value="2020-01-01" />
    </td>
  </tr> 
  <tr>
    <td align="top">
      <input type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="2" value="" size="50">
    </td>
    <td align="left">
      <input class="inputText row2" type="text" name="mYear" id="mYear"  value="2020">
    </td>
    <td>
      <input class="date row2" id="pDate2" name="dob" type="date" value="2020-02-01" />
    </td>
    <td>
      <input class="date row2" id="qDate2" name="dob" type="date" value="2020-02-01" />
    </td>
    <td>
      <input class="date row2" id="bDate2" name="dob" type="date" value="2020-02-01" />
    </td>
  </tr> 
</table>  

Open in new window




1 ) i want to do first date filed (pDate1) when click in date picker from system date + 7 days are only enable to pick all past date are not enable to pick in date picker
2 ) in second field (qDate1) only after pDate1 is enable to pick in date picker
3 ) in second field (bDate1) only after qDate1 is enable to pick in date picker

please let me know if i want to describe more .
0
how can i send ajax call to database and retrieve a table having 5 columns data as json  and render in jsp to display .
0
Hi I m populating data like below in tabular foarmat . my requirement is like while submiting ajax call before that
each row which is cheked having 3 date field need to validate Q Date should greater then P Date ,
B Date sholud be greater then Q Date and P Date. pelase help me out with some code snippet.


<table align=center>

<tr>			<th>Check/UnCheck</th>
                <th>MYear</th>
                <th>P Date</th>
                <th>Q Date</th>
                <th>B Date</th>
</tr>
<%for(int i=0 ; i<mVector.size();i++)
{
	
%>
 <tr>
<td align="top">
<INPUT type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" data-row="row<%=i%>" value="" size="50">
</td>
<td align="left">
<input class="inputText row<%=i%>" type="text" name="mYear" id="mYear"  value="<%=mVector.elementAt(i)%>">
</td>

				<td>
		            <input class="date row<%=i%>" id="pDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(0)==null?"":oldValues.elementAt(0))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="qDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(1)==null?"":oldValues.elementAt(1))%>" />
				</td>
				<td>
		            <input class="date row<%=i%>" id="bDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(2)==null?"":oldValues.elementAt(2))%>" />
				</td>

</tr> 
<%}%>

</table>

Open in new window



ajax call is like below


$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	

	$('.chkValues').on('click', function() {

		//get values of dates
		var array = [];
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + $row).each(function() {
			array.push($(this).val());
		});
		$('#btnSubmit').click(function(evt) {
    	evt.preventDefault();
    	$.ajax({
            type: "POST",
            url: "Test.jsp",
            data: {array : array},
            success: function(responseFromServer) {
            	 $.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
                    $('#content').html(resultMessageKey);
                });
    	    	//getClearDateValues();
    		
            },
            error: function() {
                alert(" Ajax call Failed to Update Values  into Database ");
            }
        }); 
		});

	});

});

Open in new window

0
Hi In below function i m calling one validate function save()
if save() execute and give all values validated then ajax call go
other wise ajax call don't go . in below code save function is working
perfectly but when it gives no validation error ajax call is not going.
please help me out to recify this.


$(document).ready(function() {
	$("#save_data").click(function(evt) {
		evt.preventDefault();
		alert("succeess");
		if (save()){
			$.ajax({
				url: "Test.jsp",
				type: "post",
				data: {
				pS:$('#pS').val(),
				psT:$('#psT').val(),
				pC:$('#pC').val(),
				mY:$('#mY').val(),
				pDate:$('#pDate').val(),
				pdDate:$('#pdDate').val(),
				bDate:$('#bDate').val()},
				success: function(responseFromServer) {
	            	$.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
	                    $('#content').html(resultMessageKey);
	                });
	                //$('#content').html("Date Confguration Saved");
	    	    	//getClearDateValues();
	    		
	            },
	            error: function() {
	                alert(" Ajax call Failed to Update Values into Database");
	            }
			});
		}
	});
});

Open in new window

0
Hi i am sending ajax request to java servlet on success ia m prining the response to servlet and sending back as ajax response
but after executing it gives error like below -

jquery-1.9.1.min.js:3 Uncaught TypeError: Cannot use 'in' operator to search for '72' in


{"Request Processed":"Request Processed"}
0
How can i reload the page with success message when ajax response will get from java controller .
Case - i am sending an ajax request to java controller it is successfully going to java controller i am setting a response in controller and revert it back to jsp . while success i want to reload the page with success message which i already set in java controller.
0
Hi,

I am getting CORS error in my website. Even though I am getting status 200 in network tab as CORS was allowed for the domain.

jquery-2.1.4.min.js:4 Access to XMLHttpRequest at 'https://authuat.mysite.com/api/users' from origin 'http://etgsit.hrt.uyetr.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In Nework tab, I am getting status 200 for the API https://authuat.mysite.com/api/users as CORS was allowed for domain
http://etgsit.hrt.uyetr.com

Code as below:
$.ajax({
        url: 'https://authuat.mysite.com/api/users',
        type: 'GET',
        xhrFields: { withCredentials: true },
        accept: 'application/json',
        async: false
    }).done(function (data) {

        console.log(data);

    })
        .fail(function (jqXHR, textStatus, error) {

            console.log('falied');
        });

Open in new window


Please advise on this.

Regards,
0
Requirement Description Imagehow can i send dynamically created fields through ajax to servlet?

i have a jsp page where i fetch data from a table and display there are 3 date fields

all row having checkbox when i click on chekbox new date value should go to servlet through ajax.
code are below -

<table align=center>

<tr>			<th>Check/UnCheck</th>
                <th>MYear</th>
                <th>Date1</th>
                <th>Date2</th>
                <th>Date3</th>
</tr>
<%for(int i=0 ; i<mYearVector.size();i++)
{
	
%>
 <tr>
<td align="top">
<INPUT type="checkbox" class="chkValues" id="ckbCheckAll" name="chkBox" type="checkbox" value="" size="50">
</td>
<td align="left">
<input class=inputText type="text" name="mYear" id="mYear"  value="<%=mYearVector.elementAt(i)%>"  readonly>
</td>

				<td>
		            <input class="date1" id="payrollCutOffDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(0)==null?"":oldValues.elementAt(0))%>" />
				</td>
				<td>
		            <input class="date2" id="payrollPaymentDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(1)==null?"":oldValues.elementAt(1))%>" />
				</td>
				<td>
		            <input class="date3" id="inactiveDate<%=i%>" name="dob" type="text" value="<%=(oldValues.elementAt(2)==null?"":oldValues.elementAt(2))%>" />
				</td>
</tr> 
<%}%>

</table>

Open in new window

0

AJAX

12K

Solutions

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.