AJAX call unable to fetch data from PHP, shows undefined data - javascript

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.

Related

How to pass JavaScript values to PHP within the Ajax

Here is the situation.
I'm trying to pass from some Javascript values to various PHP functions within my ajax so it can properly be displayed on the page.
Here is my code:
$("[data-department-id]").click(function() {
id = $(this).attr('data-department-id');
document.getElementById('department'+id).innerHTML = '';
$.ajax({
url:"/desk/template/fetchtickets.php",
type: 'POST',
dataType: 'json',
data : {
'id' : id
},
success: function (res) {
$('#department'+id).append('<ul>');
for (var key in res) {
var ticketId = res[key].id;
var clientId = res[key].clientid;
var clientName = res[key].name;
var clientColor = res[key].hexColor;
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
$('#department'+id).append('<li class="list-group-item list-group-item-light" data-date-2="<?php echo Ticket::lastReplyStamp($ticketId); ?>"> <span class="text-width">'+res[key].ticket+' '+res[key].subject+'</span><div class="tools" ><span class="client-listing"> <?php clientBadge($clientId,$clientName,$clientColor); ?> <?php // echo "<scipt>document.writeln(test)</script>"; ?> '+test+' </div></div></li>');
}
$('#department'+id).append('</ul>');
}
});
})
When I do a console.log();
It shows the proper value, however, when I do an echo $ticketId, it shows +ticketId+ .
Now I did do a document.write and document.writeln and it still doesn't work.
Is there a proper solution to resolve my problem?
You can not add php code here.You can use JQuery to change value in the Dom or set some hidden inputs value, but you can not set php variable in JS. PHP runs on the server side. When the php code is running, your js code is waiting to be run on the client's computer.
These line are always going to be interpreted as string assign from server side.
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
The order of your code processing is something like this :
PHP code get processed
PHP returns HTML
User clicks an element (in your case data-department-id)
JQuery sends ajax request
Server processes the request and sends response back to the frontend
Ajax success function receives the response and now has the response in javascript variable res which is passed as argument of success(res) function
All the code inside success is executed
Alternatively if the server throws an error response, no 6. and 7. would trigger the error callback
But the main part it, the PHP code in your success() function will NOT run as you are thinking, which is after the Ajax receives response. At this point all you can do is use javascript to manipulate the variables.
So in short, change below part and use javascript or jQuery if you have it to change DOM elements based on response.
<?php $ticketId = '"+ticketId+"'; ?>
...
...
For example, let's say you have an H1 tag which shows ticket id. You would do
// jQuery
$('#ticketIdElement').text(res.id);

getting JSON into d3.js file

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; ?>;

converting Javascript variable to PHP variable in two different php file

Can some body help me get the current value from this option tag
to account.php as a session variable or anything ..
// loadsubcat.php This code is for dependent dropdown
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
var javascriptVariable = $('#sub_cat').val();
I know this can be solve using ajax but I don't know how.
I will use the javascript variable as a reference for a couple of checkboxes under it but first must be passed as a php variable.
you ajax will look like this,
$.ajax({
type: 'POST',
url: "account.php",// path to ajax file
data: {javascriptVariable:javascriptVariable},// you can pass values here in key value pairs.
success: function(data) {
alert(data);
}
});
You can send n number of key => value pairs.
like
parent_cat:100
Next:
echo $_POST['javascriptVariable']; // <--- grabbing ajax data here
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
what ever echoed in php file will come in ajax success data,
alert(data) will alert what you had echoed in php. you can use that in your html file.

Parsing JSON data with a local AJAX request

I've got a php file on a webserver that executes queries to a MySQL database.
I'm testing a site on my pc (locally) that uses a js file with an AJAX request to get JSON data from that php file.
Is it possible to do it like this, or the js file must be put on the same domain server of the php file?
Because the console.log of the parsed data gives me this error:
Uncaught SyntaxError: Unexpected token I
This is the ajax call
$.ajax({
method:"POST",
crossDomain:true,
url:"url for the php file",
data:{
query: "SELECT * FROM course_categories;"
},
success: function(response){
var course_categories=JSON.parse(response);
console.log(course_categories);
var el="";
console.log(course_categories.length);
for(var i=0;i<(course_categories.length);i++)
{
}
},
error: function(request,error){
console.log("ERROR: Request " + request + "\nSpecific Error: " + error);
}
While this is the PHP call
<?php
//get all the courses from the database and reply using the JSON structure
//$mysqli=new msqli("localhost","username","password","dbname");
$mysqli=new mysqli("localhost","hey","","db_name");
if(mysqli_connect_errno()) //returns a number of the error if there is any, if not
{
echo json_encode("Error to connect to DBMS".mysqli_connect_error());
exit(); //closes the connection
}
else
{
$query=$_POST["query"];
//$query="SELECT * FROM course_categories";
$result=$mysqli->query($query); //do a query (->query) setted by $query, using the $mysqli variable, and store the data in $result
if($result->num_rows >0) //if there is at least one row...
{
$myArray= array(); //...create an array...
while($row = $result->fetch_array(MYSQL_ASSOC))
{
//...and fetch it. Everytime this operation returns a row,
$myArray[]=$row; //...and added to myArray ([] means autoincrement).
}
}
echo json_encode(utf8ize($myArray));
//free result
$result->close();
//close connection
$mysqli->close();
}
I did it. All I had to do, was to remove the crossDomain:true line so that the JSON could actually parse the data.

Update my php array in javascript function

I want to update or add new key=>value to my php array in javascript function.
The paging is in ajax, page is not reloaded again.
Actually I am receiving the data in a text file which is uploaded on my server. I parse that file and get a limited number of records, when I click on NEXT then one more file is uploaded on server and I parse it once again and show the data. So, I want that all data to be stored in php array on that page so when next time I go to PREVIOUS record, it doesn't parse the file once again, just show the data from the array.
//php array name is $call_data
var file_data = <?php $content = #file_get_contents("text file name");
$content = rawurldecode($content);
$new_call_data = json_decode( $content );
foreach ($new_call_data->CALLS as $key => $val) {
$call_data['CALLS'][] = $val; $file_rec_start++;
}
echo json_encode( $call_data ); ?>;
i don't see the part, where you split your "content" part into peaces so you have to reload the page, is it missing or is this part in JavaScript?
also you could minify you source:
<?php
$my_contents = file_get_contents('myfile.json');
$my_contents = rawurldecode($my_contents);
$my_array = json_decode($content);
$my_json = json_encode(array_values($my_array->CALLS));
?>
var file_data = <?=$my_json?>;
than you can itterate trough the array in javascript without the need of refreshing the page.
you could use
var results_per_page = 25
var page_available = Math.ceil(file_data.length / results_per_page);
var page = 0;
var page_array = file_data.slice((page * results_per_page), ((page+1)*results_per_page));

Categories

Resources