how to execute ajax output script - javascript

I'm getting an ajax output success data.
Where the data contains some html text and a script.
But the script is not executing, how can I execute the script.
Let's say Ajax response obj is
<div>something....</div><script>alert("test");</script>
the above code is my Ajax response.The div is getting rendered, but the alert is not working.

Assuming you are not using JSON or jQuery, or any other library, and your AJAX call returns some HTML and/or javascript which is being added to your existing document (eg. using innerHTML), any javascript returned using AJAX will not execute in the browser - except for events on elements in the HTML.
So if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />, the js alert will work ok, but if your AJAX call returns <script type="text/javascript">alert('hello');</script> it will not execute. In that case, you would have to parse the result to extract the javascript and execute it, using a function such as this:
function extract_and_execute_js(output_to_parse)
{
if(output_to_parse != '')
{
var script = "";
output_to_parse = output_to_parse.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){if (output_to_parse !== null) script += arguments[1] + '\n';return '';});
if(script)
{
if (window.execScript)
{
window.execScript(script);
}
else
{
window.setTimeout(script, 0);
}
}
}
}

If you are retrieving the JSON formatted result from AJAX call, you can just use eval to execute the javascript.
Assume, if the result json is formed like this
var res = '{"Data": "<something>",
"script": "alert(something)"}';
var out = eval("(" + res + ")");
var data = out.data;
eval(out.script);

Interestingly enough, I use jQuery and using the html() function was enough to get the JavaScript to execute. So more or less I had nothing special to do.
There is a simplified version:
var myform = $('form#form-id');
$.post(myform.attr('action'), myform.serialize(), function(response) {
$('#some-id').html(response.message);
}
In my case the code kicked in automatically so I did not need any other of the solutions proposed here.

Not sure if you are using a library, but with Prototype I had to set
evalScripts: true
before JavaScript would be eval-ed. See here for more info:
http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxRequest

Using jQuery here is a simple bit of code:
$.ajax({
type: "POST",
url: "getData.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result);
}
});
But, to actually use the results of the variable result I ended up using a javascript library, from http://www.json.org/js.html, I did:
success: function(result) {
var myData = JSON.parse(result.d);
There are probably better approaches, but this was simple, and worked for me, so I just use this. Later, when the project is in production I may go back and clean this up, but that is after I get everything working.

Related

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

Get AJAX data from server before document ready (jQuery)

I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.

JQuery parse JSON

I'm fairly new to JQuery. The code below works and I can see the correct JSON response in Firebug. But I couldn't find a way how to get and parse it in the code. Alert window only shows
"[object Object]" but not any json text.
<script>
$.ajaxSetup({ cache: false });
var _token;
function make_token_auth(user, token) {
var tok = user + ':' + token;
return "Token " + tok;
}
$.ajax
({
type: "GET",
url: "url",
dataType: 'json',
beforeSend: function (xhr){
xhr.setRequestHeader('Auth', make_token_auth('userid', 'token'));
},
success: function (data){
alert(data);
}
});
</script>
The fact you precised
dataType: 'json',
tells jQuery to parse the received answer and give it as a javascript object to your success callback.
So what you have here is fine and what is alerted is correct (this is an object, so
alert simply prints the result of data.toString()).
Use console.log to see what it is exactly :
success: function (data){
console.log(data);
}
and open the developer tools in Chrome or the console in Firebug to browse the properties of the object.
don't use alert() for debugging -- it's often unhelpful (as in this case), and also has serious issues when used with asyncronous code (ie anything Ajax) because it interrupts the program flow.
You would be much better off using the browser's console.log() or console.dir() functions, and seeing the object displayed in the console. It is much more functional, and doesn't interrupt the flow of the program.
So instead of alert(myjsonvar) use console.log(myjsonvar).
You can get the json string by using JSON.stringify
var jsonstr = JSON.stringify(data);
alert(jsonstr);
The alert function expects you to pass in a string or number.
Try doing something like this:
for(x in data) {
alert(x + ': ' + data[x]);
}
Update in response to comments: You can use alert in development or production to see string and number values in the object returned by the server-side code.
However, carefully rereading your question, it looks like what you really want to see is the actual JSON text. Looking at #dystroy's answer above, I think that if you remove the dataType: 'json' from your $.ajax invokation, jQuery will treat the response as plain text instead of automatically converting it to an Object. In this case, you can see the text by passing it to the alert function.
Try using
data = JSON.parse(data)
Then do whatever you want with the data.
Source: JSON.parse() (MDN)

Using Javascript / JQuery to access an array built from an external XML file

I hope this is not too much of a newbe question but I've been pulling my hair out for a while now so thought I'd give in and ask for my first piece of advice on here.
I'm trying to read an external xml file using javascript / jQuery / ajax and place the retrieved data into an array so that I can then reference it later.
So far I seem to be doing everything right upto the point I put the data into the array but then I'm struggling to to read the data anywhere other than inside the function where I create it. Why am I not able to access the Array from anywhere other than in that function?
Here is my code...
Please help!!
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser
});
function do_xmlParser(xml)
{
var myArray = new Array();
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
console.log("inside "+myArray); // This outputs the array I am expecting
return myArray; // is this right???
}
console.log("outside: "+myArray); // This does NOT output the array but instead I get "myArray is not defined"
You're defining do_xmlParser as a callback to an asynchronous function (success of the jquery ajax call). Anything you want to happen after the ajax call succeeds has to occur within that callback function, or you have to chain functions from the success callback.
The way you have it now, the actual execution of code will go:
ajax -> file being requested -> console.log ->
file transfer done -> success handler
If you're doing some critical stuff and you want the call be to synchronous, you can supply the
async : false
setting to the ajax call. Then, you should be able to do something like this:
var myArray = [],
do_xmlParser = function (xml)
{
$(xml).find("tag").each(function ()
{
myArray.push($(this).find("innerTag").text());
});
};
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: do_xmlParser,
async: false
});
console.log("outside: " + myArray);
The async option doesn't work for cross-domain requests, though.
NOTE
I don't recommend doing this. AJAX calls are supposed to be asynchronous, and I always use the success callback to perform all of the processing on the returned data.
Edit:
Also, if you're into reading... I'd recommend jQuery Pocket Reference and JavaScript: The Definitive Guide (both by David Flanagan).
look close and you will see. You are actually firing up an array that dosen't exist. You have declared myArray inside function. Try do something like this.
console.lod("outside :"+do_xmlParser(xml)); // I think that when you merge a string and an array it will output only string, but I can be wrong.

Categories

Resources