I have a page that popup a modal and using hidden.bs.modal event, I want to reload the same page contents i.e body tag html via ajax. I have the following code:
$("#actions-modal").on('hidden.bs.modal', function(){
alert(document.location)
$.ajax({
url: document.location,
type: "get",
sucess: function(data){
alert('hhhh')
return $("#body1").html($(data).find('#body1'));
},
error: function(xhr){
console.log(xhr);
}
})
})
In the above code, alert(document.location) works fine. However, both alert('hhhh') in success handler of the ajax and console.log(xhr) in the error handler of the ajax don't work at all. i.e there is no success nor error! Additionally, there is no any errors in the browser's console.
document.location will return you the object, So try using document.location.href which will return you the string of URL. Then the AJAX call will start working.
Remove the return from your success function. You don't need to return when changing the html of an element. The return is only required when doing something like this:
function getHTML()
{
$.ajax({
url: document.location,
type: "get",
sucess: function(data){
return data;
},
error: function(xhr){
return "Failed";
}
});
}
var myHTML = getHTML();
$('#body1').html(myHTML);
However, when you are immediately setting the html you don't need it.
Related
I want to add ajax call on hyperlink tag "a", this ajax will only send some info to server and I don' have to get any return.
I tried something like this:
document.querySelector("#myId").onclick = function() {
$.ajax({
url: 'path',
type: 'post',
data: {key: 'value'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
});
}
And I found that, if my "a" tag with a href-link like
click
My server WON"T get any info, and my fail callback function of ajax was triggered, but if I remove the href-link or replace it with # like
<a id="myId"></a>
my server WILL get the info I send, and of course my success callback funciton was triggered
The fail callback function didn't return any error message, just a simple word error
Does anybody know what's going on and how to change the page and send ajax call in the same click?
By the way, I'm not prefer to put something like
window.location.href = "https://www.google.com.tw" in my success callback function, because in this case I'm maintain others' codes, I prefer to append my code down below rather than modified the already exist one, thanks!
First you should prevent the default behaviour (redirection) by adding preventDefault() :
e.preventDefault();
Hope this helps.
document.querySelector("#myId").onclick = function(e) {
e.preventDefault();
$.ajax({
url: 'api_url',
type: 'post',
data: {key: 'value'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
click
I have an HTML able, which I bind by using the following Action in MVC controller:
public ActionResult BindTable(int ? page)
{
int pageSize = 4;
int pageNumber = 0;
List<Users> _users = query.ToList();
return View(_users.ToPagedList(pageNumber, pageSize));
}
Below the table I have the following HTML:
<textarea class="form-control" style="resize:none;" rows="9" placeholder="Enter value here..." id="txtValue"></textarea>
<br />
<button style="float:right; width:100px;" type="button" onclick="CallFunction()" class="btn btn-primary">Update specific record</button>
The Javascript function responsible for calling the action is as following:
function CallFunction() {
if ($('#txtValue').val() !== '') {
$.ajax({
url: '/User/UpdateUser',
type: 'POST',
data: { txt: $('#txtValue').val() },
success: function (data) {
$('#txtValue').val('');
alert('User updated!');
},
error: function (error) {
alert('Error: ' + error);
}
});
}
And here is the Action responsible for updating the user:
public ActionResult UpdateUser(string txtValue)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(1));
if(obj!=null)
{
obj.Text= txtValue;
obj.Changed = true;
db.SaveChanges();
return RedirectToAction("BindTable");
}
return RedirectToAction("BindTable");
}
Everything works fine. But the table doesn't updates once the changes have been made ( it doesn't binds ?? )...
Can someone help me with this ???
P.S. It binds if I refresh the website.. But I want it to bind without refreshing the website...
I created a BIND function with Javascript, but it still doesn't binds:
function Bind() {
$(document).ready(function () {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
});
}
You're not actually updating the page after receiving the AJAX response. This is your success function:
function (data) {
$('#txtValue').val('');
alert('User updated!');
}
So you empty an input and show an alert, but nowhere do you modify the table in any way.
Given that the ActionResult being returned is a redirect, JavaScript is likely to quietly ignore that. If you return data, you can write JavaScript to update the HTML with the new data. Or if you return a partial view (or even a page from which you can select specific content) then you can replace the table with the updated content from the server.
But basically you have to do something to update the content on the page.
In response to your edit:
You create a function:
function Bind() {
//...
}
But you don't call it anywhere. Maybe you mean to call it in the success callback?:
function (data) {
$('#txtValue').val('');
Bind();
alert('User updated!');
}
Additionally, however, that function doesn't actually do anything. For starters, all it does is set a document ready handler:
$(document).ready(function () {
//...
});
But the document is already loaded. That ready event isn't going to fire again. So perhaps you meant to just run the code immediately instead of at that event?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
}
But even then, you're still back to the original problem... You don't do anything with the response. This AJAX call doesn't even have a success callback, so nothing happens when it finishes. I guess you meant to add one?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do something with the response here
}
});
}
What you do with the response is up to you. For example, if the response is a completely new HTML table then you can replace the existing one with the new one:
$('#someParentElement').html(data);
Though since you're not passing any data or doing anything more than a simple GET request, you might as well simplify the whole thing to just a call to .load(). Something like this:
$('#someParentElement').load('/User/BindTable');
(Basically just use this inside of your first success callback, so you don't need that whole Bind() function at all.)
That encapsulates the entire GET request of the second AJAX call you're making, as well as replaces the target element with the response from that request. (With the added benefit that if the request contains more markup than you want to use in that element, you can add jQuery selectors directly to the call to .load() to filter down to just what you want.)
I am doing form data submit using Ajax with jQuery.
When I submit form on popup window, I refresh the parent page.
My code:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webapp/addSpeedDataAction.do",
data: $(this).serialize(),
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
However page gets refreshed on success of callback but i can not see update on my parent page. Sometimes I can see updates and sometimes not. What is the issue? I also need to know how I can write it in native javascript and submit form using ajax javascript.
Maybe your getting this error due the fact that javascript is async and your code will proceed even when you have yet no response from the request.
Try this:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webfdms/addSpeedDataAction.do",
data: $(this).serialize(),
async: false, // This will only proceed after getting the response from the ajax request.
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
i have a page searchKB.jsp and it has some code like this :
$.ajax({
type: "GET",
data: {app:app,env:env,ptitle:ptitle,kbaseId:kbaseId},
url : 'jsp/knowledgeBase/kbResults.jsp',
success: function(res){
getResponse(res);
},
error: function(){
document.getElementById("message").style.display="";
$('#message').html("<b><font color=red face=Arial size=2>An Error encountered while processing your Request.Please try again after sometime.</font></b>");
}
});
function getResponse(response){
document.getElementById("message").style.display="none";
document.getElementById("KBInfo").innerHTML = response;
}
searchKB.jspis calling kbResults.jsp through the above code and now i want to apply jquery on elements of kbResults.jsp ..how will i do this ?
i tried everything but it is failing
<input type="button" id="expand3" value="Hide"/> <div id="result3">hide this</div>
and corresponding jquery code
$("#expand3").click(function(){
$("#result3").hide();
});
Try using something like this.
$(document.body).on("click", "#expand3", function(){
$("#result3").hide();
});
Assuming that elements with IDs expand3 and result3 are coming from that AJAX call, you can do something like this:
$.ajax({
type: "GET",
data: {app:app,env:env,ptitle:ptitle,kbaseId:kbaseId},
url : 'jsp/knowledgeBase/kbResults.jsp',
success: function(res){
getResponse(res);
} // removed the error callback for clarity
});
function getResponse(response){
$("#message").hide();
$("#KBInfo").html(response);
// only then attach the listener
// because #expand3 needs to be in the DOM
$("#expand3").click(function(){
$("#result3").hide();
});
}
Or, you can use #ashokd's solution with delegated listener.
I have ajax request:
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
And php
.....
return $this->paypalController(params, etc...) // which should redirect to other page
.....
How should i make that ajax request if success, submit form normal way, because now if I redirect (at PHP) its only return response, but i need that this ajax request would handle php code as normal form submit (if success)
Dont suggest "window.location" please.
I would add a class to the form to test if your ajax has already occured. if it has just use the normal click funciton.
Something like:
$('form .submit').click(function(e) {
if (!$('form').hasClass('validated'))
{
e.preventDefault();
//Your code here
$.post(url, values, function(data) {
if (success)
{
$('form').addClass('validated');
$('form .submit').click();
}
});
}
}
Why don't you use a result variable that you update after a succesful AJAX request?
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
// avoid to execute the actual submit of the form if not succeded
var result = false;
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
async: false,
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
result = true;
}
}
});
return result;
});
</script>
I've had this issue before where I needed the form to submit to two places, one for tracking and another to the actual form action.
It only worked by submitting it programatically when you put the form.submit() behind a setTimeout. 500ms seems to have done the trick for me. I'm not sure why browsers have trouble submitting the form programatically when they are attempting to submit them traditionally, but this seems to sort it out.
setTimeout(function(){ $("#abc_from").submit(); }, 500);
One thing to keep in mind though once it submits, that's it for the page, it's gone. If you still want whatever processes are running on the page to run, you will need to set the target of the form to _blank so that it will submit in a new tab.