I'm trying to send two values from a javascript to a PHP file that in it's turn sends them to my arduino webserver. The values are strings and my wish is to send the pin value from my "pinArray" like this:
$.get("curl.php",{pin: pinArray[i],state:"1"});
But it is not working.
$.get("curl.php",{pin: "23",state:"1"});
is working fine though.
My "pinArray" looks like this:
var pinArray = ["23","25","27","29"];
The PHP file "curl.php" looks like this:
<?php
$pin = $_GET['pin'];
$state = $_GET['state'];
// Create cURL call
$service_url = 'http://arduino.local/digital/' . $pin . '/' . $state;
echo 'alert("Pin: "+ $pin +" state: "+ $state )';
$curl = curl_init($service_url);
....
Can anyone please help me with this?
It looks like either
pinArray is not defined at the time of the request
i is not defined at the time of the request
pinArray[i] is not defined at the time of the request
try to debug the values with chrome devotees or firebug:
console.log('pinArray', pinArray);
console.log('i', i);
console.log('pinArray[i]', pinArray[i]);
var data = {pin: pinArray[i],state:"1"};
console.log('data ', data);
$.get("curl.php", data);
Related
In Javascript i encode parts of the request parameter like this
window.location.href = "search.php?qry=" + encodeURIComponent("m & l");
In my Search.php i reach this like this
$url = urldecode($_SERVER['REQUEST_URI']);
echo ."Full URL: " .$url ."<br>";
$parts = parse_url($url);
parse_str($parts['query'], $query);
$qry = "Just Query: " .trim($query['qry']);
echo $qry ."<br>";
This prints out:
Full Url: /Search.php?qry=m & l
Just Query: m
Looks like the stuff after the & is being dropped in the 'm & l`
What changes do i need to make in PHP or Javascript?
Just change:
$url = urldecode($_SERVER['REQUEST_URI']);
to
$url = $_SERVER['REQUEST_URI'];
You're basically double-decoding as parse_url will decode it as well.
Worth noting that PHP has already done this for you so there's not really a reason to parse your own URL. $_GET['qry'] will contain 'm & l'
If you're doing this for several query variables, you'll need to run encodeURIComponent separately for each.
Example:
window.location.href = "search.php?qry=" + encodeURIComponent("m & l") + "&subcat="+encodeURIComponent("hello & there");
You're explicitly telling it to encode the & after all.
I am new to web development and this is my first question here so please don't mind my vagueness, if any.
Now, I am facing facing problem with my javascript file which is supposed to draw a line chart.
Through an ajax call I am unable to fetch data from a php file which gets some variable from a html form. The problem is that I am not getting anything when I load my test.html (which includes the necessary file) not even in console.
Relevant part of my js file is here (graph.js):
$(document).ready(function(){
$.ajax({
url : "http://localhost/series/data.php",
type : "GET",
dataType: "json",
success : function(data){
console.log(data);
var time = [];
var sensor1 = [];
var sensor2 = [];
var sensor3 = [];
for(var i in data) {
time.push("time " + data[i].time);
sensor1.push(data[i].sensor1);
sensor2.push(data[i].sensor2);
sensor3.push(data[i].sensor3);
}...
And this is my PHP file(data.php):
<?php
header('Content-Type: application/json');
//connects to database
include '2connect.php';
//gets a date of which sensor data is to be displayed
if(isset($_GET['dateselector'])&&!empty($_GET['dateselector'])){
$date=$_GET['dateselector'];
//echo "$date";
$query1= "SELECT `time`,`sensor1`,`sensor2`,`sensor3` FROM `$date`";
if($result = mysqli_query($con,$query1)){
$data=array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
}
$result->close();
$con->close();
print json_encode($data);
}else {
echo"<br> failed <br>";
}
}else {
echo "You didn't select a date \n";
}
?>
Whenever I remove the isset check from my php code and give $date a value the code runs perfectly. Is it so that ajax doesn't fetches data from a php file which gets data (form data) from another file?
EDIT: The process is: User chooses a date from the calender (index.html) that date is sent to a php file (data.php) which displays the result in json format. Then in another browser I open a html file(test.html) which includes graph.js and graph.js should fetch data from data.php.
I have a chart created using d3.js where if you hover over the months,the weekly scores are found.
Fiddle link to the chart I am talking about here : https://jsfiddle.net/qp7L1hob/1/
I also have a table in my DB where I maintain the record of the scores of the Employees every week.What you see here is only for four weeks - (week1 to week4) but in my DB I have record for all the weeks of the months.This is just for reference .
Table pointsScored :
After the user logs in,I want to display only that person's relevant scores.Lets say if Rob logs in,his score for week1 is 47 , week2 is 44, week3 is 44 and week4 is 43.
Issue : I am Using php to extract json from SQL server . Below PHP file does that.
The problem is that how do I get the JSON into the d3.js file, i.e the above fiddle.
please help.
json file (lets name it as data.php) :I understand that I need to include this data.php in the above d3.js file.But not sure how.
<?php
session_start();
$servername="xxxxxxx";
$connectioninfo=array('Database'=>'xxxxxx');
$conn=sqlsrv_connect($servername,$connectioninfo);
if($conn)
{
echo 'connection established';
}
else
{
echo 'connection failure';
die(print_r(sqlsrv_errors(),TRUE));
}
$q1="SELECT WeekNumber,pointsRewarded,EmployeeID FROM pointsBadgeTable WHERE EmployeeID = '" . $_SESSION['id'] . "' ";
$stmt=sqlsrv_query($conn,$q1);
if($stmt==false)
{
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors(),TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
echo json_encode($result); //You will get the encoded array variable
?>
Let me give you the direction to understand, you can use AJAX to call your php file and get data
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var dataObj = JSON.parse(response.responseText); // parse data into JSON object
chartDrawFunction(dataObj); // call draw here, to load chart only when you have data
}
};
xhttp.open("GET", "data-url-to-be-passed", true); // pass the URL here
xhttp.send();
Update
As i understood the question other way if PHP file was separate from the view. In view you can echo the data in a JavaScript variable like
var data = <?php echo data; ?>;
I am trying to crawl a full section of a website, but the problem is that the data that I need is not there from the start. Is there anyway to get the data from the website with PHP?
this is the link: https://www.iamsterdam.com/nl/uit-in-amsterdam/uit/agenda and this is the section I need:
After my post was set to duplicate I tried this
https://stackoverflow.com/a/28506533/7007968 but is also doesn't work so I need a other solucion this is what I tried:
get-website.php
$phantom_script= 'get-website.js';
$response = exec ('phantomjs ' . $phantom_script);
echo $response;
get-website.js
var webPage = require('webpage');
var page = webPage.create();
page.open('https://www.iamsterdam.com/nl/uit-in-amsterdam/uit', function(status) {
console.log(page.content);
phantom.exit();
});
this is all I get back (around 3% of the page):
</div><div id="ads"></div><script src="https://analytics.twitter.com/i/adsct?p_id=Twitter&p_user_id=0&txn_id=nvk6a&events=%5B%5B%22pageview%22%2Cnull%5D%5D&tw_sale_amount=0&tw_order_quantity=0&tw_iframe_status=0&tpx_cb=twttr.conversion.loadPixels" type="text/javascript"></script></body></html>
So I have the feeling that i am getting closer this is what I after a lot of searching:
var webPage = require('webpage');
var page = webPage.create();
var settings = {
operation: "POST",
encoding: "utf8",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
DateFilter: 04112016,
LastMinuteTickets: 0,
PageId: "3418a37d-b907-4c80-9d67-9fec68d96568",
Skip: 0,
Take: 12,
ViewMode: 1
})
};
page.open('https://www.iamsterdam.com/api/AgendaApi/', settings, function(status) {
console.log(page.content);
phantom.exit();
});
But what I get back doesn't look good:
Message":"An error has occurred.","ExceptionMessage":"Page could not be found","ExceptionType":"System.ApplicationException","StackTrace":" at Axendo.SC.AM.Iamsterdam.Controllers.Api.AgendaApiController.GetResultsInternal(RequestModel requestModel)\r\n at lambda_method(Closure , Object , Object[] )\r\n
etc.
I hope somewann can help me,
Addressing your main question about 3%.
You use exec incorrectly. When used like this
$response = exec ('phantomjs ' . $phantom_script);
$response will containt the last line of what was printed in terminal during execution of a given command. Because you did console.log(page.contents); the last line of HTML document was placed into $response variable.
The correct use of exec would be
exec ('phantomjs ' . $phantom_script, $response);
This way the result will be placed into $response variable as an array, with each line an element of the array. Then, if you just want to get html, you can do
$html = implode("\n", $response);
But a more simple and correct way is to use the specific function for the task:
passthru ('phantomjs ' . $phantom_script);
passthru executes a function and returns recieved data unmodified, straight to the output.
So if you want to contain it to a variable, do:
ob_start();
passthru ('phantomjs ' . $phantom_script);
$html = ob_get_clean();
I have function like this:
function SetPageShow (obj)
{
window.location.href="?CMD=PAGEROWS&PARA="+obj.options[obj.selectedIndex].text;
}
and it works fine until I have a page with another GET-values like
http://protectneu/main.php?site=mitarb&liz=260
. then when I call the function SetPageShow, the URL will be
http://protectneu/main.php?CMD=PAGEROWS&PARA=25
and the other values(mitarb and liz) are getting lost. Is there a way to keep them saved and just add the new paramethers. The result that I need is:
http://protectneu/main.php?site=mitarb&liz=260&CMD=PAGEROWS&PARA=25
if (window.location.search)
return window.location.href + "&CMD=PAGEROWS&PARA="+obj.options[obj.selectedIndex].text;
else
return window.location.href + "?CMD=PAGEROWS&PARA="+obj.options[obj.selectedIndex].text;
On the PHP side you need to strip out the parameters that you would send via JavaScript, then build a string with the other parameters, like so:
<?php
$params = $_GET;
unset($params['CMD']);
unset($params['PARA']);
?>
<script>
function SetPageShow(obj)
{
var params = '<?php echo http_build_query($params); ?>';
window.location.href = '?' + (params ? params + '&' : '') + "CMD=PAGEROWS&PARA=" + encodeURIComponent(obj.options[obj.selectedIndex].text);
}
Btw, I've also added encodeURIComponent() in JavaScript to perform proper escaping of the selected value.
Consider using PHP's sessions if you want to retain information like this.
<?php
session_start();
$_SESSION['foo'] = $bar;
?>
Then you can refer to this information on other pages by calling session_start() at the beginning of the page.
<?php
session_start();
$bar = $_SESSION['foo'];
?>