How get variable from ajax in another php file - javascript

The problem is when I click on "submit data" button I get the response (this is correct), but when I click on "go to the php file" link (which is the same php file as previously) I get Undefined index: firstname and Undefined index: lastname error. How can I fix it?
Here is my code:
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
go to the php file
</body>
and the php file
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>

Because both are different requests :
As you are passing parameters firstname and lastname using AJAX. You have to pass the same in URL using GET request.
go to the php file
<?php
echo 'Thank you '. $_REQUEST['firstname'] . ' ' . $_REQUEST['lastname'] . ', says the PHP file';
?>
Output :
Thank you abc xyz, says the PHP file
It will work in both Submit button and Hyperlink.

By clicking the link your browser sends not a POST request, but a GET request to your server-side. That is why the global array $_POST doesn't contains the elements you are trying to retrieve in your PHP file. The error message points you that there is no such elements in the $_POST array like "firstname" and "lastname".
It is recommended to add a check whether the array elements exist like so:
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
} else {
echo 'Nothing to say';
}

Thanks R J for explanation. Now i fixed it and works properly.
But I am worried, because i used this code only for training. In my main problem i need to send the real object (not string etc.) by ajax to my php site, so i cant add it to the url, can I?

Related

How to pass javascript variable to PHP file [duplicate]

I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.

php doesn't receive string value from ajax

I'm trying to send the id of a clicked element via ajax to php. But it isn't working. The value is being sent from php file (contacts.php) to the javascript function callMessage(id) (which does return the right id when clicked), it is then calling the php file (get_message.php) which is supposed to query the result which has the right id. But when I echo the id it returns "Undefined variable".
Here's my code:
contacts.php
<div id="<?php echo $row['id']; ?>" onclick="callMessage(this.id)">
</div>
<div id="createMsg"></div>
contacts.js
function callMessage(id) {
var http = new XMLHttpRequest();
var url = 'includes/get_message.php';
http.open('GET', url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("createMsg").innerHTML = this.responseText;
}
}
console.log(id);
http.send('id='+id);
}
here console.log(id) does return the id of the element that was clicked.
get_message.php
if(isset($_GET['id'])) {
$msg_id = $_GET['id'];
}
echo $msg_id;
The echo here returns "Undefined variable: msg_id". I've also tried using POST request to send the id value but that hasn't worked either.
A couple of issues:
echo $msg_id; should be inside the if in the PHP. Logically you don't want to echo that if it isn't populated, I would expect.
As per https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send, the 'id='+id will be added to the request body, whereas $_GET in PHP tries to retrieve values from the querystring. Therefore you need to attach the value to your url variable, and url-encode it.
So
if(isset($_GET['id'])) {
$msg_id = $_GET['id'];
echo $msg_id;
}
else echo "No ID supplied";
and
var url = 'includes/get_message.php?id=' + encodeURIComponent(id);
...
http.send();
is the correct solution here.
You are placing the data in a GET request with the 'send' function.
Submitting data via send is relevant for POST & PUT.
Data under send() for GET & HEAD will be replaced with NULL.
If you're using GET method use the URL parameter:
var url = 'includes/get_message.php?id=' + encodeURIComponent(id);

How to send an email with emailjs?

