Ajax refreshes the whole page instead of a particular part - javascript

Net web services. The following code is attached to my master page using a JS. When I run the ajax call, it seems like at the end of success function, it refreshes the whole page. Rather than some particular part. I have tried using both ways, form + input submit, and normal button with click function.
$.ajax({
url: 'service url',
data: { LookupParameter: somevariable },
method: 'POST',
dataType: 'xml',
asynch: false,
cache: false,
success: function (data) {
var xmldata = $(data);
//dom manipulation code
},
error: function (e) {
}
});
Master Page
following code is embedded inside body tag. but not in content placeholder.
<form itemscope itemtype="http://schema.org/LocalBusiness" id="form1" runat="server">
<span class="input-group-addon borderRadiusZero" id="basic-addon1">
<span class="glyphicon glyphicon-question-sign"></span>
</span>
<Input ID="txt_lookup_pincode" type="number" class="form-control" min="111111" max="999999" placeholder="Enter Your Pincode" />
<span class="input-group-btn ">
<button id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button>
<input id="LookupServices" class="btn btn-primary borderRadiusZero" style="height:100%;" type="submit" value="submitM" />
</span>

The issue may be because of this line
<button id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button>
The button type is not defined here. In this case the default type that is submit will be applied.
Define the button type as button
<button type = "button" id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button>

If your JavaScript function with the Ajax call is included in the onclick handler of your button, it should return false to prevent the default action of the button:
<button id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas(); return false;" style="height:100%;">Submit</button>

You can add to the button the type "button" to suppress the default behavior
<button type="button" id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button

put the dom elements which you want to refresh after the ajax success in another div which is outside the form and do the manipulations to that div. Hope this helps!

Related

Redirect location after ajax call in a click event

The code below is supposed to
Process the delete request when the delete a tag is select
redirect to the /projects webpage.
it seems like the redirect to /projects is occurring before the delete function gets a chance to run.
Is there a best practice that I'm missing here? or is there a better way to do this?
$(document).ready(function() {
$('#delete').click(function() {
var settings = {
url: `http://localhost:3000/projects/<%= project.id %>`,
method: 'DELETE',
timeout: 0,
};
$.ajax(settings).done(function(response) {
console.log(response);
});
});
});
<form class="update-project" method="POST" action="/update-project">
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">ID</span>
<input type="text" class="form-control" name="id" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default" value="<%= project.id %>" disabled />
</div>
<a type="cancel" class="btn btn-secondary" href="/projects">Cancel</a>
<button type="submit" class="btn btn-primary float-right">Submit</button>
<a id="delete" type="delete" class="btn btn-danger" href="/projects"> DELETE </a>
</form>
I will try to answer using all the information the colleagues left in the comments.
We need to:
1 - Get the click button.
2 - Call event.preventDefault() to avoid refresh due to the <form method="POST" action=...>.
3 - Do the ajax request on the "click" event.
4 - In the ajax callback do the redirection.
Step by step:
1 - I will remove the href="/projects" from <a id="delete" type="delete" class="btn btn-danger" href="/projects"> DELETE </a>
2 - Add event.preventDefault() in the first line of the "click" callback.
3 - Add window.location.replace('/projects') in the first line of the ajax callback.
After all this it would look like:
<form class="update-project" method="POST" action="/update-project">
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">ID</span>
<input type="text" class="form-control" name="id" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default" value="<%= project.id %>" disabled />
</div>
<a type="cancel" class="btn btn-secondary" href="/projects">Cancel</a>
<button type="submit" class="btn btn-primary float-right">Submit</button>
<a id="delete" type="delete" class="btn btn-danger"> DELETE </a>
</form>
$(document).ready(function() {
$('#delete').click(function(event) {
event.preventDefault();
var settings = {
url: `http://localhost:3000/projects/${project.id}>`,
method: 'DELETE',
timeout: 0,
};
$.ajax(settings).done(function() {
window.location.replace('/projects');
});
});
})
Note: I also want to add that the HTML structure doesn't make sense with what you want to do. You are creating an HTML form, but at the same time, you want to handle the form calls via JS instead of using the native HTML form you already have there. It should be refactored to get cleaner and less buggy-prone.
Note 2: You should not use <a> tags as buttons, buttons should be used as buttons because this is what they are :)
Issue ended up being another part of my code on the server side. I needed to return the status code in the express js router.put via return response.redirect(303, '/projects');
const express = require('express');
const ProjectModel = require('../src/controller/projectController');
const router = express.Router();
const controller = new ProjectModel();
module.exports = (params) => {
router.delete('/:id', async (request, response) => {
await controller.deleteById(request.params);
return response.redirect(303, '/projects');
});
return router;
}

