ajax call response is forwarded to new html page on browser - javascript

I am trying to write a ajax call in response I am passing back a html string
I am setting this html string as div content. it is working but once the div is updated request is forwarded to new page. I am unable to figure it out.
here is the html code -
<div id="basicdetailsdiv" class="row"><br>
<form:form id="basicdetailsform" method="post" modelAttribute="basicdetailform" action="updatebasicdetails"><br>
<div class="col-sm-6"><br>
..... ...... .....<br>
...... ..... .... <br>
<div id="editbasicsavediv" class="col-xs-5 control-label"> <a id="editbasicsavelink" class="btn vd_btn btn-xs vd_bg-yellow"> <i class="fa fa-pencil append-icon"></i> Save </a> </div>
</form:form>
<div>
.js code
jQuery("#editbasicsavelink").click(function () {
jQuery.ajax({
type: "POST",
url: "updatebasicdetails.xml",
dataType: "html",
data: $("#basicdetailsform").serialize(),
success: function (response) {
alert(response);
alert(response.responseHtml);
alert(response.responseText);
$("#basicdetailsdiv").html(response);
//element.innerHTML = resp.responseText
alert("Details saved successfully!!!");
// XMLHttpRequest.abort();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
so once the page is updated with response, then request forwards to a new url
localhost:8080/test/updatebasicdetails
this page has same html response what I am receiving from ajax call response.
where I am making mistake????
method code -
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String processForm(#Valid com.mrg.form.BasicDetailsForm bdForm, Model model, HttpServletRequest request
) {
System.out.println("basic details save start");
// service call here to read entity object from db which is data
model.addAttribute("basicdetailform", bdForm);
return getBasicDataResponse(data);
}
getBasicDataResponse(data) is private method which returns a string. data is jpa entity object. inside method stringbuilder to set the values in html string and returns a whole html string with new value.

thnx for your help.
it was my stupid mistake, i missed to remove a js method
inside which on same link click i was submitting the form.
so after executing the given ajax call it was executing that another block and hence submitted the form..what an idiotic mistake. forgive me for that! thnx all.

Try this one
jQuery("#editbasicsavelink").click(function (e) {
e.preventDefault();//this will stop page from refreshing
jQuery.ajax({
//ajax code
)}
});

Check the type of your button ( id = "editbasicsavelink" ). If the type is "submit", change it to button.
(Or)
Add "return false;" in the callback function to prevent the form submission.

Your callback is not getting bound to the html element I guess.. make sure to bind it after the document is completely loaded. add id=editbasicsavelink to your button and make sure to call event.preventDefault() as it'll stop the default action.
jQuery(document)
.ready(function() {
jQuery("#editbasicsavelink")
.on('click',function(event) {
jQuery.ajax({
//ajax code
});
});

Related

How do I insert a PartialView into a normal View using an Ajax-Function in ASP.NET Core 3?

This is the site.js code I am using to insert the PartialView into the main View.
$("#btn2").click(function () {
$.ajax({
url: "/Home/RefreshDoors",
datatype: "text",
type: "POST",
success: function (data) {
$('#DoorBox').html(data);
},
error: function () {
$("#DoorBox").html("ERROR");
}
});
});
I want to place the resulting table inside a box (div with the id="DoorBox") however as a result I get a raw view of the returned Door-Json-Objects:
(imgur-link to screenshot)
This is the div-code inside the view:
<div id="DoorBox">
</div>
This is the code from the HomeController I use to render the PartialView:
[HttpPost]
public PartialViewResult RefreshDoors()
{
return PartialView("_Doors", RefreshDoorsFunction().Result);
}
How do I get the code to insert the PartialView (just a table with the properties of the door-model displaying the doors)) to render within the div-box (without refreshing the page)?
Edit: Here is the code from the RefreshDoorsFunction():
public async Task<List<NewDoor>> RefreshDoorsFunction()
{
string token = await _auth.GetTokenAsync();
_doorList = SecureRestCall.GetDoorListAsync("https://exampleapi.azurewebsites.net", token);
return _doorList.Result;
}
I got the answer. Turns out I'm just stupid: I used the wrong button to test the ajax function (wrong id assigned to the button). It works now. Sorry for wasting some people's time.

Calling same controller's method using ajax GET and POST type

Hi I am a newbie to Grails and Groovy. Please help me to solve the below issue related to calling controller's method using ajax call.
The scenario behind the code is to recover the password using the username whenever the user is unable to remember the password. I have explained the code flow in detail below.
Application begins with the below auth.gsp page:
<form action='${postUrl}' method='POST' id='loginForm' autocomplete='off'>
<input type='text' name='j_username' id='username'/>
<input type='password' name='j_password' id='password'/>
<input type='submit' id="submit" value='${message(code: "default.button.login")}'/>
<g:message code="etranscripts.forgotPassword"/>
</form>
When I click on the Forgot password link of the anchor tag, it will call the below ajax method:
<script>
$(document).ready(function () {
$('#recovery-link').click(function () {
var url = $(this).attr('recovery-url')
$.ajax({
url: url,
dataType: "html"
}).done(function (html) {
$('#loginForm').replaceWith(html)
$('#sign-in-instruct').text('<g:message code="js.resetEnterName"/>')
}).fail(function (jqXHR, textStatus) {
console.log("Request for url failed: " + url)
})
event.preventDefault()
return false
});
});
The controller method for the above call is as below.
def recoverPassword = {
println "RecoverPassword method of ctrl....."
if (!request.post) {
// show the form
render(template: "recoverPassword" )
return
}
//some other stuff based on the input conditions.
The successful output template for the above ajax call is:
<div id="recover-password" >
<ul>
<li>
<span><g:textField name="username" id="username" value="" /></span>
<input type='submit' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>
</li>
</ul>
Till here my code works perfect. But the issue begins from here.
i.e When I enter some value in the username field of the template and click on submit, it should call the below ajax method.
$(document).on('click', '#submit-username-link', function (event) {
var url = $(this).attr('recovery-url')
var username = $('input#username').val();
$.ajax({
url: url,
type: "POST",
data: {username:username},
dataType: "json"
}).done(function (responseJson) {
$('#sign-in-instruct').text(responseJson.message)
$('div.copyright').css('margin','74px 0px 0px 140px')
$('#home-link').show()
if ( responseJson.status == 'success') {
$('#recover-password').remove()
}
}).fail(function (jqXHR, textStatus) {
$('#recover-password').remove()
$('#sign-in-instruct').text(textStatus)
console.log("Failed to send the email " + textStatus)
})
event.preventDefault()
return false
});
The thing is, url refers to the same method of the controller but the only change is POST type is used and that will be taken into consideration inside the method using if conditions.(i.e some other stuff of the controller)
These GET and POST type of method calls are configured as shown below in the URLMappings.groovy file.
"/recoverPassword/recoverPassword"(controller: 'recoverPassword') {
action = [GET: "recoverPassword", POST: "recoverPassword"]
}
The whole summary of this question is, for the same method of controller, GET request is working but POST type of ajax call is not able to reach the controller's method.
Am I doing anything wrong over here? Please help me to solve this issue. Thanks in advance :-)
Overcomplicated. Why don't you use separate function in controller for GET (rendering the form) and separate function for POST (for handling the recovering the password)?
Check out also https://en.wikipedia.org/wiki/KISS_principle
Change input Type submit to button
<input type='button' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>

jQuery ajax doesn't work with generated markup

We have a search functionality in our application, when user types in something, the result will be generated based on the filter and displayed on page.
Here's the dynamic result after each keyup:
htmlResult = `
<li>
<div>
<img src='${user.avatar}' width='80' alt='${user.fullName}' />
</div>
<a tabindex='0'
class ='btn2'
data-html='true'
data-toggle='popover'
data-content="<div class='list-group'>add
</li>
`;
Here are the event handlers:
$("[data-toggle=popover]").popover();
$(document).on('click', '.btn2', function(event) {
event.preventDefault();
$(this).popover({ html: true });
});
$(document).on('click', '.item', function (event) {
event.preventDefault();
const value1 = $(this).attr('data-val1-value');
const params = {
value1: value1
};
$.ajax({
type: "POST",
url: endPoint,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(params),
success: (result) => {
// refresh
}
});
});
There are two problems with this code:
popover will be displayed after 3 times clicking on .item
jQuery ajax won't succeed, it shows 400 Bad Request error on console.
PS: this code works fine with not-generated markup.
any idea?
For popover you must reinitiate every your dynamic content was append to HTML.
For Ajax 400 this is because the URL not found the route path, please check again your backend requirement for this request.
a) to make sure your url is correct,
1) update your serverside funtion not to accept any parameter just for testing
2) call ajax with data: NULL
3) debug and see if it reaches to server side function.
b) if not reached to server side, check if it is a POST or GET in server side function.
c) if you are sure that server side function is correctly called, data without stringfy.
that might help.

