put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script
This is my HTML page:
<html>
<head></head>
<body>
<script src="file.js"></script>
</body>
</html>
I can not get the following javascript code to send data to a PHP page:
this is inside file.js
var http = new XMLHttpRequest();
var url = 'server.php';
var params = 'a=use&b=12345678';
http.open('POST', url, true); // error javascript stop always here
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200)
{ alert(http.responseText); } }
http.send(params);
and this is inside server.php:
<?php
$username = $_POST['a'];
$password = $_POST['b'];
echo 'username :' . $username;
?>
When I put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script tag?
for example when i put the file.js script in online compiler like 'playcode.io' it does not work
It doesn't matter whether you put the javascript code directly in the HTML page or add it to the script using the src attribute on the script. The problem is, you aren't setting a request header with setRequestHeader(). Add the following line of code just after http.open(), but before http.send() and it'll definitely work:
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
The application/x-www-form-urlencoded format provides a way to encode name-value pairs.
Related
I have a html page called index.html. Inside it I use js to send JSON to other page (loja.html) and right after that I load this page. I would like to read the contents of JSON on loja.html and use it to populate some html tags. Here's my code:
piece of index.html's
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
}
}
ajax.open("GET", "http://localhost:8080/DBRest/loja.html",true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(dataToJSON(nome,idade));
console.log(dataToJSON(nome,idade));
window.location = 'http://localhost:8080/DBRest/loja.html';
piece of loja.html's js:
window.onload = function() {
alert('alert');
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
alert(JSON.parse(ajax.responseText));
}
}
}
When I load loja.html from index.html none of alerts are displayed. when typed on browser, only first alert is displayed. How can I correctly send data to loja.html from index.html and after it immediately load loja.html?
Javascript lives/executes within the current browser window/location; if loja.html isn't currently loaded, it won't do anything as the javascript on that page hasn't been run. You'll need a server-side component to accept the GET (not POST) request that you're making and store the data. loja.html can then load that via Javascript.
You have a few options to move data between pages:
Store Data in Local Storage
Store Data in a cookie
Add data to the URL via query parameters
Query the database on the new page to retrieve the data.
Without using a SPA, there isn't a direct way to move data from one html page to another html page.
I want to write a JavaScript to return contents of a webpage when URL is given and enter those contents as a data in table?
The alert pop up is not working.
Return HTML content as a string, given URL. JavaScript function returns a blank screen.
Here is my code:
<html>
<head></head>
<body>
<script type="text/JavaScript"> function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
document.write(httpGet("stackoverflow.com/")); </script>
</body>
</html>
You can simply get contents of a webpage by using javascript's ajax
var contents="";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
contents=this.responseText;
}
};
xhttp.open("GET", "webpage.html", true);
xhttp.send();
Although you can also manipulate HTML you should make sure that webpage.html is showing the data in a valid format for you to easily manipulate. Like JSON, xml or anything else so that you can use the data in the contents variable and iterate over it for your insert statements.
The reason because its showing a blank screen is because of the cross origin policy. stackoverflow.com does not allow CORS(cross origin requests).
And one more thing,, Until and unless you are requesting from a relative Url, specify the address with the protocol name.
Like : 'stackoverflow.com' to 'http://stackoverflow.com'
So just change the address to your file and it will work fine. :)
I have a PHP file, having HTML and JavaScript code also,
I want to use the javascript variable value in the php code,
Sample code is as follows:
<script>
function dropdown(){
var e = document.getElementById("im_position");
var strUser = e.options[e.selectedIndex].value;
}
</script>
<?php
$q = //here want to use strUser(javascript varible);
?>
How do I use it ?
Help me..
You can't access to javascript variable like that. PhP is execute by the server and JavaScript by client.
You can create an ajax function in JS who call your php script.
http://www.w3schools.com/ajax/
Here you can learn to use Ajax.
JS
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
xhttp.responseText // return from your php;
}
};
xhttp.open("GET", "yourphp.php?variable="+yourjsvariable, true);
xhttp.send();
}
Php
<?php
return $_GET["variable"];
?>
You can't.
Php runs server-side. Javascript runs client-side.
This means that php compiles into html and does not reach the client. Javascript runs on the client's browser.
Your best solution would be to use ajax.
I'm abit confused as to how i will go about doing this, so i'm making a .js file to collect data on a page(100% with js) and i want to POST it to a php file which will then take care of it and insert it into the db etc..
How will i go about doing this? I know you can use jquery in a html document, but i want to use it in a .js file not a .html file.
I've successfully done it using a .html file and importing the jquery file, but i want to do it all in a .js file.
Any help is greatly appreciated. Thank you very much (:
I'd comment, but I can't. Can you post some samples of your code?
What I got is that you are using JavaScript (jQuery) to POST (form data?) over to a PHP file. If you want to use jQuery inside of a .js file, all you have to do is include the jQuery library before you include your .js file, like so:
<script src="jquery.js"></script>
<script src="myExternalScript.js"></script>
And then, inside of myExternalScript.js, you can use jQuery methods.
The external script is aware of your DOM elements, really, just like inline JavaScript would be, so you can still do whatever you want with your form or wherever you are getting the data to POST from.
EDIT: (in accordance to what you commented on this answer)
EDIT 2: I had forgotten to add the request header for POST
If you want to send an AJAX POST request (notice that I set the Content-Type request header, so that the data gets sent correctly):
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://zegita.tk/stargazer/magic.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("n="+user);
If you want to send an AJAX GET request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://zegita.tk/stargazer/magic.php?n="+user, true);
xmlhttp.send();
It is important that you use the correct method, depending on whether you are using $_GET or $_POST in your magic.php file.
Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)
<script type="text/javascript">
function sendJSValsToPHP(){
var xmlhttp;
//These are the variables i am going to post to illustrate the example, what you want
var var_1toPost = 1;
var var_2toPost = 2;
var var_3toPost = 3;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//You can get the response text from abc.php file and process it in any of the tags you want by javascript code
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
xmlhttp.send();
}
</script>
The echo'ed data in abc.php will come in the div="myDiv" //as a response.
<body>
<div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
the things echo'ed in abc.php will come in this div
</div>
<button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>
and then in abc.php //file
<?php
$recieved_1 = $_GET['recieve_1'];
$recieved_2 = $_GET['recieve_2'];
$recieved_3 = $_GET['recieve_3'];
//Do your processing here and insert it in the database
//Insert Query OR Update Query (whatever)
// after you have inserted you can get the response in
// the <div> having id="myDiv" Or whatever you want
// Suppose you have successfully inserted data then
$insertedDataBoolean = true;
if($insertedDataBoolean){
echo "Data: " . $recieved_1 . ", " . $recieved_2 .
" and " . $recieved_3 . " inserted successfully.";
}
else{
echo "Data-insertion error.";
}
?>
What my php side does is load data use 'id' from database, and then show the raw data of swf files.
The code of php like this:
<?php
if(isset($_GET['id']))
{
include ('database.php');
$record = mysql_query("SELECT `Flash`, `FlashBlob` FROM `information` WHERE `id` = '". $_GET['id'] ."'; ", $link);
$swf = mysql_fetch_array($record);
mysql_close($link);
header("Content-type: " . $swf['Flash']);
echo $swf['FlashBlob'];
exit;
}
So if I just load the php in the web link, it goes well( the whole php page will show the flash I stored in database).
In my main page, I want to load the page into my div($("#gameArea")), I have tried:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", 'api/swfInfo.php?id=' + id,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('gameArea').innerHTML=xmlhttp.responseText;
}
}
but the result is it load only raw data( binary data) not the flash(swf file to be shown), what should I do?
I even not sure whether I should find a flash plugin for my flash or not
because I put my flash(swf file) in the database for some reason......
Please help me for the direction, thanks in advance!
Your overcomplicating the problem. If in-fact your swfInfo.php is outputting the swf file's bytes with a content type of application/x-shockwave-flash all you need to do is set the data attribute of your <object> tag to that URL.
<object type="application/x-shockwave-flash" data="api/swfInfo.php?id=7">
<param /> <!-- parameters -->
</object>
I would also recommend a content-length declaration to ensure your connection closes properly when loading files this way.
header('Content-length: ' . mb_strlen($swf['FlashBlob']));
header('Connection: close');
Try the following:
header('Content-Type: application/x-shockwave-flash');
header("Content-Disposition:attachment; filename="test.swf");
My questions are:
What is $swf['Flash'] ? Maybe there is the error?
Have you tried your script with a file_read_content() just for debugging reasons?