I can't receive the data value on my php script, the ajax success fires but the data on my database is not changed when I send this.
$.ajax({
type: "POST",
url: "database/clientpanel/agent_panel/notiffolder/notifedit.php",
data: {
email: email,
number: number,
emailon: emailon,
texton: texton,
email_delay: emaildel,
ext_delay: textdel,
timezone1: zone1,
timezone2: zone2
},
cache: false,
success: function(html){
$("#upnotif").show();
$("#errnotif").hide();
$("#errnotif1").hide();
$("#errnotif2").hide();
}
});
php
<?php
session_start();
include("../../../dbinfo.inc.php");
$query=" select * from tele_panel_notification where client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$client = $row['client'];
if($client == ""){
$query = "insert into tele_panel_notification set
emailon = '".$mysqli->real_escape_string($_POST['emailon'])."',
texton = '".$mysqli->real_escape_string($_POST['texton'])."',
timezone = '".$mysqli->real_escape_string($_POST['timezone'])."',
timezone2 = '".$mysqli->real_escape_string($_POST['timezone2'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
email_delay = '".$mysqli->real_escape_string($_POST['email_delay'])."',
text_delay = '".$mysqli->real_escape_string($_POST['text_delay'])."',
number = '".$mysqli->real_escape_string($_POST['number'])."',
client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "true";
}else{
//if unable to create new record
printf("Errormessage: %s\n", $mysqli->error);
}
}
else{
$query = "UPDATE tele_panel_note SET
emailon = '".$mysqli->real_escape_string($_POST['emailon'])."',
texton = '".$mysqli->real_escape_string($_POST['texton'])."',
timezone = '".$mysqli->real_escape_string($_POST['timezone'])."',
timezone2 = '".$mysqli->real_escape_string($_POST['timezone2'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
email_delay = '".$mysqli->real_escape_string($_POST['email_delay'])."',
text_delay = '".$mysqli->real_escape_string($_POST['text_delay'])."',
number = '".$mysqli->real_escape_string($_POST['number'])."'
where client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "true";
}else{
//if unable to create new record
printf("Errormessage: %s\n", $mysqli->error);
}
}
//close database connection
$mysqli->close();
?>
Take a look at your PHP part,
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$client = $row['client'];
if($client == ""){
You should verify directly with your row if you want to be able to know if the row already exists:
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
//$client = $row['client'];
if(!$row){
And then your client variable is useless.
Related
I am working on a scanner reader, so I used ajax when the code is read by the scanner, it should insert data to the database. The problem is the data is not inserting.
Inside the script / Ajax - query is the variable I used to get the data (name)
var query = $('#scanned-QR').val();
fetch_customer_data(query);
$(document).on('keyup', '#scanned-QR', function(){
var query = $(this).val();
fetch_customer_data(query);
});
function fetch_customer_data(query = '')
{
$.ajax({
url:"validScan.php",
method: 'GET',
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
if (data.status == '1') {
decoder.stop();
alert('Sucess!');
}
else if(data.status=='0'){
decoder.stop();
alert('Fail!');
}
},
error:function(err){
console.log(err);
}
});
}
My Input/Textarea
<textarea id="scanned-QR" name="scanQR" readonly></textarea>
MySQL
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
}
mysqli_close($link);
?>
For insert query, result will return as boolean, So mysqli_num_rows($res) won't accept boolean argument. mysqli_num_rows() expects parameter 1 to be mysqli_result
So you can simply check by below, whether it is inserted or not:
if ($res) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose);
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose);
exit;
}
mysqli_close($link);
You should use exit try following code :
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
exit;
}
mysqli_close($link);
exit;
mysqli_num_rows() is for getting the number of rows returned from a SELECT query. You need to check the number of affected rows instead.
You should also be using a prepared statement, and I also recommend that you set up MySQLi to throw errors. I also prefer the object-oriented approach.
<?php
// Configure MySQLi to throw exceptions on failure
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Init connection
$link = new mysqli("localhost", "root", "", "schedule");
$response = [];
// Prepare the statement and execute it
$stmt = $link->prepare("INSERT INTO attendance (name) VALUES (?)");
$stmt->bind_param("s", $_GET['query']);
$stmt->execute();
// Check the number of inserted rows
if ($stmt->affected_rows) {
$response['status'] = 1;
} else {
$response['status'] = 0;
}
// Close the statement and connection
$stmt->close();
$link->close();
echo json_encode($response);
Okay so I have an ajax function which sends data to register-process.php. I want the register-process.php to send the PHP value $msg back to ajax. I tried using $('.message').html("<?php $msg; ?>").fadeIn(500); on success but it does not seems to work. Is there any way to do it?
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var cpass = $("#cpass").val();
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val(),
cpass: $("#cpass").val()
};
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
$('.message').html("<?php $msg; ?>").fadeIn(500);
}
});
return false;
});
});
</script>
register-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
$cpass = (!empty($_POST['cpass']))?$_POST['cpass']:null;
$email = (!empty($_POST['email']))?$_POST['email']:null;
if($_POST){
$stmt = "SELECT COUNT(*) FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> execute();
$checkunm = $stmt->fetchColumn();
$stmt = "SELECT COUNT(*) FROM members WHERE mem_email = :email";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':email', $email);
$stmt->execute();
$checkeml = $stmt->fetchColumn();
if($uname == '' or $pass == '' or $cpass == '' or $email == ''){
$msg = "<div class='message-error'>Fields cannot be left empty. Please fill up all the fields.</div>";
}else if($checkunm > 0){
$msg = "<div class='message-error'>This username is already registered. Please use a different username.</div>";
}else if($checkeml > 0){
$msg = "<div class='message-error'>This Email ID is already registered. Please use a different Email ID.</div>";
}else if($pass != $cpass){
$msg = "<div class='message-error'>Passwords are not matching.</div>";
}else if(strlen($uname) > 12){
$msg = "<div class='message-error'>Username should not be more than 12 characters long.</div>";
}else if(strlen($uname) < 6){
$msg = "<div class='message-error'>Username must be at least 6 characters long.</div>";
}else if(strlen($pass) < 6){
$msg = "<div class='message-error'>Password must be at least 6 characters long.</div>";
}else{
// If everything is ok, insert user into the database
$stmt = "INSERT INTO members(mem_uname, mem_pass, mem_email)VALUES(:uname, :pass, :email)";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> bindValue(':pass', password_hash($pass, PASSWORD_BCRYPT));
$stmt-> bindValue(':email', $email);
$stmt-> execute();
if($meq){
$msg = "<div class='message-success'>Congratulations! You have been registered successfully. You can now login!</div>";
}else{
$msg = "<div class='message-error'>Server Error! Please try again later. If problem persists, please contact support.</div>";
}
}
}
echo $msg;
?>
In your Ajax function no need to echo the php variable.Just map response to your html element like below:
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
console.log(html);//see output on browser console
$('.message').html(html).fadeIn(500);
}
});
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.
Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");