Display Ajax response in HTML - javascript

I'm calling a PHP file, and it's returning the response when I view it in Firebug. However, it's not displaying on my page. I'm not sure if the success is actually firing, because I can't even run an alert, but it is working because the PHP code is firing and returning what it's supposed to.
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "GET",
url: 'https://www.example.com',
dataType: 'jsonp',
contentType: "text/html",
crossDomain:'true',
success: function (data) {
$(".result").html(data);
}
});
</script>
<div class="result"></div>

You need to make the ajax call on load or document ready. The div may not exist at the time of response (page is interpreted top down).

Just a little lesson about what your are doing.
When working with any form of Ajax (or JavaScript in general), it is usually imperative to have your console open. You will be able to see your request, your response, and whole other useful information.
I usually work with Firefox and Chrome from time to time.
You can open your console by right clicking on the page anywhere and inspect an element with Firebug (on Firefox).
And inspect element in Chrome.
Once you see the Ajax call, click the + and see its content.
You should see something like:
Headers Post Response JSON Cookies or something alike.
I hope that helps.

Related

Ajax success code not loading in synchronous manner

We are expecting the below things:
Would like to show the page with updated values.
Then show the session attribute.
What is happening for the below code, session message displayed first and then the page is getting reload.
$.ajax({
type: "POST",
url: "startSelectedServer",
data: { selectedJvmHostIp : selectedJvmHostIp, selectedJvmPort : selectedJvmPort },
success: function(result){
1. location.reload();
2. $("#save-message-div").show();
},
error : function(e) {
}
});
<div id="save-message-div" style="background-color: #DFF2BF; padding: 8px;display:none">
<h2 id="save-message" style="color: #4F8A10"></h2>
</div>
But we are expecting to show message after reloading the page.
In above 2 is executing first then 1 is executing.
ok it appears to me that you are trying to perform a server-side functionality and then refresh the page and have a message appear that the functionality has occurred.
This is fine as far as it goes but will not work the way you have it. To do it closest to the way you invision you will want to put in conditional logic on page load to determine if it is appropriate to show the div.
Even if your page did not show the div prior to reloading, the way it is written, when the page reloads it will not still be executing the same piece of script - it is a blank slate with only what you pass to it.
I am not sure why you want to reload the page at all actually; you can, and should [to make use of ajax], just use the information client-side that is returned from the server asynchronously.

Using Ajax to call the same page makes the body content show twice

