Execute a Javascript using AJAX call - javascript

Is it Possible to execute a Javascript using AJAX call or calling a specific function in the Javascript.
I am able to display the contents of the Javascript file like "http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first " but not able to execute the javascript.
Is there any way. Actually I am a newbie AJAX

Ajax lets you do two things:
Make a request to the server
Read the response you get back
Anything else happens around that.
If you are, for instance, running NodeJS on the server, then the HTTP request will trigger some server side JavaScript.
If you get JavaScript back from the server, then you'll have that available in a string and you can do whatever you like to it (including passing it through eval()).
Generally speaking, fetching new JS from the server like that is a bad idea. Better to have your JavaScript loaded into your webpage up front and then just trigger it based on data you get back from the server.

If I am understanding correctly the case here is that the
server is returning some javascript code and you like to evaluate it.
You can use the eval() function as described here.
In the example you provided it would be something like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
eval(xhttp.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
But you should be careful, because using eval is not always a good idea.
See this SO question: Why is eval a bad idea?

Related

Making a local file hold a value to use by any user

I am trying to make a webpage that will be able to store a variable, using JavaScript, called heart-count (I was trying it with jQuery and JSON, but didn’t have any luck, I could access the number easily, but I couldn’t change it).
This variable should be easily accessed by the JavaScript and be able to be changed (or in my case incremented).
The way that I have it right now is in a local file called heart.json inside this file is the following code:
{
"hearts": 0,
"heartLog": []
}
I am accessing that file in my JavaScript like this:
$.getJSON("../js/heart.json", function(data) {
$("#num-hearts").text(data.hearts)
})
I was trying to use XMLHttpRequest (a way that was suggested to me):
var myJSON
$.getJSON("../js/heart.json", function(data) {
myJSON = data
setTimeout(() => {
myJSON.hearts++
console.log(myJSON)
console.log(data)
}, 2000);
})
var xhr = new XMLHttpRequest()
xhr.open("PUT","../js/heart.json",true)
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
xhr.send(JSON.stringify(myJSON))
I can’t confirm that this doesn’t work, since the way that the webpage is set up I test it using some interesting methods (interesting, but required…), and those use localhost. The reason I say that I can’t confirm that it doesn’t work, is because when I test the previous code, it says that “PUT” isn’t a valid protocol.
If there are any suggestions or validations of my code, that would help a lot.
How ya doin? I'm sorry to say but you can not write to a file in server directly with jQuery or Javascript because Javascript is frontend language. It doesn't have the capability to do so.
However you can send or receive data with XMLHttpRequest, but you need a server side language/program to process your XMLHttpRequest.

What do I do after I json_encode() my php array?

I am new to both php and javascript and having trouble understanding how to communicate between the two. I have a php array and I used json_encode() to turn it into json and now I just don't know what to do from there. I have just been looking around and haven't been able to find an answer of what to do from there. Do I print it? If I do print it... how do I used javascript to grab it. I can't use the php variable name since javascript doesn't understand it. I am just not grasping this concept.
The most popular way to make a Javascript script communicate with a PHP script is via Asynchronous Javascript And XML (AJAX) requests.
In AJAX requests, your javascript code calls the PHP script needed, sending to it any required parameters. Then, your PHP script should print (echo) the result (the JSON encoded array in your case), and when it does, an event gets fired in your javascript code, which you can handle accordingly.
In Javascript, there are two main ways of performing AJAX requests:
1- Using the XMLHTTPRequest object:
In this method, we are using a Javascript XMLHTTPRequest object to send the request to our PHP script, and we handle its onload event to get the response and do something with it :
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "some_url.php?param1=123");
xmlhttp.send();
xmlhttp.onload = function() {
//here the response from the PHP script is saved in the this.responseText variable
//parsing the JSON string we got into an actual array
var myArray = JSON.parse(this.responseText);
//do something with the array
}
(note that we can also handle the object's onreadystatechange, but onload is a bit simpler to handle)
2- Using a promise (fetch):
fetch("some_url.php?param1=123")
.then(function(response) {
return response.text();
})
.then(function(data)) {
var myArray = JSON.parse(data);
//do something with the array
});

Accessing data returned by GET request using Javascript

Hi I'm trying to use Javascript to write a chrome application that will show your last number of tweets but I'm having trouble getting the tweets. I'm a newbie to javascript but I have searched quite a bit and can't find an understandable answer to this.
From chrome and twitter I have the following code.
<script type="text/javascript">
var req = new XMLHttpRequest();
req.open(
"GET",
"https://api.twitter.com/1/statuses/user_timeline.json?
include_entities=true&include_rts=true&screen_name=twitterapi&count=3")
</script>
This GET request works but how do I use the data it returns with javascript?
The result is in the req.responseText. You can append it o your document, to see what the response is. It actually depends on what is the response. I mean maybe you need to alert the response, or show it somewhere, or put it in a condition operator and compare with something... Some basoc use:
alert(req.responseText);
document.body.innerHTML+=req.responseText;
It is somewhere in req.responseText. That is, you need to set req.onreadystatechange and once it's ready you'll have it in there.

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

Passing JavaScript variable to Python

For example:
#!/usr/bin/python
print "This is python."
print "<script type="text/javascript">
var pass_to_python = new Number(7)
</script>"
the_number = pass_to_python???
How do I get the pass_to_python in python?
With pyv8 you can execute javascript from within Python.
import PyV8
class Global(PyV8.JSClass):
pass
with PyV8.JSContext(Global()) as ctxt:
the_number = ctxt.eval("var pass_to_python = new Number(7)")
see http://code.google.com/p/pyv8/
You can GET or POST to the Python script. If you need to do this dynamically, you can use AJAX.
Here is a good link: How are POST and GET variables handled in Python?
i am using flask and ajax to pass values from javacript to python
function pass_values() {
var pass_to_python = new Number(7)
$.ajax(
{
type:'POST',
contentType:'application/json;charset-utf-08',
dataType:'json',
url:'http://127.0.0.1:5000/pass_val?value='+pass_to_python ,
success:function (data) {
var reply=data.reply;
if (reply=="success")
{
return;
}
else
{
alert("some error ocured in session agent")
}
}
}
);
}
python:
#app.route('/pass_val',methods=['POST'])
def pass_val():
name=request.args.get('value')
print('name',name)
return jsonify({'reply':'success'})
HTTP is a simple request-response protocol, it doesn't let you pause mid-stream and wait for more information from the client — and since your JS runs in the browser (JS can run on the server, but most people wouldn't be attempting this if they didn't need the code to run in the browser, so I'm assuming that using server side JS is out of the question) and the Python runs on the server, that is what you need for your code to work (as well as fixing your broken quote nesting in the Python code).
You need to load the complete document, and then issue a new HTTP request.
This might involve having the JS set location.href (making sure you have a fallback for non-JS clients), it might involve using XMLHttpRequest to load new data asynchronously, it might be best using another technique (it is hard to say for sure as your example simplifies too much to tell what X is)
I think using JSON is the best way.you can create a JSON file as intermidiary between JavaScript and Python, both languages can access and modify JSON file

Categories