how to run javascript within a ajax called file? - ajax

$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
How do I run javascript within test.html and make it work ?
Thanks
Abhinab

It doesn't really work like that. Javascript in a page is interpreted by the browser when the page is loaded. In this case you aren't loading a page in the browser, you're just getting the page in your ajax response. That response HTML may have <script> elements in them, but nothing is going to do anything with it.
I hesitate to even say this, but you could parse the response in your success function to find all of the script elements, then add whatever you're looking for to your own page's DOM. That should cause the script to be fetched and evaluated. I hesitate to mention it because it smells really bad. If any of my developers did this we'd be having a tough conversation. ;-)
It might help to elaborate on what you're trying to accomplish, as there might be a more elegant way to achieve your goals.

function call_recursive(){
var pages ["test1.html", "test2.html", "test3.html" ];
while(pages.length() > 0){
page = pages.pop();
$.ajax({
url: page,
context: document.body,
success: function(){
$("div#logger").append("<p>" + page " loded </p>");
},
error: function(){
$("div#logger").append("<p class'error'>" + page " is not loded </p>");
},
});
}
}
just execute call_recursive

Related

issue with Ajax dispatcher in typo3

I'm trying to grab some data from the database on a page in typo3 using Ajax . So after a long time looking for the appropriate way to do it , I got convinced that The Ajax Dispatcher is the best tool to do the job . So I created the file following the instructions to be found here.
Now when I make an Ajax call on my page , the console displays a 500 (Internal Server Error).
joined is a snapshot of my console tab.
and this is the jquery function that gets run on an onchange event .
function getContent(id)
{
console.log("Start process ...");
$.ajax({
async: 'true',
url: 'index.php',
type: 'POST',
data: {
eID: "ajaxDispatcher",
request: {
pluginName: 'listapp',
controller: 'Pays',
action: 'getMyCos',
arguments: {
'id': id,
}
}
},
dataType: "json",
success: function(result) {
console.log(result);
},
error: function(error) {
console.log(error);
}
});
}
Could someone please help me , I just started developing with this CMS of shit :p
If you indeed followed the tutorial step by step, and you use TYPO3 V6.2, you would get errors cause of depricated function calls to t3lib_div (as the title of the blog item says, it is for version 4.x)
Always keep your error.log open, it's your best friend in times of coding stress
You can also use typenum for ajax calls
http://lbrmedia.net/codebase/Eintrag/extbase-60-ajax-bootstrap/
I can imagine that starting with TYPO3 can be frustrating, but calling it a 'CMS of shit' does not seems to be a smart strategic move if you need help from people who think differently about it.

.done attachment not working with ajax update to file, works with read from file

Attaching .done .fail and .always to ajax calls is now doable for me - it is "easy" when the script is at the bottom of the html page.
Now I want to create generalized ajax functions that I can use just by including a js file in the header. I've been successful with ajax functions that read data from server (.done always works). I'm having problems when I just write or update data to the server (no return of data). Here are the specifics-
Standard ajax add/update call that always works - in script tags at bottom of page.
$.ajax({
type: 'POST',
url: 'supdateajaxfunctiontestbackend.php',
data: {localid: localid,
firstname: firstname,
lastname: lastname}
}).done(function(){ alert('Done with Add/Update!'); });
If I create a function at the bottom of the page, or add the function to a js file, this add/update always works.
function generalWriteAjax(filetocall, datatosend) {
$.ajax({
type: 'POST',
url: filetocall,
data: datatosend
}).done(function(){ alert('Done with Add/Update!'); });
}
I would like to detach the .done from the function, and call the .done when attached to a separate function/object. The following code works fine WHEN THERE IS DATA RETURNED FROM THE SERVER. (a separate generalReadAjax function that asks for server data). The done is attached to an object that is returned from the server (This concept I found here on Stackoverflow).
backenddata = generalReadAjax('readtesttablebackend.php');
displayData(backenddata);
backenddata.done(function(){ alert("Done with read!"); });
});
I have tried all of the following with the WRITE/UPDATE only function, and none of them work.
generalWriteAjax(filetocall4update, datatosend4update).done(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update).when(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update).then(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update);
createdonealert = generalWriteAjax(filetocall4update, datatosend4update);
createdonealert.done(function(){ alert('Done function'); });
createdonealert.when(function(){ alert('Done function'); });
createdonealert.then(function(){ alert('Done function'); });
So obviously, there is a difference in the way the promise is handled between a "go get me data" and "here is data, please store it".
I even put an echo "Done"; at the bottom of the update php file just to return something, and still no luck.
I've searched this site and google with combinations of:
ajax .done attach add update not working promise
and have found nothing that deals with my specific example.
Can someone give me some guidance?
I thank you in advance.
Well, no one has responded, and I've learned a bit by hacking on this for the last day. Here are some things I THINK I've learned:
If you create a general callable function using ajax, it does not act the same as an "inline" ajax - you do not get the same callback actions as you do when the ajax code is at the bottom of an HTML page between script tags.
If you return something from the server, the ajax function acts similarly to when it is between script tags.
If you DO NOT return data from the server, the ajax function does NOT act the same as when it is inline.
So what I've done is on all php files that are "write/update" only (no data returned), I add a little code to the bottom of each php file that returns a small amount of json "junk". With this "junk" the ajax function acts like a regular ajax call between script tags at the bottom of the page.
It's a kludge, but it works. Here is the code at the bottom of a read/update php file that normally would NOT return anything. It now returns a json array regarding "John":
$json = array('firstname' => 'John');
echo json_encode($json);
Here is the function in the attached js file:
function generalWriteAjax( filetocall, datatosend ) {
return $.ajax({
type: 'POST',
url: filetocall,
data: datatosend,
dataType: 'json'
});
}
Here is the code on the page that calls the .js function:
$("#clicktoupdate").click(function(e) {
var localid = $('#idnumber').val();
var firstname = $('#updatefirstname').val();
var lastname = $('#updatelastname').val();
var filetocall4update = 'supdateajaxfunctiontestbackend.php';
var datatosend4update = {localid: localid, firstname: firstname, lastname: lastname};
generalWriteAjax(filetocall4update, datatosend4update).done(function(){ alert('Done inline'); });
});//end of update click
I wish I understood the details, but this is an empiric solution that works.
Comments from the experts would be nice.
Thanks for looking!

