0

I would like to push my value of textbox to sql and then display it. I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php

    $("#send").click(function(){

    var username = "<span class ='username' = >Klient: </span>";
    var newMessage = $("#textbox").val();
    nw = newMessage;
    $.ajax({
    type: "POST",
    url: "db2.php",
    data: {'name': nw },
    success: function (json) {
        jss = json.PYT;
        oss = json.ODP;
        console.log(jss);
    }

});
    $("#textbox").val("");

    var prevState = $("#container").html();


    if( prevState.length > 3){
        prevState = prevState + "<br>";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });

and my db2.php .

<?php
header('Content-type: application/json');
include 'connect.php';  

if (isset($_POST['name'])) {

$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE 
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
    $result[] = $pomoc;
}
}

echo json_encode($result);

Now my result is {}, echo is null.

console.log(nw) VM289:1 dsasa undefined I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards

UPDATE. Now I would like to get jss value out of this function to the other one.

   var jss = {}; //(first line code)

    $("#send").click(function(){

    var username = "<span class ='username' = >Klient: </span>";
    var newMessage = $("#textbox").val();
    nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: { 
    'name': nw, 
},
success: function(data){
   jss = data[0].PYT;

}
});

UPDATE 2

var jss2 = {};
var nw;




$(function(){

username();

$("#textbox").keypress(function(event){
if ( event.which == 13) {
    if ( $("#enter").prop("checked") ){

        $("#send").click();
        event.preventDefault();
        }
    }
});
$("#send").click(function(){

    var username = "<span class ='username' = >Klient: </span>";
    var newMessage = $("#textbox").val();


    $("#textbox").val("");

    var prevState = $("#container").html();


    if( prevState.length > 3){
        prevState = prevState + "<br>";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });


})

function send_message(message){

    var prevState = $("#container").html();

    if(prevState.length > 3){
    prevState = prevState + "<br>";
    }

    $("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
    $("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;

}

function ai(message){
    var jss;
    message = message.toLowerCase();
    nw = message;

    $.ajax({
type: 'POST',
url: 'db2.php',
data: { 
    'name': nw, 
},
success: function(data){
   jss = data[0].PYT;

}
});

console.log(jss);
    if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
    send_message(Answer);
    return;
    }

    else{
    send_message("Nope ");
    }

}  
  • I'm guessing the query returns no results. does the query work if you run it directly in SQL (substituting your $name variable of course)? BTW you should really use parameterised queries - this is ripe for SQL injection attacks. http://bobby-tables.com/ explains the problem and includes example solutions for PHP/mysqli. – ADyson Dec 08 '17 at 10:34
  • Yes If i run directly from sql its ok, then if i change my ajax and just select * from table i can display it $.ajax({ url: "db.php", async: false, dataType: 'json', success: function(data) { jss = data[0].PYT; jss2 = data[1].PYT; oss = data[0].ODP; oss2 = data[1].ODP; } }); But I want to get value from function and then search in datebase and then display Thanks for this site I will read this and do best, but first I just want to run this – KompanierosB Dec 08 '17 at 10:45
  • 1
    You mentioned `var_dump($_POST['name']);` shows null, is that right? In that case, check that `$("#textbox").val();` in your JS returns a value. I can't see your HTML, so don't know if that's correct or not. – ADyson Dec 08 '17 at 10:54
  • I updated my statement, and my last problem "solved" i don't know but now it works but unsuccesfully only in this function . I need value to update other function ai(message). – KompanierosB Dec 08 '17 at 11:13
  • "out of this function to the other one". What "other one" do you mean? I see only one function in your code. Can you just call this other function from your "success" function and pass to it the new value of jss? I don't know what the function is for, or when it's supposed to be executed, so it's hard to know what to suggest. – ADyson Dec 08 '17 at 12:04
  • Okay sorry, i though it was more clearly, now as u see change place ajax cause te message is the same value. But jss is {}. Thanks for attention – KompanierosB Dec 08 '17 at 12:20
  • Do you mean `console.log(jss);` shows `{}`? This will always be null because it runs before the ajax call has time to complete. Ajax calls run async inside another thread. Any code you write on the line after $.ajax will be executed immediately, in parallel to the ajax call. It doesn't wait. If you have some code which relies on the value of `jss` being populated from the ajax call, then quite simply it has to be executed after the ajax call has completed. The simplest way to achieve that is to put it inside the "success" function (or in a function which you call from inside the "success" – ADyson Dec 08 '17 at 12:46
  • You have given to $.ajax a callback function which you identified as the "success" function for your ajax call (`success: function(data){ jss = data[0].PYT; }`). This is held in a variable by $.ajax, and then executed at a later time when the ajax request completes successfully. This is the place where your `jss` variable gets populated. If you have some other code (such as you showed above) which needs the value of `jss` in order to work properly, then you must put that code into this same "success" callback function, or in a function which is called by that function. – ADyson Dec 08 '17 at 14:14
  • That is the only way to fully guarantee that your variable will have the necessary value in it when the code runs, because it is guaranteed to run _after_ the ajax request completes, and therefore the variable `jss` has been populated with a value. This is because ajax requests run asynchronously. – ADyson Dec 08 '17 at 14:16

1 Answers1

0

I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:

function ai(message){
  var jss;
  message = message.toLowerCase();
  nw = message;

  $.ajax({
    type: 'POST',
    url: 'db2.php',
    data: { 
      'name': nw, 
    },
    success: function(data){
      jss = data[0].PYT;
      console.log(jss);
      if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
        send_message(Answer);
        return;
      }
      else{
        send_message("Nope ");
      }
    }
  });
}

Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

ADyson
  • 57,178
  • 14
  • 51
  • 63