display data js from datebase sql [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
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 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.

Related

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

Unable to see the source of the problem with the code for sending data to PHP file

I am very sorry to appear much ignorant but I have experienced this problem for long and I am now completely unable to understand why my JQuery function is not working.
I need this code to send data to PHP file which I am sure its working. I have tried to code everything with php but I have found there are place that I will have to include ajax.
$(document).ready(function(){
$('#sending').on('submit', function(event){
event.preventDefault();
if(($('#receiver_id1').val() == '0') && ($('#receiver_id2').val() == '0') && ($('#receiver_id3').val() == '0'))
{
alert("Please fill in the recipient!");
return false;
}
else if($.trim($("#message").val()) == '')
{
alert("You cannot send an empty message.");
return false;
}
else if($('#subject').val() == '')
{
var retVal = confirm("Are you sure to send a message without a subject?");
if( retVal == true ) {
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
type:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
} else {
return false;
}
} else
{
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, from_user_name:from_user_name, from_user_id:from_user_id, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
I really need help. I absolutely need this script to work. Thanks in advance.

Why can I not iterate over this object? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am trying to iterate over an object, but the jquery $.each won't fire.
This is the outcome of the $fileNames variable:
and this is the code I've built so far:
$("input[type=button]").on("click", function(){
$searchtag = '';
$files = '';
$fileNames = {};
// first get all files in the directory
$.ajax({
url: "php/cse.php",
data: "requestFileNames=true",
method: "POST",
success: function(result){
$result = JSON.parse(result).toString();
$result += ",";
$count = ($result.match(/o/g)||[]).length + 1;
for (var i = 1; i <= $count; i++) {
$fname = $result.substr(0, $result.indexOf(','));
$fileNames[$fname] = {};
$result = $result.replace($fname + ",", "");
}
}
});
console.log($fileNames);
$.each($fileNames, function(key, value){
// this does not fire, for some reason.
});
});
Why is it not working?
Make async false, but this will pause the code.
$.ajax({
url: "php/cse.php",
data: "requestFileNames=true",
method: "POST",
**async: false,**
success: function(result){
$result = JSON.parse(result).toString();
$result += ",";
$count = ($result.match(/o/g)||[]).length + 1;
for (var i = 1; i <= $count; i++) {
$fname = $result.substr(0, $result.indexOf(','));
$fileNames[$fname] = {};
$result = $result.replace($fname + ",", "");
}
}
});
Or call the function (i.e. $.each()) within success or complete method

commands in chatroom & defining words after command

Okay basically I'm trying to have a action happen of alert('hi $message'); when a user enters the command /command lewis into the chatroom; In the alert I have stated the variable $message and this is the word followed by the command; for example /command $message. I have posted my script below; so basically what I'm trying to achieve is recognise when a user types /command followed by a $message into the textarea then perform an action.
Chatroom Javascript
name ='<? echo $chat_room_username; ?>';
$("#name-area").html("You are: <span>" + name + "</span>");
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
var newdata = data.text[i].replace(/:brand/g,"<img src=\"/_img/logo1.png\"></img>");
newdata = newdata.replace(/:tipsound/g,"<audio autoplay><source src=\"/tip.wav\" type=\"audio/mpeg\"></audio>");
<?
$select_gifs = mysql_query("SELECT * FROM `submited_chatroom_gifs` WHERE `staff` = '1'");
while($gif = mysql_fetch_array($select_gifs)){
?>
newdata = newdata.replace(/:<? echo $gif['name']; ?>/g,"<img data-toggle=\"tooltip\" height=\"<? echo $gif['height']; ?>\" width=\"<? echo $gif['width']; ?>\"title=\":<? echo $gif['name']; ?>\" src=\"/_img/gifs/<? echo $gif['img']; ?>\"></img>");
<? } ?>
$('#chat-area').append($("<p>"+ newdata +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
process.php
<?php
$function = $_POST['function'];
$room = $_GET['room'];
$log = array();
switch($function) {
case('getState'):
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = $_POST['nickname'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
fwrite(fopen($room . '.txt', 'a'), "<p><font size=\"2px\">". $nickname . ": " . $message = str_replace("\n", " ", $message) . "</font></p>\n");
}
break;
}
echo json_encode($log);
}
?>
the alert is only for the person who wrote the command in
Thankyou for any help, and I apologise for the lengthy question.
[edit] Sorry just re-read my question and I will just try and explain what I'm trying to achieve in abit more detail. So basically when a user inputs /command lewis the script would then perform an alert('Hi Lewis');. But then if a user was to enter /command john the alert would be alert('Hi John');.
The alert would be instead of posting the message to the chatroom.

Sending an array of objects to PHP function with jQuery.ajax request

There is an array of objects like this:
rectangle[0].width = w;
rectangle[0].height = h;
rectangle[1].width = w;
rectangle[2].height = h;
rectangle[3].width = w;
rectangle[3].height = h;
...
How we may to send this array to PHP function with jQuery.ajax request and vise versa, modified array from PHP function as response?
I mind that JS code may be:
request = $.ajax({
type : "POST",
url : "post.php",
data : {rec :rectangle}
});
request.done(function(msg) {
alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
and PHP:
if (isset($_POST["rec"]) {
$rec = $_POST["rec"];
$arr_length = count($rec);
$response = $arr_length;
}
echo $response;
Please, demonstrate the true form of request. Thanks.
Very easy:
<script>
var myarray = new Array();
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
$.post(
'test.php',
{ data: paramJSON },
function(data) {
var result = JSON.parse(data);
}
</script>
php side:
if(isset($_POST["data"]))
{
$data = json_decode($_POST["data"]);
$myarray = $data->myarray;
foreach($myarray as $singular)
{
// do something
}
}

Categories

Resources