Grails: Passing a javascript variable to a template

I am new to ajax so maybe this is obvious. I've tried many different not-working approaches. I have javascript that when you click on a button:
an ajax call that grabs some data from a controller - returns an object
display that data in a template that I will show on the page
Here is the javascript/ajax:
<script type="text/javascript">
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Here is the key line in grails view template:
<g:each in="${allResults}" status="i" var="result">
How do I get the data from the javascript to the gsp code (ie allResults)?
Do I have to "refresh" this template to display new data?
thanks.
You just can't make your javascript/jquery code populate things in the gsp, since the gsp is processed server-side and javascript is processed client-side, after the gsp rendered all html documents and populated them with your model. You need to be aware that your page was already processed, so things like ${variables} won't be reloaded anymore. So when you do this:
$(".resulttable").show();
It's not gonna show the result you're waiting for. You have to use javascript code to reload your result table.
So if you're using ajax here, you should use the function success to alter your html table via javascript/jquery since you already have the response you wanted. Maybe this read can help you. Oh, and I think it would be better if in your ajax call, you would define a dataType (json works great in your case), like this:
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
dataType: 'json',
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Just to make clear what kind of response you're getting from the controller.
You do not need to write your ajax calls the hard way. There are some Grails intern tags you can use inside your html:
http://grails.org/doc/latest/ref/Tags/remoteFunction.html
http://grails.org/doc/latest/ref/Tags/submitToRemote.html
http://grails.org/doc/latest/ref/Tags/remoteLink.html
Following the links you will find some nice examples...

Converting AJAX call to avoid cross-domain problems

I m trying to convert the following code to another AJAX call, in order to not have cross-domain problems!
This is my original code:
<script>
$(document).ready(function() {
$("#os").load('http://www.a.gr/os #livesos');
var refreshId = setInterval(function() {
$("#os").load('http://www.a.gr/os #livesos');
}, 60000);
$.ajaxSetup({ cache: false });
});
</script>
And here is a sample code for what i want to do, but i dont know how...
$.ajax({
type: "GET",
cache: false,
url: 'http://www.a.gr/os',
dataType: "???",
.
.
.
.
});
Can someone help me please?
Your best bet to avoid cross-domain issues is to have the phone call your server, and the server can call the other servers to get the data needed.
There are a couple of benefits to this, one being that you can cache recent calls, if it doesn't change often, and more quickly send it back to the client.
Also, if you want to later change the url or make additional calls to return richer data, you can do that without affecting the client.

jQuery: Use a plugin on a page pulled in via AJAX

I'm building a simple AJAX driven website (because of the audience, it's okay to do this) where pages are pulled in based on the anchor etc. Simple enough.
However, one of the pages I want to pull in should have a slideshow on it. Once the call is successful and the page appears, the plugin isn't working.
Do I have to re-initialize the plugins I want to use on a page that's dynamically pulled in?
I can't show any code right now but in theory, what would the best practice be to use plugins and re-init JS code on dynamic pages?
I usually have all my script in one jquery.scripts.js file in the head of the main index page. Do these scripts need to be on the separate pages themselves?
Many thanks!
Michael.
$('#logo a').click(function() {
$.ajax({
type: "POST",
url: "./ajax/test.html",
data: '',
dataType: "html",
success: function(data){
if(parseInt(data)!=0) {
$('#cycle').html(data);
$("#cycle").cycle({
fx: 'fade',
//easing: 'easeOutExpo',
speed: 3000,
//timeout: 0,
//next: '#cycle-next',
//prev: '#cycle-prev'
});
}
}
});
return false;
});
This code executes the call, loads the page, but does not re-init the plugin. It does nothing, and there are no errors. Weird.
What you should do is after you retrieved the ajax page, insert it into your website and when that is done you can initialize the slideshow.
so basically:
$.ajax({
url: 'myurl',
success: function (data) {
$('#target').html(data);
$('#target .slideshow').slideshow();
}
});
<div id="#target">
<div class="slideshow"></div>
</div>
You don't say whether the cycle plugin has been previously initialized before running the $.ajax command. If it been, then you'll need to destroy the cycle slideshow and re-initialize it.
success:function(data){
if(parseInt(data)!=0) {
$('#cycle').html(data);
$('#cycle').cycle('destroy');
$("#cycle").cycle({
fx:'fade',
//easing:'easeOutExpo',
speed:3000,
//timeout:0,
//next:'#cycle-next',
//prev:'#cycle-prev'
});
}
}

Resources