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

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
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
I have an ajax call within a function and when I return the result of the ajax call from the function it comes back undefined, what am I doing wrong here ?
	function get_applications(){
		var application_list = "";
		
		$.ajax({
			url: '../ajax/some_file.php',
			contentType: false,
			processData: false,
			type: 'POST',
			success: function(data){
				application_list = data;
			//	console.log(data);
			},
			error: function() { 
			//	console.log('NOT updated'); 
			}			
		});
		return application_list;
	}

Open in new window

0
I have a login script, instigated by a button in the header that calls up a form in a modal window which, on submit, processes  using jQuery AJAX, On successful login, the script returns to the original page, where it calls up another modal window with utilities only available to the logged in user. I have tried using a query variable, and I have also tried using a global but, for some reason, both fail.

Code has been working fine to just log the user in and return to the page. The page name is held in a PHP variable:
$CurrentPage = empty($_REQUEST['CurrentPage']) ? $_SERVER['HTTP_REFERER'] : $_REQUEST['CurrentPage'];

Open in new window


In the AJAX result I have tried using the following to attach a query string.
<?PHP
echo('window.location.href = "'.$CurrentPage.'?ET=1";');
or
echo('window.location.search("'.$CurrentPage.'"+"?ET=1");');
echo('window.location.search("'.$CurrentPage.'?ET=1");');
?>

Open in new window

The page needs to reload in order to show the user is logged in in the header.
When I could not get the query to work, (The string does not appear) I tried using a global variable:
<script>
window.ETSHOW = "Active";
<?PHP
echo('window.location.href = "'.$CurrentPage.'");');
?>
</script>

Open in new window


The code that contains the opening of the logged-in user utility menu is contained in the footer of the page, so I did this when attempting to use the query string:
<script>
<?PHP
if(!empty($_REQUEST[ET]))
{
   // Run function to clear the URL, then
   var hUrl    = "etselect.php";
   var hTitle  = "Utilities";
   var w       = 630;
   var h       = 630;
   LVPopup(hUrl,hTitle,w,h); // Opens the model window
}
?>
</script>

Open in new window

Attempting to use a global variable, I have done this:
<script>
if(typeof window.ETSHOW !== 'undefined' && window.ETSHOW != null) 
{
   ETSHOW = null;
   var hUrl    = "etselect.php";
   var hTitle  = "ExpressTRAX";
   var w       = 630;
   var h       = 630;
   LVPopup(hUrl,hTitle,w,h);
}
</script>

Open in new window

I've not used JavaScript globals much, but I do not understand why that is not working, and I am really puzzled that the query variable is not attaching to the URL.

Process Order
(Header and Footer are includes that appear on every page - But not in the modal windows)
  1. User selects the Login button in the header. This opens a login form in a js modal window.
  2. Form submit uses Ajax to authenticate the login.
0
<form id="restaurantForm">
            <input type="text" id="name" class="req" placeholder="Restaurant Name" />
            <input type="text" id="address" class="req" placeholder="Address" />
            <input type="text" id="suite" placeholder="Suite"/>
            <button type="button" onclick="sendForm()">Done</button>
            <button type="button">Cancel</button>
</form>


I have this code doing an ajax post in jQuery

const sendForm = () => {
const name = document.querySelector('#name');
const address = document.querySelector('#address');
const suite = document.querySelector('#suite');
   
$.post('AddRestaurant.aspx', { name: name.value, address: address.value, suite: suite.value }, () => {
    $("#dbContent").html(html); } );

Since it's a post, how can I automatically grab the form field values like a normal form post submittal without having to add all of the form field values to the second arg of $.post? Basically, I want to put one value as the second arg of $.post, that will have all form fields and their values Do I have to make the button of type "submit" and then e.preventDefault() and then have to serialize the form results somehow and add the result as the second arg?
0
Hi,

I have page and on body tag I am calling the ajax call.
The process takes sometime. And I wanted to add loader to the page in the mean time loader process the request.

Please advise to add loader.

Thanks

</head>
<body><!-- <===== PLEASE NOTE THIS IS YOUR BODY TAG -->
<script>
    $.ajax({
        url: '/der/surface/userHasSession',
        data: { currURL: window.location.pathname + window.location.search },
        type: 'GET',
        xhrFields: { withCredentials: true },
        accept: 'application/json',
        async: false
    }).done(function (userdata) {
        console.log('Done');
    }).fail(function (jqXHR, textStatus, error) {
        console.log('Session Check Fail: ');
    });
</script>

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.