ajax load data from mysql

189 views Asked by At

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?

2

There are 2 answers

4
zion ben yacov On

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>
0
Reminisce On

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 = "[email protected]").

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