I get info in javascript dialog like this:
<!DOCTYPE html>
<html>
<body>
<script>
var myInfo = prompt("Please enter info", "");
if (myInfo != null) {
//Here is my info
}
</script>
</body>
</html>
How can I send this "myInfo" to PHP file (in the same server of javascript file) via GET, POST or by other method?
This is fairly easy with ajax,
PHP Code:
<?php
$data=$_GET['data'];
//Do something with it
echo 'Response';
die();
?>
HTML Code:
<!DOCTYPE html>
<html>
<body>
<script>
var myInfo = prompt("Please enter info", "");
if (myInfo != null) {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;
//Do someting with it
}
}
xmlhttp.open("GET","/file.php?data="+myInfo,true);
xmlhttp.send();
}
</script>
</body>
</html>
Instead of using native ajax you can use jquery and ajax to send data like below
<!DOCTYPE html>
<html>
<body>
<script src="jquery-1.11.3.min.js"></script>
<script>
var myInfo = prompt("Please enter info", "");
if (myInfo != null) {
$.ajax({
url: "php_page.php",
data: {
info: myInfo
},
success: function( data ) {
alert( "data sent" );
}
});
}
</script>
</body>
</html>
You will have to use jquery.js inorder to use this ajax functionality. On your php page you can directly refer the variable using $_REQUEST method as below
<?php
$data= $_REQUEST['info'];
?>
for more info on how jquery works you can refer to jquery.com
Related
I wanted to perform jquery post to php and get the data and post to the console log. But however i cant find data on the console.log after performing post the data. my code is found below...........please help me...
student html page
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post("student.php",
{
PostLastName: "Abdullah",
PostLastReligion: "Muslim"
},
function(data)
{
console.log(data);
});
});
</script>
</body>
</html>
student.php script
<?php
if ((empty($_POST["PostLastName"])) && (empty($_POST["PostLastReligion"])))
{
//Return "Posted Values are empty" if the values is empty
$post_string = 'Posted Values Are Empty';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
else
{
//Return the Post Data
$post_string= 'Post Last Name = '.$_POST["PostLastName"]."\n".' Post Last Religion = '.$_POST["PostLastReligion"].'';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
?>
I have test your code. i think check first check your loaded jquery included in header.
After change some code like below mention and test your browser console.
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post( "student.php", { PostLastName: "Abdullah", PostLastReligion: "Muslim" })
.done(function( data ) {
console.log(data);
});
};
</script>
</body>
</html>
I hope u resolve u r issue.
I am running XAMPP and Apache. I have two files:
index.php
<html>
<head>
<title>php script</title>
</head>
<body>
<?php
header("Access-Control-Allow-Origin: *");
echo "hello world";
?>
</body>
</html>
post.html
<html>
<head>
<title>html page</title>
</head>
<body>
<script>
var xhr;
xhr=new XMLHttpRequest();
xhr.open("POST", "http://localhost/demoApp/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send();
</script>
</body>
</html>
I want post.html to call index.php so that post.html displays "hello world" on the html page. When I open index.php, I see "hello world."
I also know that post.html is calling index.php because I have other script that when copied into index.php will successfully send me an email if I open post.html.
If post.html is indeed calling index.php, why is my echo not displaying on post.html?
post.html is making a request, but you're not actually doing anything with that request. When using ajax, javascript is making the call and you need to tell it explicitly what you would like to do with the response.
To simply alert the remote content, listen on the onreadystatechange event, and when it's 4 (Complete), show an alert:
xhr.onreadystatechange = function() {
if(xhr.readyState==4) {
alert(xhr.responseText);
}
}
If you wish to append the data anywhere (Without using jQuery), I recommending assigning a div with an ID, and appending or assigning the data:
index.php:
<?php
header("Access-Control-Allow-Origin: *");
echo "hello world";
?>
post.html:
<html>
<head>
<title>html page</title>
</head>
<body>
<div id="remote_content"></div>
<script>
var xhr;
xhr=new XMLHttpRequest();
xhr.open("POST", "http://localhost/demoApp/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState !== 4)
return;
document.getElementById('remote_content').innerHTML = xhr.responseText;
}
xhr.send();
</script>
</body>
</html>
The following code should add 100 to an existing number in a mysql table if the button gets clicked. If I click the button nothing happens, but if I reload the page the function adds 100 to the number. What is wrong with my code?
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
<?php
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
?>
});
</script>
</html>
You cant call PHP code from a jQuery function like that. All the php runs when the page loads and thats it. You can however use jQuery and Ajax to send a message to a php script that processes that message then returns a response. The script can even be in the same actual file like you have (or in a different file altogether) something like this would do:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
if(isset($_POST['updateTest']){
$val = $_POST['test'];
$id + $_POST['userId'];
// validate inputs and such....
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
// send success or error response...
echo json_encode(['success'=>true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
var count = 100;
var userId = 1;
var dataObject= {updateTest: true, test: 100, userId: 1};
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataObject,
success: function(response) {
if(response.success){
alert('test worked');
}
else{
alert('there was an error')
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</html>
As mentioned by the previous poster PHP is server side and Javascript client side so what is actually happening is the following.
When the page is returned back to the user your piece of javascript just looks like the below..
Your MySQL statement here has executed already it can not interact with client side code in this way
<script>
$("#button").click(function(){
// nothing here.. But your MYSQL statement has executed anyway
});
</script>
I have two script files - one is perl-cgi and the other is javascript. Inside the cgi script I have written the Javascript function for retrieving data from a text file (using ajax). I then pass the contents of the data into another function called main_function(). This writes into the javascript file (seq_new.js). When I load the page, the console.log reports main_function was not defined. Then I refresh the page and the result displays. I don't know why it behaves this way.
The Perl script as follows:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
use CGI;
my $a= new CGI;
my $processId = $a->param("processId");
.
.
my $file_path = "/$processId/$file_name[1]";
print <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>RepEx - Result</title>
<script type="text/javascript" src="/min.js"></script>
</head>
<body>
<script>
file_load("$file_path","$filename");
function file_load(f1,f2)
{
var fileNm = f2;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var pt = xhttp.responseText;
main_function(pt,fileNm,"$file_path",$file_cnt,"$head_st");
}
};
xhttp.open("GET", f1, true);
xhttp.send();
}
</script>
<script type="text/javascript" charset="utf-8" src='/seq_new.js'> </script>
</body>
</html>
My javascript file contains this:
function main_function (a,file_seq,main_file,fle_cnt,header_set)
{
.
..
}
The problem I am encountering
Loading the page for the first time, the console.log reports that the main_function was not defined and no results are displayed. After refreshing the page (by pressing F5 or clicking the reload button), the result is displayed.
I'm trying somthing else that sends parameter form file.php (that has javascript written <script> .... </script>). I am trying to pass parameter to other file file2.php but I am failed to do so. (sorry for my bad english). here is the code that i am trying.
file.php
<html>
<head>
</head>
<body>
<script type="text/javascript">
function changeThis(){
var formInput = document.getElementById('theInput').value;
document.getElementById('newText').innerHTML = formInput;
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "event2.php?theInput"= + formInput, true );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
<!-- <p>You wrote: <span id='newText'></span> </p> -->
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
file2.php
<?php
$id = $_GET["theInput"];
echo $id;
?>
You've commented out <span id='newText'></span>, so document.getElementById('newText') will be undefined so trying to assign a value to document.getElementById('newText').innerHTML will throw an exception and your function will terminate at that point.
Either stop trying to modify an element you've removed, or put the element back.
Other that that, this will successfully send the data (although you really should URL Encode the user input you are stuffing into the query string). It just won't do anything with the response as you don't have a load or readystatechange event handler on the XHR object.
Your first scipt could work, just change :
xmlHttp.open( "GET", "file2.php?theInput=" + formInput, true );
Wrong :
xmlHttp.open( "GET", "event2.php?theInput"= + formInput, true );
Your php filename seems to be file2.php and not event2.php
You must have = between the ""
your old script corriged :
<html>
<head>
</head>
<body>
<script type="text/javascript">
function changeThis(){
var formInput = document.getElementById('theInput').value;
document.getElementById('newText').innerHTML = formInput;
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "file2.php?theInput=" + formInput, true );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
<p>You wrote: <span id='newText'></span> </p>
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
file.php
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.10.1.min.js'></script>
<script type="text/javascript">
function changeThis(){
$.ajax({
type: "POST",
url: "file2.php",
data: {theInput:theInput},
dataType: 'json',
success:function(data){
$('#newText').html(data.newText);
}
});
}
</script>
</head>
<body>
<span id='newText'></span>
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
file2.php
<?php
$arr = array();
$arr['newText'] = '';
if(isset($_REQUEST['theInput']))
{
$arr['newText'] = $_REQUEST['theInput'];
}
die(json_encode($arr));
?>
First make sure event2.php and file2.php is same file. then try to use escape .
xmlHttp.open( "GET", "event2.php?theInput="= + encodedURIComponent(formInput), true)