Can ajax call on return add new javascript function to the page? - javascript

I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.
Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?
The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.

To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into

You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:
$.ajax({
success: function(){
// Perform JS action
}
}
The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.

The returned ajax response can contain javascript code as a string. Then you can eval(response).

If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.
Per the jQuery doc, getScript() is a shorthand for:
$.ajax({
url: url,
dataType: "script",
success: success
});
Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.

You can make your request a variable and extend upon it after the set up.
// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "PageOrControllerOrWebApi/MethodName",
type: "POST",
data: { id : dataID },
dataType: "json"
});
// When the request is done process
// what you need done
request.done(function(msg) {
alert('You got this ' + msg);
});
// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});

you can do it using success callback i think this can be a way please try
$.ajax({
.....,
.....,
success:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#tableID").append( script );
});
i hope it should help.

Related

Load HTML content synchronously

I need to load HTML in a div.
$("#content").load("content.html");
$("#myText").html("Prasath");
After that I need to update some text in a div(id='myText') which is available in "content.html". "content.html" contains huge data, so it takes some time to load. Before that this line is executed:
$("#myText").html("Prasath");
How to load HTML content synchronously from JavaScript/jQuery ?
I don't want to do this from call back option in load.
You can't load it synchronously but you can quite easily do the next task in the load() callback. For example:
$("#content").load("content.html", function() {
$("#myText").html("Prasath");
});
$("#content").load("content.html", function(data){
// this will execute after load is fired.
});
Use a callback.
EDIT: If you really want to make synchronous request, you can use the following code. However, you'll get a warning in console as I mentioned in the comment earlier:
var data = $.ajax({
type: "GET",
url: "content.html",
async: false
}).responseText;
// this code waits for the above ajax request.
Please have a look on the JQuery documentation about load().
You can pass callback function to load()
For example:
$("#content").load("content.html", function(){
$("#myText").html("Prasath");
});
EDIT: There is no way to make load() to load content synchronously. A workaround solution is that you can define a Jquery function that use ajax() to send synchronous request to target url and then set the response content to destinate div.
$(function(){
$.fn.extend({
syncLoad: function (url) {
var result = $.ajax({
url: url,
async: false,
type: "GET"
}).responseText;
$(this).html(result);
}
});
$("#content").syncLoad("/echo/js/?js=hello%20world!");
});
JS Fiddle: https://jsfiddle.net/1v8fmb8b/

Accomplishing Client-side Work During Page Initialization

In order to complete the initialization of an entry-point page, I need some data which can only be obtained through a third-party via client-side JavaScript. Hence, I need some sort of temporary page to be served which will run the JavaScript code before the target page gets rendered. How can I accomplish this?
My Server-side code, MyPage.aspx.vb may look something like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
...
...
// Read data from DB which gets written via client-side
// JavaScript interacting with web service
End Sub
Create two different pages your target page which here is MyPage.aspx, and as you yourself have mentioned, a temp page like Temp.aspx. Use a flag to check if your client-side task is done, in the session scope. like:
Session["AjaxCallIsDone"]
in your your MyPage Page_Load method, check if it is true:
If(Session["AjaxCallIsDone"] == null ||
!(Boolean)Session["AjaxCallIsDone"])
Response.Redirect ("Temp.aspx");
Ok then, now it goes to the temp page if your ajax call hasn't been done yet.
using jQuery or raw javascript, create your ajax call in the temp page:
request = $.ajax({
url: "third-party-server-url",
type: "POST",//or may be GET
data: yourdata
});
request.done(function (response, textStatus, jqXHR){
//your client-side task is done
});
create a Handler or Generic Handler to let client inform the server about the ajax call and to set the AjaxCallIsDone flag, do this in your handler method;
Session["AjaxCallIsDone"] = true;
then in your request callback create another ajax call to call that Handler, then in handlerRequest callback function do your redirect like this:
request = $.ajax({
url: "third-party-server-url",
type: "POST",//or may be GET
data: yourdata
});
request.done(function (response, textStatus, jqXHR){
//your client-side task is done
var handlerRequest = $.ajax({
url: "your-handler-url",
type: "GET"
});
handlerRequest.done(function (response, textStatus, jqXHR){
document.location="MyPage.aspx";
});
});
and now all is done.
Some more specifics / example code of what you got so far would be nice.
If you are using jQuery then you could use the getScript method...
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
//now do what you need to do
});
http://api.jquery.com/jquery.getscript/
Hope that helps.
I would recommend using jQuery AJAX instead of Temp.aspx,
Step 1. Get the data from third-party via client-side JavaScript.
Step 2. Using jQuery AJAX, get the data from from your DB which gets written via client-side & render it.

