I created a php page and javascript code that contains some variables from the PHP page, this is a code that inserts php variables into the database using Javascript :
<?php
$id = "Kevin";
$user = "Calvin";
?>
<!-- include jquery library file-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: <?php echo json_encode($id); ?>, to: <?php echo json_encode($user); ?>},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
</script>
and in the full.php page
<?php
mysql_connect("localhost","root","");
mysql_select_db("db");
$to=mysql_real_escape_string($_POST['to']);
$from=mysql_real_escape_string($_POST['from']);
$msg=mysql_real_escape_string($_POST['msgg']);
$to = mysql_real_escape_string($to);
$from = mysql_real_escape_string($from);
$msg = mysql_real_escape_string($msg);
if(empty($msg)){
exit();
}
$query=mysql_query("INSERT INTO `message`(`user`,`who`,`message`) VALUES ('$to','$from','$msg')");
if($query){
echo "Perfect!";
}else{
echo "Failed!!";
?>
so is there any way to put the Javascript code into another page and inject it using ajax?
Assign PHP variable's value to java script variable :
<script type="text/javascript">
var json{
"id":<?php echo $id;?>,
"user" : "<?php echo $user;?>"
};
</script>
Change this line from your code :
$.post('full.php', {msgg: msg, from: json.id, to: json.user}
Now you'll have separate js file like:
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: json.id, to: json.user},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
Say this file is myjs.js now include it in php file:
<script type="text/javascript" src="myjs.js" />
Related
I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});
I am unable to print data in the first run but can get it to print in the second run.I want to print data in first run itself.
i have 3 files
1. main files sends ajax post,print data(main.php)
2. put sent data into session(put.php)
3. print data into excel(print.php)
main.php
<?php
session_start();
echo '<p class="first">ABC</p>'; //DOM IS <p class="first">ABC</p>
?>
$(document).ready(function(){
var value = $('.first').text();
myfun();
function myfun(){
$.post("put.php", {"content":value},function(data){
console.log(data);
});
}
window.location.href ='print.php';
});
put.php
<?php
session_start();
$_SESSION["content"] = $_POST["content"];
?>
print.php
// these file print into excel code is simple
<?php
session_start();
header("content-type:application/xls");
$table = '<table><tr><th>Name</th></tr>';
$table .='<tr><td>'.$_SESSION["content"].'</td></tr></table>';
echo $table;
header("content-Disposition: attachment; filename = new.xls");
?>
please help me,thanks in advance.
Why
js won't stop exec when ajax not complete,
so you should redirect after ajax complete to make sure $_SESSION["content"] has set
Fix
change
$(document).ready(function(){
var value = $('.first').text();
myfun(); //i was missing then
function myfun(){
$.post("put.php", {"content":value},function(data){
console.log(data);
});
}
window.location.href ='print.php';
});
to
$(document).ready(function(){
var value = $('.first').text();
myfun(); //i was missing then
function myfun(){
$.post("put.php", {"content":value},function(data){
console.log(data);
window.location.href ='print.php';
});
}
});
First PHP Page and Jquery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript">
function get_ver() {
$(document).ready(function() {
var ver = $("#OSVER option:selected" ).text();
alert (ver);
$.ajax({
type : 'POST',
url: 'create_policy.php',
data: { 'OSVER' : ver }
});
});
}
</script>
<?php
<b><a href='index.php?xtype=create_policy&pol_id=$pol_id&pol_type=$pol_type' class='texthidevisi' onClick='get_ver()' >Edit |</a></b>
Second PHP Page :
<?php
$ver=$_POST['OSVER'];
echo "Version is $ver";
?>
In the first php page I am calling jquery function get_ver() which will get the values from drop down box. I am able to get the value selected in the jquery variable "ver", but I am not able to get it second php page.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a button in my php page :
<button id="myButton">Delete me</button>
and in that page I have a variable which I want to pass to a JavaScript function, and this is my JS code :
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
How can I do that ?
I think you might be wanting to put a variable through PHP on your button and pass it to your function using jQuery data. Check this out:
<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button>
And in your js:
$(function() {
$('#myButton').on('click', function(e){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var confirmed = $thisButton.data('confirmed');
if(confirmed) {
//Here I'll use the variable
}
})
});
Basically, you can access variables in javascript using this method if you are interpolating PHP vars directly on the page. If this isn't what you are looking for, please let me know in comments.
<button id="myButton">Delete me</button>
<input type="hidden" name="variable" id="variable" value=2>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {=
alert(document.getElementById('variable').value);
//Here I'll use the variable
}
})
});
You can declare the variable outside the click event like so:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});
Assuming you're talking about passing php variables to Javascript, you can do this when writing to the page, ex:
<?php
$passThis = 'Passing'
?>
<script language="javascript" type="text/javascript">
var sStr = "My name is <?php echo $passThis ?>.";
document.write(sStr);
</script>
You could also get integer values, doing something like
$integerValue = 5;
var int = "<?php echo $integerValue; ?>";
int = parseInt(int);
By modifying this, you could use it to pass more types of variables, so assuming you have something like this:
<?php
$text = 'someText';
?>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
you could do
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
to make Javascript alert 'someText'.
this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name, email: email}, function(data){
$('#show').html('settings saved').fadeIn(500).delay(2000).fadeOut(500);
alert(data);
});
});
If you want to communicate between JavaScript and PHP, the best way is to create a hidden-inputfield in fill in the errors-variable. And then you can read out the value with jQuery.
The inputfield:
<input type="hidden" value="<?php echo $error; ?>" id="errors" />
And the jQuery-Code:
var errors = $("input#errors").val();
You can't place PHP code inside "javascript" file, PHP code must be in PHP file.
The below code can work if it's placed in .php file:
<html>
<head>
<title>javascript test</title>
<script>
var error = '<?php echo $error;?>';
alert(error);
</script>
</head>
<body>
</body>
</html>
I am assuming that your $error will by different depending on the $_POST values.
If your response header is in HTML, then you can do something like this.
// in your JS codes.
$.post('settings.php', function(response) {
$('#show').html(response).fadeIn(500).delay(2000).fadeOut(500);
});
// in your php codes.
<?php if(isset($error)) { echo($error); } else { echo("setting saved"); } die(); ?>
Anything you want in your js from server side has to come as AJAX or JSON response. echo it from your php function and get it as AJAX or JSON in javascript.
$.getJSON('url for the php file', function(data){}
And in the php file just echo the value
see http://php.net/manual/en/function.json-encode.php
Or take a hidden input field and put the value there. You can get that value from js using the 'id' or 'class' attribute