So I have been trying to set up a contact page for a client and I am currently using emailjs to do it but it keeps coming up with errors when sending test emails to see if it works.
I have tried going onto the website for emailjs to find out what is wrong with it but I come up with nothing.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles2.css">
<link rel="stylesheet" href="css/newheader.css">
<link rel="stylesheet" href="css/contact.css">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script type="text/javascript" src="https://cdn.emailjs.com/sdk/2.3.2/email.min.js"></script>
<script type="text/javascript">
(function(){
emailjs.init("user_ID"); // i have the user id in the code I just didn't want to post it online
})();
</script>
<script type="text/javascript">
window.onload = function() {
document.getElementById('contact-form').addEventListener('submit', function(event) {
event.preventDefault();
// generate the contact number value
this.contact_number.value = Math.random() * 100000 | 0;
emailjs.sendForm('contact_service', 'contact_template', this);
});
}
</script>
</head>
<body>
<header>
{{>header_2}}
</header>
<form id="contact-form">
<input type="hidden" name="contact_number">
<label>Name</label>
<input type="text" name="user_name">
<label>Email</label>
<input type="email" name="user_email">
<label>Message</label>
<textarea name="message"></textarea>
<input type="submit" value="Send">
</form>
</body>
</html>
The expected result is to send a test email to get things going but for some reason it is not working, it comes up saying bad request so I am unsure what to do.
Sending a an email is super easy, you dont need a plugin. First lets get your form ready; add these attributes to the form.
<form id="contact-form" method="POST" action="PHP/mailto.php">
now its time to set up a js script:
// first things first you gotta listen to the submit event and stop it from
// performing the 'action' which is redirecting the form data to the php
// file we are going to create.
document.getElementById('contact-form').addEventListener('submit', function(event){
//this prevents the form from doing its default action: redirection
event.preventDefault();
// disable inputs so form can only be sent once
$disabled_inputs = document.querySelectorAll('input, textarea');
for(i = 0; i < $disabled_inputs.length; i++){
$disabled_inputs[i].disabled = true;
}
// empty JSON object that will hold form data
var data = {};
//this function will loop through the data and collect the info on the inputs
// and text areas with a name attribute
this.querySelectorAll('input[name], textarea[name]').forEach(function($input) {
// this formats the data in a JSON object {inputname : inputvalue}
$data[$input.getAttribute('name')] = $input.value;
});
// take a look at the console so you get used to the json format
console.log($data);
// this will store the data in a JSON object so you have to clean it to send
// it to the php file with a post variable set
var json_upload = "your_php_postvariable=" + JSON.stringify($data);
// open new ajax request
var inquriry_request = new XMLHttpRequest();
// declare ajax method and origin (look at the form element)
inquriry_request.open("POST", "/PHP/mailto.php");
// declare cleaned JSON format to PHP file
inquriry_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// send ajax request with data
inquriry_request.send(json_upload);
// this functions runs after ajax request loads response
inquriry_request.onload = function(){
// create new script element
scripter = document.createElement('script');
// declare javascript type
scripter.type = 'text/javascript';
// load script echoed from php file inside this tag
scripter.innerHTML = inquriry_request.responseText;
// append script to body (this will cause script to run)
document.querySelector('body').append(scripter);
}
});
now lets set up the mailto.php file:
<?php
// run this function if post variable is set
if(isset($_POST['your_php_variable']){
// this while output an error log inside the /PHP/ directory
error_log(0);
// html email headers
$headers = "From: Web Emails <your#email.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// php post variable loop input attributes
var $php_post_var_loop = $_POST['your_php_variable'];
$name = $php_post_var_loop['user_name'];
$email = $php_post_var_loop['user_email'];
$message = $php_post_var_loop['message'];
// strings in php are appended by dots
$email_text = "From: ". $name . "<br><br>".
"Email: " . $email . "<br><br>".
"Message: " . $message;
// run if statement to check if php function ran to send mail
if(#mail('your#email.com', 'Email Subject', $email_text, $headers)){
// use this if you have to switch between single and double quotes
// inside your js script
$quo = '"';
echo "//js code to run if mail sends!"
} else {
// use this if you have to switch between single and double quotes
// inside your js script
$quo = '"';
echo = "//js code to run if mail does not send"
}
}
?>

How to send or pass a javascript variable to a php file? [duplicate]

I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.

Using AJAX to send form data to php script (without jQuery)

I am trying to do a basic AJAX implementation to send some form data to a php script and db. I'm just doing this for learning purposes, and have taken it as far as I could. When I hit the "Create Profile" button, nothing is happening. From my code below, does anything obvious jump out at anyone in my syntax/structure?
Note* I've yet to implement the code to retrieve the data using AJAX, will do this later once I get the send working.
EDIT*** I made some slight changes to the sendFunction(), and have seen some success. Values are now being added to my database, but they values are blank, instead of the values in the form data.
Thank you for all help/suggestions ahead of time!
HTML doc:
<!DOCTYPE HTML>
<html>
<head>
<title>Ajax Form</title>
<script language="javascript" type="text/javascript">
function sendFunction() { // Create a function to handle the Ajax
var xmlhttpCreate; // Variable to hold the xmlhttpRequest object
if (window.XMLHttPRequest) { // Checks for browser compatibilities
xmlhttpCreate = new XMLHttpRequest();
}
else {
xmlhttpCreate = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpCreate.onreadystatechange = function() {
if (xmlhttpCreate.readyState == 4) { // If server has processed request and is ready to respond
document.getElementById("createSuccess").innerHTML = xmlhttpCreate.responseText; // Display a success message that the data was sent and processed by the php script & database
}
}
var fName = document.getElementById('firstName').value; // Dump user firstName into a variable
var lName = document.getElementById('lastName').value; // Dump user lastName into a variable
var queryString = "?fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("GET", "ajax_create.php" + queryString, true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(); // Send the request
}
</script>
</head>
<body>
<h3>Create Profile</h3><br>
<form name="form">
First Name: <input type="text" id ="firstName"/><br><br>
Last Name: <input type="text" id="lastName"/><br><br>
<input type="button" onclick="sendFunction()" value="Create Profile">
</form><br>
<div id="createSuccess"></div><br>
<h3>Search for Profile</h3><br>
<form name="searchForm">
First Name: <input type="text" id="searchFirstName"/><br><br>
<input type="button" onclick="sendFunction()" value="Search for Profile"/>
</form><br><br>
<div id="resultFN"></div><br>
<div id="resultLN"></div><br>
</body>
</html>
And here is my PHP script:
<?php
// Connect to the database
$con = mysqli_connect('localhost', 'root', 'intell', 'ajax_profile');
// GET variables from xmlhttpCreate
$fName = $_POST['fName'];
$lName = $_POST['lName'];
// Escape the user input to help prevent SQL injection
$fName = mysqli_real_escape_string($fName);
$lName = mysqli_real_escape_string($lName);
// Build the query
$query = "INSERT INTO users (firstName, lastName) VALUES ('$fName', '$lName')";
mysqli_query($con, $query);
mysqli_close($con);
$success = "Profile added to the database";
echo $success;
?>
you are sending data with method GET and you want to get the date in your php file with POST ... now you have two solutions . you can change the javascript code to send with GET like this :
var queryString = "fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("POST", "ajax_create.php", true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(queryString);
or you can change the way you get the data on your php file like this:
$fName = $_GET['fName'];
$lName = $_GET['lName'];
don't do both things , only one, change either javascript function or php file.

Categories

Resources