javascript variable into php that is already into javascript - javascript

i have tried this code:
<script type="text/javascript">
var s = 0;
document.getElementById('text').value = "<?php echo phpVal[s];?>";
</script>
the problem is how can i put the (s) value into (PHP) code.
Here's more context:
<head>
<?php $s = ["a","b","c"]; ?>
<script type="text/javascript">
function doFun(ss){
var data = "<?php echo json_encode($s); ?>";
document.getElementById('t').value = s[ss];
}
</script>
</head>
<body>
<input type="text" id="t" name="t" />
<button type="button" id="b" name="b" onclick="doFun(0)">doFun</button>
</body>

You can't, by the time s has a value (on the client), the PHP code (on the server) has long-since completed.
What you do instead depends a lot on what your end goal is. You have a lot of options. Here are two of them:
Output the entire phpVal array/object to the client, and then index into it with s.
var s = 0;
var data = <?php echo json_encode(phpVal)%>;
document.getElementById('text').value = data[s];
Send s to the server via ajax, have the PHP code that runs in response to that request pick out the correct value from phpVal, and return that as the result of the ajax, putting it in the client-side input's value. For example:
JavaScript:
var s = 0;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('text').value = xhr.responseText;
}
};
xhr.open("get-value.php?s=" + encodeURIComponent(s));
// You don't really need this ^
// for `0`, but many times when sending variables to the
// server, you do
xhr.send();
PHP for get-value.php (roughly):
<?php
header('Content-Type: text/plain');
$phpVal = /*...get the value however it is you do that...*/
echo $phpVal[$_GET['s']];
?>
But again it depends on what you're actually trying to do.

Related

Ajax response text is always 1

I am sending two variables to my php page for calculation then echoing the end result back. My response text always equals one.
The Javascript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4)
{
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
The php:
I set the end var to a random number here just to test if my math was causing the problem.
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
echo $workingDays;
Set $workingDays directly to 10 ( random number ). If it is not 10, then you are clearly not seeing the result of that echo statement.
1 is often used as the output to native PHP functions such as isset
You're case is wrong.
$workingdays = 239;
echo $workingDays;
Make it workingDays (with capital D) in both places.
Always use isset() for receiving data and you are using variable $workingdays for declaration and for echo $workingDays, take care of these things. I hope this will work for you.
$startdate = '';
$endDate ='';
if(isset($_GET['w1']))
{
$startdate = $_GET['w1'];
}
if(isset($_GET['w2']))
{
$endDate = $_GET['w2'];
}
$workingdays = 239;
echo $workingdays;
die;
Try adding this variable in your ajax code just to make a test if in the server side is receiving the data you sent using get method.
var ftest = 1;
var ltest = 2;
I assumed that your ajax code is inside the a function let say myfunction and you have a link like this link
Here is the full implementation of the code assuming that your filename is index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
link
<script type="text/javascript">
function myfunction () {
var ftest = 1;
var ltest = 2;
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4) {
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
</script>
</body>
</html>
and Calc.php
<?php
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
$result = $startdate + $endDate;
echo "$result";
?>
In this example you alert will equal to 3 it be same in your code
Hope this will help

Zillow Data - json_encode not working - works for regular variables

I have an issue that may or may not have been solved before, but I seem to be the only one on here using pure JavaScript instead of JQuery to accomplish my simple AJAX requests.
First here is my AJAX:
function getZestimate(address,csz){
var xmlhttp = new XMLHttpRequest();
var userdata = "address="+address+"&csz="+csz;
xmlhttp.open("POST","../wp-content/themes/realhomes/submit_address.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
retrieve = JSON.parse(xmlhttp.responseText);
document.getElementById("zestimateArea").innerHTML =
'<div id="zillowWrap">
<div id="logoANDtag">
<img src="http://www.zillow.com/widgets/GetVersionedResource.htm?path=/static/logos/Zillowlogo_150x40.gif" width="150" height="40" alt="Zillow Real Estate Search" id="ZillowLogo" />
<span id="zestimateTag">Zestimate®</span>
</div>
<span id="zestimatePrice">'+retrieve[0]+'</span>
</div>
<div id="zillowDisclaimer">
<span>© Zillow, Inc., 2006-2014. Use is subject to Terms of Use</span
<span>What’s a Zestimate?
</div>';
}
else{
document.getElementById("zestimateArea").innerHTML = "Error!"
}
}
xmlhttp.send(userdata);
document.getElementById("zestimateArea").innerHTML = "Generating...";
return false;
}
Next, here is my PHP:
<?php
$zillow_id = '1234';
$search = $_POST['address'];
$citystate = $_POST['csz'];
$address = urlencode($search);
$citystatezip = urlencode($citystate);
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$zillow_id."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$zpidNum = $data->response->results->result[0]->zpid;
$zurl = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$zillow_id."&zpid=".$zpidNum;
$zresult = file_get_contents($zurl);
$zdata = simplexml_load_string($zresult);
$zestimate=$zdata->response->zestimate->amount;
$street=$zdata->response->address->street;
$city=$zdata->response->address->city;
$state=$zdata->response->address->state;
$zip=$zdata->response->address->zip;
$one='one';
$two='two';
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode(array($zestimate,$street));
?>
What returns in my AJAX is [object Object] with no errors in my Console.
However, see the 2 variables $one and $two? If I place them in the json_encode like echo json_encode(array($one,$two)); it returns one like it is supposed to.
I am not sure what the difference is with the Zillow data. I can echo it individually no problem. But I need to send multiple values to work with. Any ideas?
When you parse a document using SimpleXML, all the nodes are objects which get cast to strings when you try to echo them, but when given to a function like json_encode, you don't get the results you'd expect.
To make them strings so json_encode works, try this:
$zestimate = (string)$zdata->response->zestimate->amount;
$street = (string)$zdata->response->address->street;
echo json_encode([$zestimate, $street]);

Updating javascript array with click when new mysql data comes in

I am using the following code to send mysql database content into a javascript array. This works fine when I start the page, but when the database gets a new entry, the new entries are not added to the array when I rerun this bit of code - unless I reload the entire page.
<p><button onclick="save_image()">Send image</button></p>
<script type="text/javascript">
function save_image(){
var userName =
<?php
$conn = new mysqli(.........."); //connect to database
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
console.log(userName)
}
</script>
I realize there are other pages about this topic, but I didn't know how to apply them to my case. If you have some ideas. Thanks.
If you want to get information from the database without reloading the page, you'd need to do an Ajax request to retrieve the information.
Something like this would work:
PHP - ajaxendpoint.php
<?php
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>
JavaScript
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //log the response from the database
//if the PHP is returning a JSON object, you can parse that:
var myArray = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "ajaxendpoint.php", true);
xhttp.send();
}
HTML - index.html
<button onclick="getData()">
Load Data via Ajax
</button>
Here is another example Ajax request in this JS Fiddle: https://jsfiddle.net/igor_9000/77xynchz/1/

