Replace AJAX after successful load and error handling - javascript

So I have this simple AJAX load method to load an URL:
<div id="load">
<h1 id="status">Loading...</h1>
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({cache: false});
var url = "http://www.example.com/get.php?id=12345";
$('#load').replaceWith($('<div>').load(url));
});
});
</script>
At the moment I dont ever see the Loading... whilst the AJAX is loading, however shouldnt my method only replace it after it's loaded the new content. On a side note, if the AJAX load failed, how would I go about replacing that status class with Failed

if you load the page into a $('<div>') - then use the .load callback to complete the replacement of status - like so
<div id="load">
<h1 id="status">Loading...</h1>
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({cache: false});
var url = "http://www.example.com/get.php?id=12345";
$('<div>').load(url, function() {
$('status').replaceWith(this);
});
});
</script>

Related

Load and write text file into html [duplicate]

I want to load a *.txt file and insert the content into a div.
Here my code:
js:
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
success : function (data) {
$(".text").html(data);
}
});
});
});
html:
<div class="button">
<input type="button" id="lesen" value="Lesen!" />
</div>
<div class="text">
Lorem Ipsum <br />
</div>
txt:
im done
If i click on the button firebug report following error:
Syntax-Error
im done
I don´t know what to do :-(
You need to add a dataType - http://api.jquery.com/jQuery.ajax/
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
});
});
You could use jQuery.load(): http://api.jquery.com/load/
Like this:
$(".text").load("helloworld.txt");
The .load("file.txt") is much easier. Which works but even if testing, you won't get results from a localdrive, you'll need an actual http server. The invisible error is an XMLHttpRequest error.
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
Try
$(".text").text(data);
Or to convert the data received to a string.
<script type="text/javascript">
$("#textFileID").html("Loading...").load("URL TEXT");
</script>
<div id="textFileID"></div>

HTML Links do not work after AJAX POST

Background: I am working on a small web application. AJAX will successfully POST the data to the action(create.php) and create.php will execute the necessary mysql query. Once AJAX is done, I append a message to the div id="container"></div> informing the user of a successful execution then clear the content "container" for future use; however, here in lies the problem.
Problem: After AJAX executes, I can not click on any HTML links already loaded onto the page(page.php). I have to refresh the page in order to click on any links and follow them to their destination. What is causing this to happen and how can I fix it?
AJAX does not need to return a result. It only needs to execute the specified jQuery code once the request is done. On a hunch, I altered create.php to echo the $_POST array and have AJAX return that as a result. Once AJAX loads the result into the "container" I still can not click on any links loaded on page.php
Answer: The DOM was not being reloaded after AJAX calls causing bootstrap dropdown menus to not function properly. The bootstrap dropdown class had to be manually reinitialized after each call. This has already been answered in detail here
create.php
<?php
if($_POST){
//run mysql query
}else{
//do nothing
}
?>
form.php
<form id="new-items">
<input type="text" name="item" />
<input type="button" onclick="create_item()" name="Submit" value="Submit" />
</form>
page.php
<html>
<head>
<script>
$(document).ready(function(){
$("#add_items").click(function(){
event.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow");
}, 5000);
setTimeout(function(){
$("#content").empty();
}, 8000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>
Link1
Link2
Add New Items
</nav>
<div id="content"></div>
</body>
</html>
After you fadeOut the #content element, it remains hidden. The next time you call your AJAX function, it's loading create.php into an invisible element.
Try:
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
Other issues: <div class="content"> should be <div id="content">; you didn't include jquery.js at the top of your script; you didn't pass the event object e to your click handler.
page.php should now look like:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#add_items").click(function(e){
e.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>Add New Items</nav>
<div id="content"></div>
</body>
</html>
The anchor links in the <nav> will natually 'refresh' the page with the new content.
If you want to load the content via an ajax request then you should try the following:
Add a common class to the links
<nav>
Link1
Link2
Add New Items
</nav>
Then attach a click event to each link which intercepts the default page refresh with e.preventDefault(). The you can perform the ajax request using the href attribute of that link.
$(function(){
$(".anchor").on('click', function(e){
e.preventDefault();
var $this=$(this);
$("#content").load($this.attr('href'));
});
});
The DOM was not being reloaded after AJAX call. Boostrap dropdown module has to be manually reinitialized after each call. Detailed answered here: answer

Post not sent immediately with ajax

<script src="http://www.ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<form>
<label>Campo</label>
<input id="campo" name="campo" placeholder="Campo" required="" type="text">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "control.php",
type: "POST",
data: "campo=" + $("input#campo").val(),
success : function(data) {
if (data == 1) {
$("#div").html("Campo non disponibile");
}
else {
$("#div").html("Campo disponibile :)");
}
}
});
});
</script>
I saw with Firebug that the POST contains the value of the input field is sent only updating the page and not immediately. Why?
You don't have a proper click/submit handler registered for the form submission. Instead, you call $.ajax only on document ready. That's why you only see the submission on page load (or to be more accurate, document ready).
You need to listen to the submit event, so change your code to something like the following
$(document).on("submit", "form", function(e) {
e.preventDefault();
$.ajax({
…
});
});
You don't need to wait for the document to be ready if your javascript is at the end of the page (it's always ready at that point). And I noticed that you include both v1.9 and v.1.10 of jQuery and that's generally not needed nor advisable.