submit form with button outside form using ajax

I try to post a form using ajax the current code does not really work. When I press the save button the form get submitted n + 1 times. i.e After refreshing the page it submit once, next time I submit two form get submitted, third time... etc.
I have spend a lot of time researching this already (2 days) and I have not found a questions quite similar to what I am asking.
I am on a steep learning curve here so I hope someone can point out to me what I am doing wrong.
I think I might have mixed something up. The steps up to submit is.
Form values is being filled in.
A button is pressed to show a modal to confirm to submit the form (The submit button is actually inside this modal and not inside the form itself).
Form is submitted.
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide'); // close confirm modal
$('#newForm').submit(function (e) {
e.preventDefault();
let formData = $(this).serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
})
<form id="newForm">
<input type="text" id="name" name="name">
<input type="text" id="company" name="company">
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" form="newForm" id="confirmYes">Save</button>
</div>
The issue is because you are creating a new submit event handler in every click. From the description of what you want to do, you instead need to create a single submit handler when the page loads, and trigger it when the button is clicked. Something like this:
$('#newForm').submit(function(e) { // handle the submit event
e.preventDefault();
let formData = $(this).serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
})
})
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide');
$('#newForm').submit(); // trigger the submit event
});
Simply remove the $('#newForm').submit(function (e) {}); :
.submit(function (e) {}) is creating an event handler for the submit event of your form, it's not submitting it.
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide'); // close confirm modal
let formData = $('#newForm').serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
});
});
$('#confirmYes').click(function() {
let formData = $('#newForm').serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
});
);
<form id="newForm">
<input type="text" id="name" name="name">
<input type="text" id="company" name="company">
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" id="confirmYes">Save</button>
</div>

Redirecting to a div with post data

I am searching a table for specific values based on the user input which queries the database for the LIKE condition. This works perfectly but I have to manually scroll to the buttom of the page to see my filtered table. I really want to redirect the user to the div of the table underneath the page. This is the form with the search box:
<form method="post">
<div class="col-lg-6 pull-right" style="margin-right:130px; width:30%;">
<div class="input-group">
<input required type="text" class="form-control" name="search" placeholder="Search Alerts for Today...">
<span class="input-group-btn">
<button class="btn btn-default" name="searchnow" type="submit" value="Submit">Go!</button>
</span>
</div>
</div>
</form>
This code below then checks to see if the button is clicked and then sets the variable that populates the table to equals the current search result from the database.
var searchIP = "";
if (Request.Form["searchnow"] != null & IsPost)
{
searchIP = Request.Form["search"];
alertForTheDay = dbConnection.searchDashboardTable(searchIP);
// Response.Redirect("Dashboard.cshtml#search");
}
Using Response.Redirect refreshes the table back to its original state. Commenting out the Response redirect as shown above allows the filter to be possible but I have to manually scroll down the page. I want this to redirect to the id of the div in that redirect. Please what can I do?
I guess you are doing a complete server round trip. From my point of view this is unnecessary.
I would suggest to do this via AJAX.
Change the HTML like this to call an AJAX operation on your button click:
<form method="post">
<div class="col-lg-6 pull-right" style="margin-right:130px; width:30%;">
<div class="input-group">
<input required type="text" class="form-control" name="search" id="search" placeholder="Search Alerts for Today...">
<span class="input-group-btn">
<button class="btn btn-default" name="searchnow" id="theButton">Go!</button>
</span>
</div>
</div>
</form>
Handle the button click and link to your anchor on success. (Assuming that the anchor to your table is present. In your case something like Dashboard.cshtml#contact)
$.fn.gotoAnchor = function(anchor) {
location.href = this.selector;
}
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#theButton").click(function() {
$.ajax({
type: "POST",
url: "<YOUR URL>",
data: { search: $('#search').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// If everything is successful link to your anchor tag
$('#search').gotoAnchor();
}
});
});
});

