Pass javascript variables into Database with MySQL and PHP [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass a variable / data from javascript to php and vice versa?
I have 3 javascript variables which gives me an id, a name and a surname as such:
if (!response.error) {
document.getElementById("meName").innerHTML = response.id
+ " " + response.name
+ " " + response.surname ;
}
Now I want to pass those variables (response.id, response.name and response.surname) into my database.
Something like this:
<?php
$query = mysql_query("INSERT INTO users (id, name, surname) VALUES
('response.id', 'response.name', 'response.surname')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
?>
How can I do this?

This is what you need:
if (!response.error) {
var uid = response.id;
var firstname = response.name;
var surname = response.surname
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "ajax.php?uid=" + uid + "&firstname=" + firstname + "&surname=" + surname , true);
xmlhttp.send();
return false;
}
and in your ajax file:
<?php include("YOUR_CONNECTION_FILE.php");
$uid = mysql_real_escape_string($_GET['uid']);
$firstname = mysql_real_escape_string($_GET['firstname']);
$username = mysql_real_escape_string($_GET['surname']);
$query = mysql_query(" YOUR MYSQL QUERY ") or die(mysql_error());
?>

Well, ajax would be the best choice in your case.
Check my answer here How to send a form without refreshing the page?
Check out some documentation also:
jQuery Documentation
jQuery.ajax() - jQuery API
Ajax - jQuery API
Tutorials
Net Tuts+ - 5 Ways to Make Ajax Calls with jQuery
Beginners Guide to Using AJAX with jQuery

I'm guessing you're trying to pass the javascript variables to php.
In order to do this you need to use a POST or GET method.
This question's answer will help.

You'd need to make an AJAX call to a separate PHP script which stores the variables.
Javascript runs browser-side, whereas PHP runs on the server - by the time the browser is running the Javascript code in the page, it has already finished running on the server and thus all of the PHP code has already executed.

I believe that response is your return via ajax, if so, you should check two things
First, set the ajax dataType to 'json'.
Second, replace
return $result
to
return json_encode($result);
By.

Related

use variable jquery inside PHP and inside jQuery function

if u see this function <?= input_txt('+order_id+') ?>
have jquery variable but jquery send error
function order_status(type, order_id) {
var value = type.value;
var info = document.getElementById("cancel_id_" + order_id).value;
document.getElementById("my_cancel_info").innerHTML = "Determine the reason for cancellation of the order number " + info;
document.getElementById("cancelled_info").innerHTML = '<?= input_txt('+order_id+') ?>';
if (value == 2) {
$('#order_cancelled').modal('show');
}
}
You first need to understand the order in which PHP and javascript execute. PHP is rendered server-side, while javascript is rendered client-side. I suggest that you look into http://api.jquery.com/jquery.ajax/ where you can pass your javascript variable to a PHP script via AJAX and then return your result.

How to send the values of the query variables into php variable for inserting into database? [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.

Passing Values of Spans to php with AJAX [duplicate]

This question already has answers here:
jQuery simple value get issue with .val()
(3 answers)
Closed 9 years ago.
thanks for taking the time. I'm working on building a visual shopping cart into multiple pages of a parallax site. Because each 'page' of the parallax forces open and close a form, I cannot use a continuous form. To remedy this, I am using jquery to place the value of the choices on the preceding pages into one page, filling spans.
I'd like to be able to grab these final choices from the dom using ajax to put them to a processing page to store the customers choice information, and check it against a dwolla transaction. I haven't got to setting up the dwolla transaction and check yet, because I have not been able to get my data to the php processing page, and get it to return an echo-able value. This is built off wordpress by the way, and allot of times, filters wordpress is implementing screw me up.
Here's the site; http://ecigjuiceclub.com
Lets jump into the code!
AJAX:
function post()
{
var name = $('#cname').val();
var street1 = $('#cstreet').val();
var street2 = $('#cstreet2').val();
var city = $('#ccity').val();
var state = $('#cstate').val();
var zip = $('#czip').val();
var email = $('#cemail').val();
var phone = $('#cphone').val();
var flavor = $('#cflavor').val();
var strength = $('#cstrength').val();
var refcode = $('#crefcode').val();
$.post('process.php',{postname:cname,poststreet1:cstreet,poststreet2:cstreet2,postcity:ccity,poststate:cstate,postzip:czip,postemail:cemail,postphone:cphone,postflavor:cflavor,poststrength:cstrength,postref:crefcode},
function(data)
{
$('#thankyou').html(data);
});
}
Php process.php
<?php
$name = $_POST['postname'];
$street1 = $_POST['poststreet1'];
$street2 = $_POST['poststreet2'];
$city = $_POST['postcity'];
$state = $_POST['poststate'];
$zip = $_POST['postzip'];
$email = $_POST['postemail'];
$phone = $_POST['postphone'];
$flavor = $_POST['postflavor'];
$strength = $_POST['poststrength'];
$refcode = $_POST['postref'];
if($zip == 90804)
{
echo "1";
}
else
{
echo "0";
}
?>
HTML Snippet (where in the DOM I'm attempting to grab):
<span style="color:#EF5D3D;">Email: </span><span style="font-size:28px;" id="cemail"></span>
<span style="color:#EF5D3D;">Phone: </span><span style="font-size:28px;" id="cphone"></span>
i think you better try innerHTML instead values i dont know the exact syntax in jquery. iprefer u use input or else instead span
var email = $('#cemail').text();
var phone = $('#cphone').text();
These should be the replacements on the post() function. Adding an alert message (as an example) at the opening of the post() function could help you check their values before they get passed in the Ajax request.
alert($('#cemail').text() + ' ' $('#cphone').text());
Also make sure to clear your cache just to make sure your javascript edits have been implemented.
The console is showing the following errors which may or maynot prevent other scripts from running:
Uncaught ReferenceError: Modernizr is not defined
ecigjuiceclub.com/:825
Blocked a frame with origin "https://www.youtube.com" from accessing a
frame with origin "http://ecigjuiceclub.com". The frame requesting
access has a protocol of "https", the frame being accessed has a
protocol of "http". Protocols must match.

Add javascript in php mysql query

I know this sound weird but I need to be able to use a variable in javascript and use it inside a php mysqli query
I use the jQuery File Upload from blueImp. It's variable are store like this
{%=file.name%}
and I need to do something like this
$iq = $mysqli->query("SELECT * FROM image WHERE mId='".$_GET['mId']."' AND file_name = '".{%=file.name%}."'");
of course this is not working because of the {}.
Anyone have a clue how to work with those kind of programming ?
In javascript:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4) {
//POST request sent
}
};
xmlhttp.open("POST", "url_to_phpfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("yourvariable="+yourvariable);
Then you can use that variable in your php file like so:
$iq = $mysqli->query("SELECT * FROM image WHERE mId='".$_GET['mId']."' AND file_name = '".$_POST["yourvariable"]."'");
No, you cannot directly do this**.
Javascript is something that will execute at client side(browser).
PHP is a server side scripting language.
If you want to pass a Javascript variable in PHP , then you can do so through AJAX

calling php and javascript functions with one button

This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication

Categories