Passing variable from php to javascript - follow-up - javascript

I saw this post Passing a variabe to jquery using Odometer but am unable to comment on it. I had a follow-up question.
Hoping I can get an answer.
I am using this php to pull a value from mysql:
<?php
// Make a MySQL Connection
include("/home/www/php_snippets/dbconnect.php");
//execute the SQL query and return records
$query = "SELECT total_miles, SUM(total_miles) FROM mileage as total_miles";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total Miles". $row['type']. " = ". $row['SUM(total_miles)'];
echo "<br />";
}
//close the connection
mysql_close($dbhandle);
?>
I want to use this script to put this value on my page:
<script>
$(function () {
setTimeout(function () {
//Get the value from serverside
var uid = '<%=odometervalue %>';
odometer.innerHTML = uid;
}, 1000);
});
</script>
The solution says to use a puplic string to declare the variable but I am confused where to use it. In my PHP?
You can use the below implementation to pass the value from code behind to Jquery
This is one example how to do it.
First Declare a Public Variable in code behind
//Declare a Public Variable in code behind
public string odometervalue = "667";
Could I use:
public string odometervalue = total_miles;
In my above php?
I am still learning so please assist if you can :)

Related

How can I get user input in between php code (from client to server)?

I created php code to run java files and provide result to the user through a web browser. Basically I am trying to create a barebones interactive java web console. However, this should also work for java files that have user input such as Scanner object.
Here is the sample java file for testing.
import java.util.Scanner;
public class JavaScannerExample
{
public static void main (String[] args)
{
// create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// prompt for the user's name
System.out.print("Enter your name: ");
// get their input as a String
String username = scanner.next();
// prompt for their age
System.out.print("Enter your age: ");
// get the age as an int
int age = scanner.nextInt();
System.out.println(String.format("%s, your age is %d", username, age));
}
}
Currently, I figured how to do this in php. With a predefined set of parameters.
<?php
$JAVA_HOME = "C:\Java\jdk1.7.0_79";
$PATH = "$JAVA_HOME\bin";
putenv("JAVA_HOME=$JAVA_HOME");
putenv("PATH=$PATH");
$result = shell_exec("javac JavaScannerExample.java 2>&1");
$progout = "";
$inputlist = array("32", "Mike");
if ($result == ""){
$options = ["bypass_shell" => true];
$proc=proc_open("java JavaScannerExample",
array(
array("pipe","r"),
array("pipe","w"),
array("pipe","w")
),
$pipes,NULL,NULL,$options);
if (is_resource($proc)) {
$line_limit = 1024;
$bool = true;
while ($bool) {
sleep(1);
$b = proc_get_status($proc)["running"];
if ($b == 1) { // There are still questions
$inputval = array_pop($inputlist);
$q = fread($pipes[1], $line_limit);
$progout = $progout.$q.' '.$inputval.'<br>';
fwrite($pipes[0],$inputval."\n");
}else{ //Program finished executions.. Get final line
$bool = false;
$finaloutput = fread($pipes[1], $line_limit);
$progout = '<br>'.$progout.$finaloutput;
fclose($pipes[0]);
fclose($pipes[1]);
}//End Else
}//End While
echo $progout;
}//End Proc
}//End If
else{
echo $result;
}
?>
Here is the result from executing the php code with the sample java file
Enter your name: Mike
Enter your age: 32
Mike, your age is 32
If you look at the line
$inputlist = array("32", "Mike");
I am passing the parameters in the hard coded manner.
However I want to be able to get user input through a web browser for the parameters. So instead of the line
$inputval = array_pop($inputlist);
I need to be able to pause the execution of php code. Then, Get the parameter from the user and store it in $inputval variable and execute the php code. I think we might have to use javascript/jquery using ajax for this. But I am not sure how.
Please help me with this question. Sample code/Pseudo code will be highly appreciated.

.post javascript with PHP to enable select statement return

