Writing in another file with javascript - javascript

I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.

Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp

PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation

Related

How to run PHP code in a JavaScript Function?

I am trying to make a function to open a webpage in the same tab as the one you are coming from, (think clicking on a bookmark in a tab). I have the page I want to go to and I know the PHP code to do what I want,
<?php
header("Location: example.php")
?>
I am wondering if there is a way for me to run PHP code in JavaScript so I can do what I want?
(Before anyone asks why I don't just run the code this way, it's because the situation I am in requires me to run the code through a JavaScript function)
You don't need PHP for page redirection. You can simply do this in pure javascript.
function gotoExample() {
window.location.href = './example.php';
}
Mixing PHP and javascript introduces complication to your code. Avoid that if possible.
There are various ways on how you can run a php script inside a js function. One way is via ajax.
//some js logic here
if (foo) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "http://foo.bar/path/to/a/script.php", true);
xhttp.send();
}
What happens on the above code is that when foo evaluates to true, than a XMLHttpRequest is called and a server side script written in php is executed.
However, in your case, it It is better to just handle a redirect on the client side rather than relying on PHP.
if (foo) {
window.location.href = 'http://foo.bar/path/to/a/script.php';
}
There are various ways on how to issue a redirect via js. The interned is huge. You'll find it with just a couple of searches.

AJAX xmlhttp.send() not working

I'm a complete and utter AJAX noob and have been sitting with the same problem for the last 5 hours.
My script code
<script language='javascript'>
function upvote(id ,username)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
};
xmlhttp.open("GET", "vote.php?id=" +id+"&username=" +username, true);
xmlhttp.send();
}
</script>
My onclick link,
<a href='javascript:void(0)' onclick='upvote($id,$username)'></a>
$_GET is used to retrieve parameters sent via the URL of the page. For example
../vote.php?id=3&username=anor
My php file works perfect when i tried that.
I don't think there's anything wrong with the PHP anyway. For some reason however, xmlhttp.send(params) is still not sending the required variables to the vote.php file. I tried post AJAX request but it didn't work either.
edit them
If php file
$id = '1';
$username = 'suman';
echo '';
?>
If this is part of your PHP code
onclick='upvote($id, $username)'
it won't work. It should be
onclick='upvote($id, "$username")'
instead. Let's see the example that you posted: $id=3 and $username=anor. This would result in
onclick='upvote(3, anor)'
As long as there is no Javascript variable with the name anor, this would be equivalent to
onclick='upvote(3, undefined)'
Do you get that?
PS: The upvote function itself seems to be fine

POST data with ajax

I'm trying to save a few lines of text in a textarea with ajax targeting a classic asp file.
I'm not sure how to use ajax when when it comes to sending data with POST method and NOT using jQuery, didn't find any questions concerning this here either, no duplicate intended.
Ajax function:
function saveDoc() {//disabled
var xhttp = new XMLHttpRequest();
var note = document.getElementById("note");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("0").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "saveNote.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(note);
ASP Classic:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\1.txt",8,true)
dim note
note = RequestForm("note")
f.Write(note)
f.Close
Response.Write("Works.");
set f=nothing
set fs=nothing
I'm aware there might be a lot wrong with the .asp since i couldn't find any specific info about how to handle ajax requests with Classic ASP correctly.
Any suggestions on how to make this work without jQuery are welcome.
I cannot test your code as I don't have a backend running on my machine right now. But I can already tell you a few things:
you are calling xhttp.send(note); but your note is a DOM element. It should be a string with a querystring format.
in your server side code you call RequestForm is it a custom function you have previously defined ? The usual syntax is Request.Form
Hope it can help

Javascript : Different behavior when run on machine and local server

Because my title is too short, I will explain more clearer. I have create a code in JavaScript . And I have two options to run :
1) Run on machine : simple click into html file.
2) Run on local server : mean I start Apache, and start this html file in localhost.
( http://localhost:85/Javascript/index.html for example)
When I choose solution 1, no thing happen. And when I choose solution 2, happen as I wish. But I don't know why.
Here is my code. Purpose : take a json file and process it.
<script>
window.onload = function(){
var url = "http://localhost:85/javascript/json1.json"; // problem here
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function(){
if (request.status == 200){
update(request.responseText);
}
}
request.send(null);
};
function update(responseText){ // some code here }
</script>
You cannot use AJAX to read content from a different domain.
Javascript running from file://whatever cannot read localhost:85.
Did you replace this line with the server's original path?
var url = "http://localhost:85/javascript/json1.json";
With
var url = "http://10.0.0.X:85/javascript/json1.json"; // Did you change the right path?
And make sure, the page is not called with the file:// protocol!

How can I open a JSON file in JavaScript without jQuery?

I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.
I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it

Categories