Jquery form being submitted twice

I have a really strange problem. My Jquery based form appears to be submitting its self twice.
It only happens when I use the following code to submit my form:
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
When I use the following, I do not get the double submit:
<input type="submit" value="Transfer" class="btn btn-success dark" id="transfer-button"/>
Here is the code in context:
FORM:
<form class="form-horizontal hidden" id="transfer-form" novalidate>
<fieldset>
<div class="control-group">
<div> </div>
<div class="controls">
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
</div>
</div>
</fieldset>
</form>
And the JQuery code:
$('#transfer-form').submit(function()
{
event.preventDefault();
//run some error checks
if (messageArray.length !== 0)
{
//Return errors
} else {
$('#transfer-button').prop('disabled', true);
$('#transfer-spin').addClass('fa-spin');
var url ='/api/transfer';
$.ajax({
//Do the ajax call...
You need to pass the event as parameter in submit:
$('#transfer-form').submit(function(event)
Your submit function needs to receive the event object
function (event) {
...
I believe you have to specify the event variable in the function, with that you can prevent default behavior.
$('#transfer-form').submit(function(event)
{
event.preventDefault();
...
}

Jquery function not fired (html injected in second moment) [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
Sorry for no-too-much clear title.
I'm using Twitter Bootstrap Modal to edit some record.
<a class="contact" href="#" data-form="/edit/models/sms/{{ #value['fields']['id'] }}" title="Edit">
<span class="fa-stack fa-lg">
<i class="fa fa-square-o fa-stack-2x"></i>
<i class="fa fa-pencil fa-stack-1x"></i>
</span>
</a>
And this is the javascript code that open the Modal:
$(".sms-model").click(function(ev) { // for each edit contact url
ev.preventDefault(); // prevent navigation
var url = $(this).data("form"); // get the contact form url
$("#smsModelModal").load(url, function() { // load the url into the modal
$(this).modal('show'); // display the modal on url load
});
$("#smsModelModal").modal('show'); // display the modal on url load
return false; // prevent the click propagation
});
Finally this is the form injected inside the modal:
<div class="modal-body">
<form role="form" method="post" class="sms-model-form" action="{{ #SERVER.REQUEST_URI }}">
<fieldset>
<legend class="sr-only">Edit</legend>
<input type="hidden" name="edit_id_model" value="{{ isset(#sms_model) ? #sms_model[0]['fields']['id']['value'] : '' }}" />
<div class="form-group">
<label for="title">{{ #lng_label_sms_title }}</label>
<input type="text" class="form-control required-field" name="title" value="{{ isset(#sms_model) ? #sms_model[0]['fields']['title']['value'] : '' }}"/>
</div>
<div class="form-group">
<label for="text">{{ #lng_label_sms_text }}</label>
<textarea class="form-control" name="text" class="required-field">{{ isset(#sms_model) ? #sms_model[0]['fields']['text']['value'] : '' }}</textarea>
</div>
<button type="submit" class="btn btn-white pull-right">
<i class="fa fa-plus-circle"></i> {{ isset(#sms_model) ? #lng_btn_edit : #lng_btn_add }}
</button>
<input type="submit" class="btn btn-primary" value="Test" />
</fieldset>
</form>
</div>
Everything functions as a charme. Now I would submit the form via AJAX.
So I'm adding this:
$('.sms-model-form').on('submit', function(e) {
console.log('test on submit....');
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize()+'&ajax=TRUE',
context: this,
success: function(data, status) {
$('#smsModelModal').html(data);
}
});
return false;
});
But form is submitted via regular mode, and not via AJAX. I.e. I don't have neither the event logged in console.
I'm thinking that this is because the form is injected in a second moment in the page and not at
$(document).ready(function() {
Am I right? How I can solve my issue?
You almost certainly need to set up your event handler via delegation:
$(document).on('submit', '.sms-model-form', function(e) {
That attaches a handler at the root of the DOM to catch bubbling "submit" events. Because you're adding your modal dialog content after your code runs, if you do it your way the code will simply have no effect; the ".sms-model-form" selector will match nothing, so no event handler will be attached anywhere.
Using the above form of .on(), you ensure that events involving DOM substructures added dynamically will still be handled as you desire them to be.

Categories

Resources