.post javascript with PHP to enable select statement return
Okay I got this script that is working
$.post('2.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
This is what my 2.php looks like
$data = $_POST['id'];
$file = fopen("test.txt","w");
echo fwrite($file, $data);
fclose($file);
So I did a test, I run 1.php and saw test.txt was created with the data.
this prove the connection was successful.
Now is the difficult part.
I need to send id:12345 to 2.php, and 2.php need to
"select * from account where account_id='$data'";
And then the return result, I think of using MYSQL_ASSOC or MYSQL_BOTH
I not sure which is best.
Then get the result, be it 1 row result or many row result.
Return as an array and then use 1.php to perform
alert( ArrayReturnResult );
Assuming that my account table have this value
account_id, account_name, account_phone, account_email
How do I accomplish this?
Assuming you know how to establish a database connection (using PDO, of course), you could do something like this in 2.php:
if(!empty($_POST)) {
$data = (int) $_POST['id'];
// query the table
$stmt = $pdo->prepare("SELECT * FROM account WHERE account_id = :id");
$stmt->bindValue(":id", $data, PDO::PARAM_INT);
$stmt->execute();
// fetch results
$buffer = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$buffer[] = $row;
}
// output JSON string
echo json_encode($buffer);
}
Of course, this isn't tested... and probably isn't secure if dealing with personal details.
Don't forget to update your $.post method so that it can expect JSON-encoded data:
$.post('2.php', { id: 12345 }, function(data) {
console.log(data); // this will now be a JS object, from 2.php
}, 'json');

Angular JS $http.get does not receive data from PHP script

