ajax load data from mysql - javascript

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";
}

Related

Call PHP Script from JavaScript with parameters

I have done a lot of research on Google and StackOverflow but I can't solve this problem (that's why this question is no duplicate):
I have a js function, which is called on click (working). With this function I'm trying to call a PHP script to execute... But it doesn't react... Please tell me what's wrong (complete solution would be appreciated...)
PHP code:
<?php
$servername = "bot-sam.lima-db.de:3306";
$username = "USER379138";
$password = "pwd";
$dbname = "db_379138_1";
$q = $_POST['q'];
$a = $_POST['a'];
function alert($msg) {
echo "<script type='text/javascript'>alert('$msg');</script>";
}
echo $q . $a;
// echo and alert are not opening so i think the php script isn't executing
alert("question is " . $q);
alert("answer is " . $a);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO knowledge_base ('question', 'answer')
VALUES ($q, $a)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
JavaScript function (which gets called properly; jQuery working):
function myfunc() {
var question = "test1";
var answer = "test2";
$.ajax({
url: 'phpscript.php',
type: 'POST',
data: {q: question, a: answer},
dataType: 'json',
sucess: console.log("SQL entry made")
});
}
I'm sorry to ask such a simple question but I just can't solve the problem...
Try to use the below code
function myfunc() {
var question = "test1";
var answer = "test2";
$.ajax({
url: 'phpscript.php',
type: 'POST',
data: {q: question, a: answer},
dataType: 'json',
success: function(result) {
console.log(result);
}
});
}

Post data from javascript to php file using ajax doesn't work

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));
}
});

Using two Ajax calls to post then retrieve data

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.

Ajax and PHP : SELECT query database

I have an UI in which the user can add objects (stored as JSON in my database). So, when the user is clicking on a button, it calls the ajax wich calls my php to get the desired JSON code.
The problem is that my ajax returns me "success" but with no JSON code. I don't know where the problem is located.
Here's my JS/AJAX:
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: {objectId: objectId},
dataType: 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
Here's my scriptObject.php:
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.");
echo json_encode($res);
[EDIT]
It answers me:
{"status":"error","message":"Problem in fetching data."}
Try following
<script type="text/javascript">
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
dataType : 'json',
data: { objectId: objectId },
success: function(response) {
var json = $.parseJSON(response);
if(json.status == 'error')
console.log(json.message);
else if(json.status == 'success')
console.log(json.objectJson);
}
});
</script>
and in scriptObject.php
<?php
// your database connection goes here
include 'config.php';
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.".mysql_error());
echo json_encode($res);
?>
scriptObject.php
if(isset($_POST['objectId']))
{
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
die;
}
you are execution the php code inside a function.
how does the compiler or the interpreter know to execute a function inside your php file.
Add dataType to your ajax options
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: objectId,
dataType : 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
then your php code
function getObjectJson() {
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
}

Ajax Call Success, Post not actually sent

I have tried removing the JSON.stringify and changing the post to get change cache to false and true. I am at a loss as to what needs to happen. It always goes to the else statement in my php and returns the default JSON. I have allowed crossdomain in my php with the wildcard so that is definitely not the problem.
Code:
$(document).ready(function() {
$('.check').click(function(){
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "POST",
crossDomain: true,
url: "retrieveColumn.php",
data: JSON.stringify({ ID: thisID}),
cache: true,
async:true,
datatype: "json",
success: function(data)
{
console.log(data);
alert(data);
}
});
});
});
PHP which always goes to the else condition:
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
Unless this is part of a larger document, you have unnecessary brackets which might be causing problems.
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
{ /* <!-- HERE! What is this?? */
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
You don't need to stringify the object you submit as data here:
data: JSON.stringify({ ID: thisID}),
Use:
data: { ID: thisID},

Categories

Resources