I want my button to do something onClick(), it has the ID btnSend. But nothing happens when I click the button which is weird and I can't figure out why.
The script is in my view for now within script tags.
$("#btnSend").click(function () {
var messageInfo = {
"Body": $("#Message").val(),
};
$.ajax({
type: "POST",
url: '/Api/Posts',
data: JSON.stringify(messageInfo),
contentType: "application/json;charset=utf-8",
processData: true,
success: function (data, status, xhr) {
alert("The result is : " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
Are you sure your script is running after the page is loaded?
Put your script at the bottom of the page and give it a try.
Related
I am working on page when user submits data and retrieves html data which contains hyperlinks.
Now when the user clicks on the link, he will be navigated to another page and when the user clicks on browser back button, I want to show earlier displayed html data.
In order to achieve this, I tried to store the value in session and retrieve it when user clicks back browser button.
But I am facing issues
I tried to capture browser back button and display the session stored variable and I am not sure why this is not getting triggered.
$(window).on('hashchange', function () {
$("#spanId").html("test");
});
Html data stored in session variable is not displaying properly like "<" is showing as "<" and all the data is showing as string instead of html content.
$(document).ready(function () {
$("#spanId").html("#Session["Data"]");
$("#btnSubmit").click(function () {
var data = {
"Date": $.datepicker.formatDate("mm-dd-yy", DateVal),
"Type": $('#type').val(),
}
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
url: '#Url.Action("GetReportdata", "Reports")',
success: function (result) {
$("#spanId").html(content);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
Please let me know if there is any other way to handle this and help me resolves this issue.
There might be another way of solving this on the server side, but this should work.
$(document).ready(function () {
$("#spanId").html(decodeHtml("#Session["Data"]"));
$("#btnSubmit").click(function () {
var data = {
"Date": $.datepicker.formatDate("mm-dd-yy", DateVal),
"Type": $('#type').val(),
}
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
url: '#Url.Action("GetReportdata", "Reports")',
success: function (result) {
$("#spanId").html(decodeHtml(content));
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
function decodeHtml(encodedHtml) {
return encodedHtml.replace(/&/g,'&')
.replace(/</g,'<').replace(/>/g,'>');
}
I found an event to handle browser back button:
if (window.performance && window.performance.navigation.type ==
window.performance.navigation.TYPE_BACK_FORWARD) {
$("#spanId").html("#Session["Data"]");
}
This can be used to repopulate data.
My problem is that when I press yes on delete confirmation the db record goes away, but if I refresh the page it comes back.
Maybe I have to put the language and the id inside the Ajax URL?
If yes how can I do this?
Please forgive me I am still learning.
This is for java eclipse and SQL database
var assetId;
var batchId;
function cancelOpname(){
$.ajax({
type: "POST",
cache: false,
url: urlPage + "opname/cancel",
dataType: "JSON",
data: data,
beforeSend: function() {
$('.loader').fadeIn();
},
complete: function() {
$('.loader').fadeOut();
},
success: function() {
if (data.errorResult == false) {
console.log("Success: else ");
javascript:window.history.back();
} else {
$('.loader').fadeOut();
}
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
no error but ajax and jQuery not working
I am using ASP.net MVC, and following is the Html code
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
<div id=waitscreen>
//some code
</div>
Code in external js
function _post(someparameter)
{
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
Also tried adding document ready in above code it is still not working
Above code worked fine and it show and hide as expected, but now I need to repeat ajax call in every page so I decided to move in external JS file now same code is not showing waitscreen.
Things I tried:
Loaded external script in head - Not working
Loaded external script at end of page - Not working
Question: I want to make hide and show work from external JS file
The following code snippet should help you. Tested by including the external JS file in the <head> of the main document and just below the inclusion of jQuery.
// main window
var json = {"key": "value"}
console.log('before calling _post()');
_post(json); // call external JS
// code in external JS say test.js
function _post(someparameter)
{
console.log('external JS called!');
$.ajax({
type: "POST",
url: 'http://www.niketpathak.com',
dataType: 'json',
data: someparameter,
async: true,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
// $("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
//delaying the error callback
setTimeout(function() {
$("#waitscreen").hide();
console.log('after completing the http-request');
}, 500);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=waitscreen>
Waitscreen....
</div>
Also, note that I have used async: true (which is also the default) since setting it to false is deprecated and not a good idea as it blocks the UI.
My ajax code in External.js file,
function _post()
{
var data = {
Email: "a#a.com",
Password:"1111"
}
$.ajax({
type: "POST",
url: "/Home/hello/",
dataType: 'json',
data: data,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
In my HomeController, I have hello method like this,
[HttpPost]
public ActionResult hello(LoginViewModel data)
{
ViewBag.Message = "Your contact page.";
return Json(data, JsonRequestBehavior.AllowGet);
}
And in my all the views I have the "waitscreen" div.
Now I just reference the External.js file to my _Layout page, I just drag and drop after jquery reference.
<script src="~/Scripts/External.js"></script>
Then in end of the same _Layout page, i just call the method like this,
<script>
_post();
</script>
Everything working properly.
Note: If you have only one parameter in your hello action method and suppose you have written like (int x) then in that case it will through 500 error. Because in your RouteConfig.js its mentioned that, by default the parameter name should be id. So you need to write int id.
Hope its help.
Having an issue. I have two different buttons included with each image displayed. One is remove, the other is assign as "main".
Remove works. It hides the image, deletes the file, and the MySQL row.
Assign Main sort of works. It updates the row in the database changing "main" value to 1, as it should, however, it should also alert(), but it does not.
<script>
$(document).ready(function() {
$(".remove_image").click(function() {
var image_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { image_id:image_id,
image_remove:1},
success: function(response) {
$('#image_'+image_id).fadeOut(400);
showUploader();
}
})
})
});
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
}
})
})
});
</script>
The success method is only called when a HTTP 200 or HTTP 304 is returned, therefore you may need to double check to see if this is actually the case.
This can be done in the ‘Inspector’ panel in most modern web browsers, usually under the ‘Network’ tab.
You can also add a error: function() {} event handler to catch any HTTP 4xx / 5xx codes.
Try and alert the error which for sure is there:
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
})
})
});
This will show you if there is something wrong in your PHP code
Use done() instead of it :
$.ajax({
type: "post",
url: "imagecontrol.php",
data: {
image_id: image_id,
image_remove: 1
}
}).done(function(response) {
$('#image_' + image_id).fadeOut(400);
showUploader();
);
il give an example
document.ready(function() {
$("#Show").bind("click", function()
{
var F = Function2();
if (F)
{
// Do Other Stuff.
}
}
});
function Function2()
{
$("#Message").Show();
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").Hide();
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
}
</script>
<div id="Message" style="display:none;">
<!-- Loading Image In here -->
</div>
<a href="#" id="Show" onclick="return:false;">Show then Hide</false>
</code>
Now what I want to happen is for this messagebox to show however the AJAX for some reason wont show it until the AJAX Request is finished by which point it is too late. I have set async to false which hasent helped either.
I think the root of this issue is a syntax error. JavaScript is case sensitive, so the correct syntax would be lowercase show() and hide()
If you're still having an issue after fixing the syntax errors, try using the ajaxStart event to show the message and hide it on success.
//use the ajaxstart event to display the message
$('#message').ajaxStart(function() {
$(this).show("slow");
});
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").hide("slow"); //hide message on success
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
Delaying the show or hide
$("#message").delay(3000).hide("slow");
Here's a jsFiddle: http://jsfiddle.net/rs83R/
Try hiding the Message div in the click event after getting true or false.
Remove the async:false, I do not think that is anyway relevant to fixing this problem. The purpose of AJAX call is to make an asynchronous call.
Also, there is an error its not $("#Message").Show() its $("#Message").show() with all lowercase, same goes for hide().
Try changing these, I hope it should work.