I am using angular's $http.get function to call a PHP script file to retrieve data
var $promise = $http.get("../php-bin/example.php",obj).success(function(data) {
console.log(data);
});
The php is supposed to just get data from a mysql db to figure out a way to get data into my app
$user = json_decode(file_get_contents('php://input'));
$email = $user->email;
$pass = $user->pass;
$con = //a mysql_connection;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$validateEmail = "SELECT `Email` FROM `newUsers` WHERE `Email` = '$email' ";
if ($result = mysqli_query($con,$validateEmail)) {
if ($result->num_rows == 1){
$date = '2014-08-13';
//$sql = "INSERT INTO newUsers (Email, CreationDate, UserRef, Type, id) VALUES ('$email','$date','$email','Host','$ssid')";
$sql = "SELECT `email` FROM `newUsers` WHERE `hashpass` = '$pass' ";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
return $row;
//I never receive this data in the angular app.
}
}
mysqli_close($con);
?>
Could some one point me to the correct way to do this.
I see you have a return statement instead of an echo statement. A return statement is not printed in the PHP output. A return statement outside a function has only sense when you include the file:
$returned = include('the_file_you_showed_here.php');
//you will hold the row here
A return statement kills the current script returning to an includer script (if any), but does not send any value to the output (that's the purpose of die/exit). You should:
Change the return to echo.
Remember to have a header('Content-type: application/json') sent if you intend to send json data, before any actual echo instruction or non-php content.
Remember to encode the data: return json_encode($row).
in your php make sure you echo your result the echoed results get passed into your variable
for example if you are passing in a varibale say from your scope
function($scope,$http){
$scope.obj= "your variable";
$reuslt = http.get('yourlocation/yourfile.php?val='+obj');
your php script
<?
$value = $_GET['val']
//not your variables have been passed in and you can use it to do your custom function wich ever way you like
and echo your result after wards
?>
hope this helps
You cannot call relative paths like that. The file has to exist at the public directory or lower. For instance, if all of your files are in /home/yourname/public, you'd need to call /php-bin/example.php instead, where php-bin is inside of the public directory (/home/yourname/public/php-bin).

jQuery $.getJson call not returning value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to make a site that dynamically creates information using the jQuery ajax call $.getJson and the jQuery template plugin. In my index.html page, I have some of the following code:
$(document).ready(function() {
var jsonData ="string";
$.getJSON("load.php", function(data) {
jsonData = data;
console.log(jsonData);
});
console.log(JSON.stringify(jsonData));
// Load template from our templates folder,
// and populate the data from the post object.
$("#test").loadTemplate('#template', jsonData);
});
The ajax call executes the load.php, which has some of the following code:
//extract user ratings and respective movies
$_SESSION['username'] = $username;
$user_query = mysqli_query($link, "SELECT * FROM Client WHERE Username = '$username'");
$user_row = mysqli_fetch_array($user_query);
$user_id = $user_row['ID'];
$query = mysqli_query($link, "SELECT * FROM Ratings INNER JOIN Movie ON Ratings.Movie_ID = Movie.MovieID WHERE Client_ID = $user_id ORDER BY Rating DESC");
//adding movies to array list
$result = array();
while ($row = mysqli_fetch_array($query))
{
$movie = $row['MovieURL'];
$rating = $row['Rating'];
array_push($result, array('moviePicture' => $movie, 'movieRating' => $rating));
}
//converting array list to json and echoing it
echo json_encode($result);
I have tested the $result and it does create a json object with all of the data that it is supposed to. However, when the javascript is run in the index.html page, jsonData does not change its value from 'string'(when I check the console log). I believe the problem is with the function(data), since it does not log the console command I have in there. Any help would be appreciated.
Proper code:
$(document).ready(function() {
var jsonData ="string";
$.getJSON("load.php", function(data) {
jsonData = data;
$("#test").loadTemplate('#template', jsonData);
});
});
The problem with your code is, that you call loadTemplate before you got reply from load.php

how to separate two or more returned variables in the $.post method in jquery?

i need to seperate two variables which i got from the server and i m using $.post method. but when i m doing it i m getting the combined mixed value from this method. here is the code
$(".spot_me").click(function()
{
var idea = $(this).attr("id");
var idea1 = $(this).attr("data");
alert(idea);
alert(idea1);
$.post('spot_me.php', 'val=' + idea + '&tim=' + idea1, function (data)
{
alert(data);
});
});
here var id is a userid. i wish to get the coordinates which this user had stored in the database. my php code for abc.php is
<?php
session_start();
$value = $_POST['val'];
$value1 = $_POST['tim'];
$con=mysqli_connect("localhost","root","******","anurag");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con,"SELECT latitude,longitude FROM notifications WHERE uid='$value' AND time='$value1' ");
if(!$result2)
{
echo "Error in query";
}
else
{
$row = mysqli_fetch_array($result2);
$lat = $row['latitude'];
$lon = $row['longitude'];
echo $lat;
echo $lon;
}
?>
now i want to get this lat and lon value separately in my jquery $.post method in the parameter data. how can i get these values separately and "I WANT TO STORE THEM IN TWO DIFFERENT VARIABLES IN $.POST METHOD" how can i do this
You'll use JSON to communicate between the languages.
Your PHP will transform the array into JSON:
else
{
$row = mysqli_fetch_array($result2);
echo json_encode($row);
}
And your javascript will treat the data as an object, because you've told the .post() function to expect json
var post_str = 'val=' + idea + '&tim=' + idea1;
$.post('spot_me.php', post_str, function (data)
{
alert(data.latitude);
alert(data.longitude);
}, 'json');
Choose a mode of response - maybe json (my preference) or xml
Construct your response with your server code
Parse that response with jQuery, with jQuery.parseXML() or jQuery.parseJSON() for json and xml respectively
At PHP
$row = mysqli_fetch_array($result2);
echo json_encode($row);
At jQuery
$.post('spot_me.php', 'val=' + idea + '&tim=' + idea1, function (data)
{
var response = jQuery.parseJSON(data);
alert(response.latitude);
alert(response.longitude);
});
This is just an indicator oh how to do it, and not tested.
you can do it by returning you output as JSon and then parse that JSON in Javascript.
In PHP file do like this: (instead of returning two variables)
echo json_encode(array('latitude' => $row['latitude'],'longitude'=> $row['longitude']));
Response will be like this (test values use)
{"latitude":123,"longitude":456}
in you Jquery Ajax code where you return response use JSON parse method
var obj = $.parseJSON(data );
alert( obj.latitude)
alert( obj.longitude)
//From the server
$row = mysqli_fetch_array($result2);
return json_encode($row);
//and on the client
var dataasjson = $.parseJSON(data);
$.each(dataasjson, function(index, element) {
element.name //this is your label i.e databse field name as key
dataasjson[element.name] //this is your long/lat value
});

Categories

Resources