Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);
Related
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() ,
I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.
I'm trying to work with ajax, but I'm stuck, because I tried various things to import a var from a php file to js. What am I supposed to write after the success: function() to import $rowcount to js? I know that there are already some questions and answers on the site, but none of those seems to work...
Here's the php code:
<?php
$host = "localhost";
$user = "root";
$pw = "";
$dbName = "mathgame";
$tblName = "fragen";
// mit mysql db verbinden
$con = mysqli_connect($host, $user, $pw, $dbName);
if ($con->connect_error) {
die ("Connection failed: " . $con->connect_error);
}
// Datenanfrage an db
$result = mysqli_query($con, "select id from $tblName where Kategorie='Kategorie1'");
$rowcount = mysqli_num_rows($result);
json_encode($rowcount);
?>
And the js code:
<script id="source" language="javascript" type="text/javascript">
$.ajax({
url: 'Kategorie1.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(){
}
})
json_encode() returns a string but your code does nothing with the value. All you need to do is write the return value to stdout. One way to do that is:
echo json_encode($rowcount);
You would need to take in the data that is returned from your PHP script.
Add the data after success: function( for you to manipulate and use the return data.
<script id="source" language="javascript" type="text/javascript">
$.ajax({
url: 'Kategorie1.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) {
console.log(data); // outputs the json data into your console
}
})
$.getJSON("Kategorie1.php", function (data) {
var nrFragen = JSON.parse(data);
That's the js code, which worked for me, and of course at the end of the php code there should be : echo json_encode($rowcount);
Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.
I'm trying to send a picture stored in localstore with javascript but can't retrieve it and show it.
Javascript part :
liste['pic'] = localStorage['pic'];
$.ajax({
type: "POST",
url: "save.php",
data: { pic : liste['pic'] },
dataType: "json",
success: function(data) {
if(data) {
alert("Picture sent succesfully");
}
}
});
The php part that receive the data :
require "lib/connect.php";
$pic = $_POST['pic'];
$insert_query = "INSERT INTO liste ( `pic` ) VALUES ( '".$pic."' );";
$result = mysql_query($insert_query);
The php part that shows the pic.
There's something in the table but since it's blob , I can't check if the right data.
$select_query = "Select `pic` From liste;";
$result = $dbhandle->query($select_query);
echo "<table border='1'>
<tr>
<th>Image</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><img src=\"" . $row['pic'] . "\" width=\"200\"/><br/><br/></td>";
echo "</tr>";
}
echo "</table>";
$result->closeCursor();
mysqli_close($dbhandle);
from this I get a broken image. What is missing ? Text works but not image, why ?
What you need to know is that when you are sending values encoded in json through POST, these values are not present in the $_POST variables.
The only way to have values in the POST variables is by using having the application/x-www-form-urlencoded and multipart/form-data.
If you wish to use another content-type, you actually need to use 'php://input'.
e.g.
$data = json_decode(file_get_contents('php://input'), true);
$text = print_r($data, true);
You should then see an array containing your image's data.