Im making a AJAX form but i have a problem with validation, i need to make a condition when a input data is greater than a variable i define in the action file echo something out, but my condition is not working its always returning true, here is the code:
<?php
include "../../admin/includes/controller.php";
$msg = "";
$balance = "";
#Get stuff from form...
if(!empty($_POST)) {
#Define submited variables
$user = $_POST['user'];
$type = $_POST['type'];
$asset = $_POST['asset'];
$price = $_POST['price'];
$amount = $_POST['amount'];
$margin = $_POST['margin'];
#Check balance...
$sql = "SELECT * FROM users WHERE username='$user';";
$result = $db->prepare($sql);
$result->execute();
while ($row = $result->fetch()) {
$balance = $row['balance'];
}
This is the condition i want to check:
if ($balance > $margin) {
$msg = "Trade opened successfully";
} else {
$msg = "low balance";
}
#Print out message...
echo $msg;}
?>
This is my AJAX code:
$(document).ready(function () {
$('#open').click(function (e) {
e.preventDefault();
var asset = $('#asset').val();
var amount = $('#amount').val();
var margin = $('#margin').val();
var user = $('#user').val();
var type = $('#type').val();
var price = $('#price').val();
$.ajax({
type: "POST",
url: "q/db.php",
data: {
"asset": asset,
"amount": amount,
"price": price,
"type": type,
"user": user,
"margin": margin
},
success: function (data) {
$('.result').html(data);
$('#contactform')[0].reset();
}
});
});
});
Related
I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);
My jQuery Ajax code:
$(".comment").click(function(){
var id = $(this).data("id");
var name = $("#username_"+id).val();
if(name==''){
alert("Please Fill All Fields");
}else{
$.ajax({
type: "POST",
url: "comments",
data:{username:name},
dataType: "JSON",
success: function(jsonStr){
$("#cmt_output").html(JSON.stringify(jsonStr));
}
});
}
});
My Php Code:
............
$con = mysqli_connect("localhost","root","","quotes") or die("Error".mysqli_error($con));
$name = $_POST['username'];
$user = get_userdetails();
$vw_id = $user->id;
$query = mysqli_query($con,"INSERT INTO tlb_comments(user_id,comments) values ('$vw_id','$name')");
$comments = mysqli_query($con,"SELECT * FROM tlb_comments");
$avatar = mysqli_query($con,"SELECT * FROM tlb_avatar WHERE `vw_id`='".$vw_id."'");
$avatar_select = mysqli_fetch_all($avatar);
$comment_select = mysqli_fetch_all($comments);
array_push($avatar_select,$comment_select);
echo json_encode($avatar_select);
I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}
I'm using a framework called Ispinia to do a simple system for my Company, and when I try to submit anyting give this error:
Web page message [object object].
I'm using IE11.
Thanks in advance!
CODE: Controller.js
function vila_do_conde_ctrl($scope, $http, SweetAlert){
$scope.dataInicio = new Date();
$scope.dataFim = new Date();
$scope.teste = function(){
alert($scope.myDate);
}
$scope.preencheEmbarques = function(){
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_embarques.php?oi="+$scope.oi)
.then(function (response) {$scope.embarques=response.data.records;$scope.emb = ""; $scope.dataChegada = ""; $scope.dataSaida = ""; $scope.dataDesova = ""; $scope.tipoCarga = ""; if($scope.ctn) $scope.ctn = ""; $scope.fornecedor = ""; $scope.servicoAdd = ""; $scope.qte = ""; $scope.unidade = ""; $scope.dataInicio = ""; $scope.dataFim = ""; $scope.obs = ""; $scope.servicos = ""; }, function (response){alert(response);});
};
$scope.buscaServicos = function(){
var embarque = encodeURIComponent($scope.emb.trim());
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_servicos.php?emb="+embarque)
.then(function (response) {
$scope.servicos=response.data.records;
for(var i=0; i<$scope.servicos.length; i++){
var dataAux = $scope.servicos[i].DataInicio.split("-");
$scope.servicos[i].DataInicio = dataAux[2]+"/"+dataAux[1]+"/"+dataAux[0];
dataAux = $scope.servicos[i].DataFim.split("-");
$scope.servicos[i].DataFim = dataAux[2]+"/"+dataAux[1]+"/"+dataAux[0];
}
}, function (response){alert(response);});
};
$scope.preencheDados = function(){
if($scope.emb){
var embarque = encodeURIComponent($scope.emb.trim());
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_dados.php?emb="+embarque)
.then(function (response) {
$scope.dados=response.data.records[0];
if($scope.dados.DtChegada){
$scope.dataAux=$scope.dados.DtChegada.split("-");
$scope.dataChegada=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
if($scope.dados.DtSaida){
$scope.dataAux=$scope.dados.DtSaida.split("-");
$scope.dataSaida=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
if($scope.dados.DtDesova){
$scope.dataAux=$scope.dados.DtDesova.split("-");
$scope.dataDesova=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
$scope.tipoCarga=$scope.dados.TipoCarga;
$scope.ctn=$scope.dados.Container;
$scope.buscaServicos();
}, function(response){alert(response);});
}
};
$scope.adicionarServico = function(){
if($scope.oi && $scope.emb && $scope.fornecedor && $scope.servicoAdd && $scope.qte && $scope.unidade && $scope.dataInicio && $scope.dataFim){
var embarque = encodeURIComponent($scope.emb.trim());
var fornecedor = encodeURIComponent($scope.fornecedor.trim());
var servico = encodeURIComponent($scope.servicoAdd.trim());
var quantidade = encodeURIComponent($scope.qte);
var unidade = encodeURIComponent($scope.unidade.trim());
var data_inicio = encodeURIComponent($scope.dataInicio.getFullYear()+"-"+ ($scope.dataInicio.getMonth() + 1) +"-"+$scope.dataInicio.getDate());
var data_fim = encodeURIComponent($scope.dataFim.getFullYear()+"-"+ ($scope.dataFim.getMonth() + 1) +"-"+$scope.dataFim.getDate());
var obs = "";
if($scope.obs)
obs = encodeURIComponent($scope.obs);
var container = ""
if($scope.tipoCarga){
if($scope.ctn)
container = encodeURIComponent($scope.ctn);
$http.get("http://127.0.0.1/DIARIODEBORDO/php/adicionar_tipo_carga.php?oi="+$scope.oi+"&emb="+embarque+"&ctn="+container)
.then(function (response) {}, function (response){alert(response);});
}
$http.get("http://127.0.0.1/DIARIODEBORDO/php/adicionar_servico.php?oi="+$scope.oi+"&emb="+embarque+"&forn="+fornecedor+"&servico="+servico+"&qte="+quantidade+"&unidade="+unidade+"&dtInicio="+data_inicio+"&dtFim="+data_fim+"&obs="+obs)
.then(function (response) {
SweetAlert.swal({
title: "Serviço adicionado!",
//text: "You clicked the button!",
type: "success"
});
$scope.buscaServicos();}, function (response){alert(response);});
}
else
alert("Preencha todos os campos!");
};
MODEL:
<?php
$oi = $_GET['oi'];
$emb = $_GET['emb'];
$fornecedor = $_GET['forn'];
$servico = $_GET['servico'];
$quantidade = $_GET['qte'];
$unidade = $_GET['unidade'];
$data_inicio = $_GET['dtInicio'];
$data_fim = $_GET['dtFim'];
$obs = $_GET['obs'];
// Create connection
$conn = new mysqli($host, $usuario, $senha, $base_de_Dados);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($obs != "")
$sql = "INSERT INTO diario_bordo.servicos (OI, EMBARQUE, FORN_SERVICO, SERVICO, QUANTIDADE, UNIDADE, DATA_INICIO, DATA_FIM, OBSERVACOES) VALUES ('".$oi."','".$emb."','".$fornecedor."','".$servico."',".$quantidade.",'".$unidade."','".$data_inicio."','".$data_fim."','".$obs."')";
else
$sql = "INSERT INTO diario_bordo.servicos (OI, EMBARQUE, FORN_SERVICO, SERVICO, QUANTIDADE, UNIDADE, DATA_INICIO, DATA_FIM) VALUES ('".$oi."','".$emb."','".$fornecedor."','".$servico."',".$quantidade.",'".$unidade."','".$data_inicio."','".$data_fim."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
[object Object] is the way JavaScript outputs an object. Not sure what the purpose of your script is, but you can show the sub-object by using objectname.key.
e.g. if 'person' is an object containing name and mail address, you can access the sub-objects (probably strings in this example) by calling person.name and person.mailaddress.
I think you should now go through your code again and have a look at all alert messages.
If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.