How can one trigger a function onchange of a div?

Here's a question which has proved very difficult to find an answer online for.
Let's say a user runs an ajax function onclick to fill the contents of a div.
But, what if the ajax output is php, and for that onclick, i want other divs on the page to change in a manner that is dependent on the contents of div1?
This means I need to wait for div1 to actually change so i can use the ajax output of the php calculations to adjust div2 accordingly.
After some testing i've found out that i cant add a call to a second ajax function at the end of the first because it seems to run before the div content from the first ajax call actually changes.
So how can i trigger an ajax call onchange of the contents of a div?
All ajax calls take a callback to run when the call completes, put your logic in there.
You could use Jquery
$('#div1').change(function(){
doAjax( $(this).html() );
});
Or in the callback of the ajax
$.ajax({
url: 'http://yoururl.com',
type: 'post',
data: { key: value },
success: function( data ){
doAjax( data );
}
});
If you are aware of jquery, this is what you should try:
$.ajax({
traditional: true,
type: "post",
url: '<your_url>',
beforeSend: function () {
//your logic to perform operation before ajax request
},
data: {
//data to send
},
success: function(response) {
//your logic to perform operation after ajax request
//here make another ajax request
}
});

how to call a specific function on every ajax request

I have a problem, that I have several pages in my project and I used a lot of ajax requests in my project, but now I think that whenever an ajax request is called a function will called and whenever that request ends another function will call. How can I do this globally I know I can put this in every ajax request but I need a solution which I do in one place and it works all over the project.
$(document).read(function(){
// Suppose this document load function is written on layout page and every page is inherited from this page
});
Use ajaxSetup, for example
$.ajaxSetup({
beforeSend: function() {
console.log('test');
},
complete: function() {
console.log('completed');
}
});
will setup beforeSend handler for every ajax request. Note that ajaxSetup can take any option that $.ajax can.
You should create a wrapper function for your ajax, then use that function. that way, you have "central" control over the ajax call. something like:
//fast and crude way to extend jQuery
$.fn.customAjax = function(params){
//contains defaults and predefined functions
var defaults = {
complete : function(){...default complete hander...},
beforeSend : function (){...default beforeSend handler}
...
}
//merge settings
var finalParams = $.extend({},defaults,params);
//call ajax and return the deferred
return $.ajax(finalParams);
}
//use it like
$.customAjax({
url : ...,
method : ...,
data: ...,
complete : function(){...} //redefining in the call will override the defaults
});
.ajaxStart
Register a handler to be called when the first Ajax request begins.
.ajaxSucess
Attach a function to be executed whenever an Ajax request completes successfully.
for Detail doc:
http://api.jquery.com/category/ajax/
Try something like this:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$.ajax({
url: "anotherMethod.html",
context: document.body
});
});
});
That means whenever ajax call completed successfully call your desire call.
It doesn't have a bug when complete. Click on Like, if work for you
$(document).ajaxSend(function(event, jqXHR, settings) {
$('#general-ajax-load ').fadeIn();
});
$(document).ajaxComplete(function(event, jqXHR, settings) {
$('#general-ajax-load ').fadeOut();
});

$.ajax JSON not passing values on complete

I'm having an annoying issue, on complete i get undefined when trying to make simple url validation. success working fine.
i get a valid json response:
{"error":"some error"}
and this is my jQuery
$("#myform").submit(function(){
dataString = $("#myform").serialize();
$.ajax({
type: "GET",
url: "myform.php",
data: $.URLDecode(dataString), //fixing url problem
dataType: "json",
beforeSend: function(){
$('#search').append('<img src="images/ajax-loader.gif" />'); //loader
$('.error').remove(); //removes every submit
},
success: function(data){
$('<span class="error">' + data.error + '</span>').appendTo($('#search'));
},
complete: function(data){
$('#search img').fadeOut(); //removes loader
alert(data.error);
}
});
return false; //force ajax submit
});
Any hint please?
If you look at the docs:
complete(XMLHttpRequest, textStatus)
A function to be called when the
request finishes (after success and
error callbacks are executed). The
function gets passed two arguments:
The XMLHttpRequest object and a string
describing the status of the request.
This is an Ajax Event.
Data is not a return value from your method.
If you're using firebug, use console.log(XMLHttpRequest) and you'll see what it includes.
You can also do this (quick - using eval here - not recommended.)
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message);
As per the docs, the complete event doesn't hold your json response.
Why do you need to define the complete handler and the success handler? Just define success.
maybe $.URLDecode() returns not JSON key/value structure
I think you want URLEncode not URLDecode? Either way I'd recommend fiddler for debugging issues like this - it'll show you exactly what's being sent to/from the server.

Categories

Resources