Parsing JSON data with a local AJAX request - javascript

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.

Related

Using extra php files to get the ajax post request and then load the php script

i have a task which is very complicated for me and also explain to you.. I will give my summary on what i m supposed to do.. there are 3 files which are the
1.html file which perform ajax post to the passwrapper.php
2. passwrapper.php will receive the ajax post request and include another file which is 3.student.php which contain codes on how to perform connection to the database and convert all data to json and then show all the data..
I was asked to perform ajax post multiple items.. In other words, i was asked to receive name and religion from the last row of database.. here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: true,
lastReligion: true,
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
executePass();
}
else
{
//how to get name and religion from the last row and then perform executepass() to show all data and also data from the last row
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
my question is how to get last data from the last row which are student_name and student_religion in the passwrapper.php and also perform executepass() to show all data... please do not modify the sql code. i also do not want get data from the success. for example: data[count(data)-1]['student_name']...
my question is how to get the last values which are student_name and student_religion in the passwrapper.php... and also perform the executepass() function to show all data.. please help me... you can write the last data to the files or show in the html console..
Best would be to change executePass() so it ends with return $json_array; instead of echoing it. Then passwrapper.php could do:
$students = executePass();
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"]))){
echo json_encode($students);
}
else {
file_put_contents("all_students.json", json_encode($students);
$last_student = end($students);
echo json_encode(array($last_student));
}
And other scripts that want to return all the students can do:
$students = executePass();
echo json_encode($students);
If you can't do that, use the output buffering functions to capture the output from executePass() instead of sending it to the client.
else {
ob_start();
executePass();
$json = ob_end_clean();
file_put_contents("all_students.json", $json);
$students = json_decode($json, true);
$last_student = end($users);
echo json_encode(array($last_student));
}

Ajax MySQL query does not return current data

I want to write an Ajax request that Returns data from a MySQL-database. But it does not work properly, because the Ajax request does not return the current values of the mysql database, if data has changed. Instead it always returns the old data of the database. The php-file is working properly, if I open it in a browser, it shows the correct current data values. I found out, that the Ajax request only shows the correct current data values, if I first open the php-file manually in a browser. If I then again use the ajax request, it returns the correct current data. What am I doing wrong?
This is the code for the Ajax request:
var scannedTubes = (function() {
var tmp = null;
$.ajax({
async: false,
url: "ajaxtest.php",
success: function(response) {
alert("RESPONSE: " + response);
tmp = response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
return tmp;
})();
The code of the ajaxtest.php file is the following:
<?php
$con = mysqli_connect("", "root");
if(mysqli_connect_errno()){
echo "FAIL: " . mysqli_connect_error();
}
mysqli_select_db($con, "multitubescan");
$queryStr = "SELECT code FROM scan WHERE row = 0 AND code <> 'EMPTY'";
$res = mysqli_query($con, $queryStr);
$num = mysqli_num_rows($res);
$scannedTubes = "";
while($data = mysqli_fetch_assoc($res)){
$scannedTubes = $scannedTubes . " " . $data["code"];
}
$scannedTubes = $num . " " . $scannedTubes;
mysqli_close($con);
echo $scannedTubes;
?>
I suppose data is cached by your browser.
Make the url unique:
url: "ajaxtest.php",
to
url: "ajaxtest.php?rnd=" + Math.random() ,

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

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.

Ajax PHP error while passing data from ajax to php

My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.

Secure AJAX POST/GET jquery

So basically my question is simple.
Imagine situation when you a making a login or register form. With jquery.post i make ajax call
$.post( "pages/form_handle.php", name: $.(".username").val(), pass: $.(".pass").val() , function( data ) {
$( ".result" ).html( data );
});
it's simple call(i belive so)...
How to make it secure?
So if user look in my source code he or she know where i send my data in example pages/form_handle.php also he or she know what data i send to this page.
One of idea what i have simple send all ajax calls to one page ajax.php adding extra variables who will call right php function for ajax call...
But does it is the right way? Or maybe there is some better way to make it secure?
Stick to basics, and keep salting your passwords.
AJAX is not server side language, its a javascript plugin that does the same thing as forms, actions, etc... just in background as a new request.
Your ajax is not in danger, but your php files are, you can use jquery-validate.js to check on users input, but also you should make validation check in your ajax.php.
Here is a simple ajax login request:
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = data[1].value; // data to ajax.php page
data = JSON.stringify(data);
$("#loginButton").html('Login');
$.ajax({
type: "POST",
url: "ajax.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if ajax.php returns success, redirect to homepage or whatever
} else {
// if ajax.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
And the simple ajax.php login:
<?php // ajax.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])){
$un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = mysql_query($query);
if (!$result) die("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result)){
$row = mysql_fetch_row($result);
$salt1 = "qm&h*";
$salt2 = "pg!#";
$token = md5("$salt1$pw_temp$salt2");
if ($token == $row[3]) echo "$row[0] $row[1] :
Hi $row[0], you are now logged in as '$row[2]'";
else die("Invalid username/password combination");
} else die("Invalid username/password combination");
}else{
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function mysql_entities_fix_string($string){
return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>

Categories

Resources