codeigniter: I can't change view page

I'm having some problems changing the view page in the code. Note: i'm using ajax.
This is part of the controller function called "insert_inventario" after the information is saved in array_db it compares with the inventario_model and the result "true" or "false" is saved in obj_inv.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view,
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
This is part of the view page called create, this is the submit button that executes the Javascript code that execute the controller function
<input type="submit" class="btn btn-danger" id="btn_enviar" value="Guardar">
The javascript Function
$("#btn_enviar").click(function(){
var r = confirm("Make sure the information you fill is correct");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
}
return false;
});
The problem is, when i fill the form and press submit, the message box appears and when I click accept, it does nothing. I'm burning my brain so much to understand what I'm doing wrong, please help me.
The main problem is a error called jquery-2.1.4.min.js:4 POST http://161.196.112.19:8080/Inventario_Remedy/inventario/insert_inventario 500 (Internal Server Error) it happens when the code try to insert the array
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
So, in order to fix this, you have to check your database values and keep trying.

post method not working

I want to submit form data using post using ajax because in form post after submit it is redirected to a new page.
<form id="myContactForm">
<p>
<label for="byour_name">Your name</label><input type="text" name="byour_name" value="" id="byour_name">
</p>
<p>
<label for="byour_email_address">Your email address</label><input type="text" name="byour_email_address" value="" id="byour_email_address">
</p>
<p>
What's on your mind?<br>
<textarea name="Message" rows="10" cols="25"></textarea>
</p>
<p>
<input type="submit" value="Send it!" onClick="sendMail()">
</p>
</form>
function sendMail() {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),
success: function( response) {
alert(response);
},
error: function() {
alert('failure');
}
});
}
Every time I make request error function is executing.I am writing app on google app engine. I am keep getting this error:
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
My post request handler is:
def post(self):
Content = self.request.get("Message")
byName = self.request.get("byour_name")
byEmailAddress = self.request.get("byour_email_address")
gmailUser = 'id#gmail.com'
gmailPassword = 'password'
dataSend = byName
mail.send_mail(sender = gmailUser,
to = gmailUser,
subject ="Email Sent By : "+ byName + "#" + byEmailAddress,
body = Content)
self.response.out.write(byEmailAddress)
And after I click submit button URl changes to:
http://localhost:8080/?byour_name=username&byour_email_address=userEmail#gmail.com%40gmail.com&Message=mlm%0D%0A#contact
as I am making a get request can someone help me..But how post request changes to get request.
You're not preventing the default submit. Either return false from your sendMail function, or take the event as a parameter and call preventDefault() on it.
Please remove form tag and the get the desired values by id and then use ajax method. Because may be ajax post and form request method are conflicting. I think form has default get method as you said earlier may be that's the reason whenever you click on submit first ajax post make request soon after form get method and may be that's the reason the error is thrown by your server.
I think I know what your trying to do , to fix this you can do the following:
remove onclick="sendMail()"
and change your JavaScript function to something like:
$('#myContactForm').submit(function () {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),success:
function( response) {
alert(response);
},
error: function(){
alert('failure');
}
});
});

Categories

Resources