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.
Related
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);
When I tried to used ajax to post data from javascript file to php file, there was nothing displayed on php file after using
$_POST['userinput']
Here is the javascript file:
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
userinput = places[0].name.toString(); // Get user input from search box
// Pass data to userinput.php via ajax
$.ajax({
url: 'userinput.php',
data: {userinput : userinput},
type: "POST",
success: function (result) {
alert(JSON.stringify(result));
}
});
});
php file:
if (isset($_POST)) {
$servername = "localhost";
$username = "XXXXXXX";
$password = "XXXXXXXXX";
$dbname = "CALIFORNIA";
$city = $_POST['userinput']; // Nothing is posted here
// Create connection
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
$sql = $conn->prepare("SELECT State FROM CITY as C WHERE C.City_name=$city");
$sql->execute();
$result = $sql->fetchAll();
$json = json_encode($result);
echo $json;
}
I was able to connect to the mysql database. However, there was no data posted from javascript file to php. I'm not sure what to do from this point. the value $city print out nothing. On the client side it printed out an empty object.
in your ajax function try setting dataType property
$.ajax({
url: 'userinput.php',
data: {'userinput' : 'userinput'},
type: "POST",
dataType: "text", // add this property
success: function (result) {
alert(JSON.stringify(result));
}
});
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
Hello i'm tryin to load data from server using ajax. Here is my js
<script>
jQuery(document).ready(function($){
$("#mc-prize").click(function(){
event.preventDefault();
$.ajax({
url: "includes/prize.php",
type: "GET",
datatype: "text",
data: {"num": num},
cache: false,
success: function(response){
$("#some-block").append(response);
}
});
});
});
</script>
Here is my prize.php file
<?php
$host = '#';
$user = '#';
$password = '#';
if (isset($_POST['submit'])){
$prize_email = $_POST['email'];
$mysqli = new mysqli($host, $user, $password, $user);
$result = $mysqli->query("SELECT * FROM prize_numbers WHERE email = '" .$prize_email. "'") or die ("Couldn't connect to database.");
$row = $result->fetch_assoc();
if($row['email']) {
echo "Your num: ".$row['num'];
} else {
echo "No email in db";
}
}
?>
But when i'm trying to get some data from db i see an error:
"Uncaught ReferenceError: num is not defined"
Whats wrong?
UPD: Sorry what is correct js for my php? What i need to place in data?
Your problem is not in your php but in the js code
this code
data: {"num": num},
the variable num is not defined anywhere in the js code
try to use this code:
<script>
jQuery(document).ready(function($){
$("#mc-prize").click(function(){
var some_email = ''; // DEFINE HERE THE EMAIL YOU WANT TO SEND
event.preventDefault();
$.ajax({
url: "includes/prize.php",
type: "POST",
datatype: "text",
data: {"email": some_email,"submit": 1},
cache: false,
success: function(response){
$("#some-block").append(response);
}
});
});
});
</script>
your num in JQuery is not defined.
Data is the parameters you're transferring out and response is the result you're getting as an output.
Just replace this line of code
data: {"num": num}, with data: "email="+email_var and add implementation of variable email_var (for ex: var email_var = "simplemail#mail.org").
UPD: Pass email so that you can check it in PHP.
if (isset($_POST['email'])){
$prize_email = $_POST['email'];
$mysqli = new mysqli($host, $user, $password, $user);
$result = $mysqli->query("SELECT * FROM prize_numbers WHERE email = '" .$prize_email. "'") or die ("Couldn't connect to database.");
$row = $result->fetch_assoc();
if($row['email']) {
echo "Your num: ".$row['num'];
} else {
echo "No email in db";
}
I am trying to let jQuery dynamically add html to my page. Unfortunately, I don't receive a response from my server. My JS code sends a GET request, which contains a parameter (bodypart). The server should return a response including the results from the database, but the response is empty.
What causes this problem?
JAVASCRIPT:
function getData() {
var sPanelHeading = '<div class="col-lg-3"><div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">Symptomen van ' + bodypart + '</h3></div>';
$( "#abc" ).append(sPanelHeading);
$.ajax({
url: 'controller.php',
data: 'bodypart=Autism',
dataType: 'json',
}).done(function(data) {
$( "#abc" ).append('<div class="panel-body" style="overflow-y: scroll;"><span class="list-group-item"><b>Vaak voorkomende symptomen</b></span></div><div class="list-group">');
for (var c in data) {
$("#abc").append('<span class="list-group-item">');
$("#abc").append(c);
$("#abc").append('</span">');
}
}).always(function(data) {
console.log(data);
});
}
PHP:
<?php
require_once( 'config.php' );
$bodypart = $_GET['bodypart'];
$sql = "SELECT c_name FROM condition WHERE c_name = '$bodypart'";
$result = $conn->query($sql);
$json_response = array();
if ($result->num_rows > 0) {
while($row = mysql_fetch_assoc($query)) {
$json_response[] = $row;
}
print json_encode($json_response);
}
$conn->close();
?>
1st : instead of
data: 'bodypart=Autism',
use
data: {'bodypart':'Autism'},
2nd
echo json_encode($json_response);
Basics of $.ajax
$.ajax({
url: 'controller.php',
type: 'GET',
data: {'bodypart':'Autism'},
dataType: 'json',
success : function(data){
alert(data);
}
});
in php
<?php
$bodypart = $_GET['bodypart'];
echo $bodypart;
?>
output should alert Autism .. if this Ok you can complete your stuff .. if something went wrong .. check your php file path