I'm making an Ajax call to the same PHP page from a link on the page.
For the final code I'll be passing some parameters but for the sake of keeping it simple, I'm not doing that in the code below. Reason I'm using Ajax is to place a "Please Wait" message as it seemed the most effective way to do it (usually you do a call from one page to another, which works perfectly fine).
I do get to see the "Please wait" message accordingly after clicking on the link but it keeps the content of THE <BODY> section below the new content being displayed by the Ajax call. So int he example, below, I basically end up with 2 links that say "Click here". How do I make it load just the new content (which in this case is identical)?
This must be simple but I'm not sure what I'm missing here.
PWAIT.PHP
<body>
<?php sleep(3); //To allow for the message to show as I have nothing processing here ?>
Click here
<script>
function loadingAjax(div_id)
{
$("#"+div_id).html('<center><img src="http://img/ajax-loader.gif"><b>Please Wait ...
</b></font></center>');
$.ajax({
type: "POST",
url: "pwait.php",
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<div id="myDiv"></div>
</body>
After our discussions, we've discovered that your code is working exactly as it should. It is doing exactly what you ask it to do.
Load the page from the server
Click button
Loads the same page via AJAX
Duplicates the page contents into a div on the page
Display duplicate contents
That's what you've asked, that's what you've received.

JQuery call not working after Ajax call succeeds

I have an Ajax call that looks like this:
$("#start-upload-btn").click(function(){
$.ajax({
type: "post",
url: "",
data: {
newProjectName: $('#project-name').val(),
csrfmiddlewaretoken: csrfToken
},
success: function(data){
$("#file-upload").click();
}
})
});
Upon success I want to perform a click on the element with id #file-upload to launch the file selection dialogue, but putting the code in success function fails to work. It works anywhere else. Is there something special about the scope of the Ajax success function? I really cannot figure this out.
Thanks
There is nothing inherently problematic about issuing a click on any normal element (including a button) from an ajax success callback.
The problem is that a file-input dialog is not a "normal element". It has some specific security limitations - one of which clearly limits your interaction with it.
This is demonstrated by the following fiddle: https://jsfiddle.net/qhfwobpz/
You'll see that issuing a click on the file-upload directly works without a problem. Doing it from an ajax callback yo'll see the callback is called, but the file dialog never shows.
This answer gives more detail as to the "why" and it boils down to you can open the dialog from an event issued by the user but not purely programatically.

Reloading a Page (or part of a page) using JavaScript

The client I am working for is trying to make it so that his page never has to reload. Instead he just wants to use AJAX. Now I realize that the way im doing it is not a very efficient way to do it but it is the easiest and you would understand why if you would see his site..
I'm trying to get it to work so that AJAX will refresh only parts of the page or the whole page.
My code is:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
function refresh (update) {
$.get(location.href, function (data) {
console.log(data);
var EL = $(data).find(update);
var HTML = $('<div>').append(EL.clone()).html()
alert(HTML);
$(update).replaceWith(HTML);
});
}
</script>
</head>
<body>
<div style="font-size: 64px;">The current timestamp is <b class="time"><?php echo rand(999, 9999999); ?></b></div>
<br><br>
<button onclick="refresh('.time')">Refresh Time</button>
</body>
</html>
When you first load the page PHP generates a random number. Hitting the refresh button is suppose to refresh this number. However, the same number stays there. The request returns the exact same page instead of return a page with a new number.
And again, people note that I know this is not a very efficient way to do this, but its the way i'm trying to get it to work
Am I doing something wrong? (besides requesting the whole page when only actually using part)
EDIT
You can try it out here: http://methods.x10.mx/projects/refreshPageParts.php
Change your call to this, to break the caching:
function refresh (update) {
$.ajax({
type: "get",
cache: false,
url: location.href,
success: function (data) {
$(update).replaceWith($(data).find(update));
}
});
}
See the notes on caching in the documentation: http://api.jquery.com/jQuery.ajax/
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false. To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true.
I tested your example on my local wamp stack and it is working fine!
btw: you forgot semicolon after the following line (It is not necessary though)
var HTML = $('<div>').append(EL.clone()).html();
EDIT: your code is working... also on the url you provided. The strange thing is you have to wait a few minutes before it is working. So when you visit the page and press the button, the time won't be updated... however if you wait few minutes it will... only once then you have to wait again. I bet your server is caching the page. So your problem is server side... disable the cache and it will work!!
EDIT:
you also could try to make the get url dynamic with a dummy parameter like so
http://methods.x10.mx/projects/refreshPageParts.php?v=dummy
maybe you don't have to make dummy dynamic, it might work with a static variable also. i'm curious, let me know ;-)

Ajax page load in div halts browser even if it is async?

I am trying to do async page open inside div with $.ajax but i am still having about 3sec delay after clicking link and that time page is jammed. Happens at least chrome and sasfari. Where am i going wrong way..?
$.ajaxSetup({
async: true
});
$(document).ready(function() {
$("#Button").click(function(evt) {
$('#change').html('<p><img src="ajax-loader.gif" width="15" height="15" /></p>');
$.ajax({
url: "reg.php",
cache: false
}).done(function( html ) {
$("#change").html(html);
});
});
});
No, asynchronous ajax requests like that don't hold up the browser. The problem is elsewhere, in code you haven't shown. The code you've shown will correctly do an async request.
Speculating on possible issues with what we can't see:
If the link has an href, you're not cancelling the default action, so it could be loading the page. You can prevent the default by calling evt.preventDefault() within your click handler, or by doing return false; at the end of it (which does that and also stops propagation).
If you have other code elsewhere setting async: false as the default, perhaps your ajaxSetup changing it back isn't getting called.
If you are using PHP sessions then the script will halt the browser until reg.php is completely finished.
In reg.php you will need to add this somewhere:
session_write_close();
This will allow you to read the session data but not write to it.
This is the case because you would probably never want two ASYNC scripts trying to write to the session at the same exact time.

Categories

Resources