Can't update database using PHP and JavaScript

I'm trying to build a very simple "budget" website solely for practice, but I can't make this site update my database.
Basically I have a database 'budgetdb' running in XAMPP with MySQL. I've got 1 table where the structure looks like this:
I've got two files, 'index.html' and 'handleUserInput.php'.
Index.html:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = document.getElementById('description').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
var xmlhttp = new XMLHttpRequest();
var url = "handleUserInput.php?description='" + description + "'&budgetin='" + budgetin + "'&budgetout='" + budgetout + "'";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('Variables sent to server!');
}
}
xmlhttp.open("POST", url);
xmlhttp.send();
}
</script>
</body>
</html>
handleUserInput.php:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb"
mysql_connect($host, $username, $password;
mysql_select_db($dbname);
$description = $_POST['description'];
$budgetin = $_POST['budgetin'];
$budgetout = $_POST['budgetout'];
$query = 'INSERT into budget VALUES ($description, $budgetin, $budgetout)';
mysql_query($query)
?>
The message prompt is displayed, but no data is shown in the database. Any clue on what I am doing wrong here?
UPDATE chrome error:
Notice: Undefined index: description in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 13
Notice: Undefined index: budgetin in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 14
Notice: Undefined index: budgetout in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 15
Other answers have shown the problem with the way you write the query, it. should be, with quotes around each of the values.
$query= "INSERT into budget VALUES('$description',$budgetin,$budgetout)";
But you also have a problem with the way you create the URL. Quotes shouldn't be put around query parameters, and you should use encodeURIComponent to ensure that special characters are escaped properly.
var url = "handleUserInput.php?description=" + encodeURIComponent(description) + "&budgetin=" + encodeURIComponent(budgetin) + "&budgetout=" + encodeURIComponent(budgetout);
And to prevent SQL injection problems, you need to escape the strings before you use them as SQL parameters. And since you're sending the parameters in the URL, rather than in the POST data, you need to get them from $_GET, not $_POST.
$description = mysql_real_escape_string($_GET['description']);
Although if you're first learning PHP now, you should use PDO or mysqli, instead of the obsolete mysql extension, and use prepared statements instead of string substitution.
Change the line that performs the query to:
mysql_query($query) or die(mysql_error());
If there's a problem performing the query, this will display the error message.
The quotes in your query are incorrect. Should be (note outer double quotes and inner single quotes):
$query= "INSERT into budget VALUES('$description',$budgetin,$budgetout)";
However, be aware this has opened you up to a SQL injection where description is
'); DROP budget;
Also, your description may contain punctuation and spaces, which may be messing up your url. You are sending a POST anyway, so all the data should be in the body of the request not the url.
Use
$query = "INSERT into budget VALUES ('$description', $budgetin, $budgetout)";
description is string type in database so you close with single quote or double quote in PHP String.
Always consider safety. ReWrite a code as (somewhat safety):
$description = mysql_real_escape_string( $_POST['description'] );
$budgetin = intval( $_POST['budgetin'] );
$budgetout = intval( $_POST['budgetout'] );
$query = 'INSERT into budget VALUES ("$description", $budgetin, $budgetout)';
Note: Don't use mysql_* function. It is deprecated in future versions. Use MySQLi or PDO
You are sending your values as GET parameters not POST parameters.
handleUserInput.php?description='" + description + "'&budgetin='" + budgetin + "'&budgetout='" + budgetout + "'"
Everything you pass to PHP thru url will fall into $_GET variable. Not only PHP bu every server side language will behave the same, once it is a standard GET means URL parameters and POST is Request Payload
You can change $_POST to $_GET or add your data do xmlhttprequest object
<!DOCTYPE html>
<html>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = document.getElementById('description').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
var params = "description=" + description + "&budgetin=" + budgetin + "&budgetout=" + budgetout;
var xmlhttp = new XMLHttpRequest();
xmlhttp .setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp .setRequestHeader("Content-length", params.length);
xmlhttp .setRequestHeader("Connection", "close");
var url = "handleUserInput.php?";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('Variables sent to server!');
}
}
xmlhttp.open("POST", url,true);
xmlhttp.send(params);
}
</script>
</body>
</html>
In order to minize your code use Jquery library instead of simple JS code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = $('#description');
var budgetin = $('#budgetin');
var budgetout = $('#budgetout');
$.post( "handleUserInput.php", { "description": description, "budgetin": budgetin, "budgetout": budgetout }, function( data ) {
alert( "Variables sent to server!" );
} );
}
</script>
</body>
</html>
Use mysql_real_escape_string in order to avoid SQL injection into your application. Initial problem was caused because php variables wasn't correctly added in the string of SQL query, for example :
$input = 'aaa';
echo 'text $input';
this code will output
text $input
but this one
$input = 'aaa';
echo "text $input";
or this one
$input = 'aaa';
echo "text ".$input.";
will output
text aaa
Please check the code bellow
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb"
mysql_connect($host, $username, $password;
mysql_select_db($dbname);
$description = $_POST['description'];
$budgetin = $_POST['budgetin'];
$budgetout = $_POST['budgetout'];
$description = mysql_real_escape_string($description);
$budgetin= mysql_real_escape_string($budgetin);
$budgetout= mysql_real_escape_string($budgetout);
$query = "INSERT into budget VALUES ('".$description."', ".$budgetin.", ".$budgetout.")";
mysql_query($query)
?>
Use single inverted comma with php variables like below.
$query = "INSERT into budget VALUES ('$description', $budgetin, $budgetout)";

program php and alert javascript on form html

i have a problem with my simple program in php that include an alert javascript.
This is the code:
<?php
function iva(){
$country='IT';
$vatnum=$_POST['n'];
$a="Work";
$b="NotWork";
$url='http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
}
if ($response != 'true'){
echo $b;
}
}
?>
<script>
function ivaz(){
alert("<?php iva() ?>");
}
</script>
<form method="post">
<input name="n" type="textarea" >
<input onclick="ivaz();" value="Validate" type="submit"> </input> </form>
My program take a value from input text box and pass the value to php script that return true or false in a javascript alert. The program work, but return previous value passed in input box.
Can someone help me to solve it?
Thanks guys.
No, it doesn't work that way. If you want to call a PHP function from Javascript without the page refreshing, you need an XMLHttpRequest.
Example:
<?php
// your php process when called by XMLHttpRequest
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vatnum = $_POST['n'];
$country='IT';
$a = "Work";
$b = "NotWork";
$url = 'http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
} else {
echo $b;
}
exit;
}
?>
<form method="post" id="form1">
<input name="n" type="text" id="n" />
<input value="Validate" type="submit">
</form>
<script type="text/javascript">
// when the form is submitted
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
var n = document.getElementById('n').value; // get the textbox value
var xmlhttp = new XMLHttpRequest();
var params = 'n=' + n;
var php_url = document.URL;
xmlhttp.open('POST', php_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
alert(response); // alert the server response
}
}
xmlhttp.send(params);
});
</script>
Remove onclick="ivaz();" from input tag
You cannot run the php script without reloading the page as php is generated serverside and javascript runs clientside.

Categories

Resources