Javascript not being called in #Html.ActionLink

I have the following javascript test.js file:
$("#addItem").click(function () {
alert("yup");
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#bandRows").append(html); }
});
return false;
});
That I want to use to inject some HTML into the "bandRows" div on a page. I'm using Razor in an MVC 3 app like so:
The Index View, which contains the link that, when clicked injects a partial view HTML:
#model IEnumerable<TariffBand>
<script type="text/javascript" src="=#Url.Content("~/Scripts/jquery-1.3.2.js")"></script>
<script type="text/javascript" src="=#Url.Content("~/Scripts/MicrosoftAjax.js")"></script>
<script type="text/javascript" src="=#Url.Content("~/Scripts/test.js")"></script>
<h2>Index</h2>
#using (Html.BeginForm())
{
<div id="bandRows">
#foreach (var band in Model)
{
Html.RenderPartial("BandEditorRow", band);
}
</div>
#Html.ActionLink("Add band...", "Add", null, new { id = "addItem" })
<input type="submit" value = "Done" />
At the moment, when I click on the link the javascript is not being called - the alert box is not being displayed - and the link just navigates to the "Add" partial view rather than injecting it into the 'bandRows' div.
Can anyone tell me why? I haven't used javascript before so I've obviously done something daft but can't work it out for the life of me.
EDIT - I have amended the .js file so the handler is for click not onclick. I have also tried amending the html helper to:
#Html.ActionLink("add band...", "Add", null, new { onclick = "addItem" } but still no dice.
Thanks
David
You have
$("#addItem").onclick(function ()
There is nothing like $.onclick.
This will be
$("#addItem").click(function ()
Edit
$().ajax({ should be $.ajax({
and the whole code should be within document.ready() like
$(document).ready(function(){
$("#addItem").click(function (){
.
.
.
});
Edit - 2
As you have admitted that you are very new to javascript world, I am giving the detail code:
<script type="text/javascript" src="=#Url.Content("~/Scripts/MicrosoftAjax.js")"></script>
#* <script type="text/javascript" src="=#Url.Content("~/Scripts/test.js")"></script> *#
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function(){
$("#addItem").click(function (){
alert("yup");
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$("#bandRows").append(html);
}
});
return false;
};
});
</script>
document ready is a very preliminary thing you need to learn when starting jQuery. This is the API documentation of ready event. And here is a tutorial for understanding document ready.

AJAX to dynamically fetch data from a file not working

I'm Using AJAX to dynamically fetch data from my php page and display it on a html page. Its not working. Here is the link to the page
HTML Page where the call is made and result should be displayed
<h3>John</h3>
<div>
<p class="post">Result to be displayed</p>
</div>
AJAX code
$.ajaxSetup ({
cache: false
});
// load() functions
var loadUrl = "../load.php";
$("#get").click(function(){
$(".post")
.html(ajax_load)
.load(loadUrl, "language=php&version=5");
});
$(function(){
$.ajaxSetup ({
cache: false
});
var loadUrl = "../load.php";
$("#get").click(function(){
$(".post")
.html(ajax_load)
.load(loadUrl, "language=php&version=5");
});
});
Is pretty much what you want.

Categories