Ajax database insert isnt working - javascript

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

Related

make a deactivate account with jquery, ajax and php prob

I am adding a deactivate feature on a website i am working on, so I added a form with a textarea to tell the reason why the user is deactivating his account and a button that become enabled when the textarea is filled out so I sent the call via jquery ajax to a php script which will update the users_table in the database to 1 for deactivated then must log the user out and redirect them to the index page of the website. So everything works fine except the log out it is not happening and no redirect. I need help with that please
here is my php script :
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
$user_id = (int)$_SESSION["user_id"];
if(isset($_POST['deactivate_reason'])) {
$deactivate_reason = mysql_prep($_POST['deactivate_reason']);
// INSERT into table
$query1 = "INSERT INTO deactivate_reason_table ( ";
$query1 .= "user_id, reason";
$query1 .= ") VALUES (";
$query1 .= " $user_id, '$deactivate_reason'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
$confirm_query1 = confirm_query($result1);
// if query1 is successful and replies deleted then we make the second query to delete the board comments
if ($confirm_query1 == 0) {
echo "error";
exit();
} else {
// UPDATE table
$query2 = "UPDATE users_table ";
$query2 .= "SET deactivated = 1";
$query2 .= "WHERE user_id = $user_id";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if ($confirm_query2 == 0) {
echo "error";
exit();
} else {
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
// redirect_to() is a custom function in the functions.php that redirects
redirect_to("../index.php");
}
}
}
and here is my jquery ajax script :
$(document).on("click", "#deactivate_button", function(e){
e.preventDefault();
var text = $("#deactivate_reason_textarea").val();
var url = "widgets/deactivate.php";
$.ajax({
url: url,
method: "POST",
data: {
deactivate_reason: text
},
beforeSend: function() {
CustomSending("Processing...");
},
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
}
});
});
To redirect the user for a another page in PHP you can use something like header('Location: ...') (manual), but you are calling the script in ajax, then you need to put the redirect in this, not in the called PHP script.
To redirect in JavaScript you can use window.location (tutorial).
window.location = "my/another/script.php";
In your case, you need to put it in the success of ajax.
$.ajax({
... # your occulted script
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
window.location = "another/script.php";
// or you can put it in a timeout to show a message for the user or other thing
// setTimeout(function() {
// window.location = "another/script.php";
// }, 10000);
}
});
ok guys thanks a lot for your help, I managed to solve this with your help
after i added widow.location = "insert.php" like tadeubarbosa suggested then i went to my index.php page and added these lines :
if (logged_in()) {
$email = $user_data['email'];
$id = $user_data['user_id'];
$edited = account_edited($email);
if ($edited == 0){
redirect_to("editprofile.php?id=$id");
}
$is_deactivated = is_deactivated($_SESSION['user_id']);
if ($is_deactivated == 1) {
$query = "UPDATE users_table SET online = 0 WHERE user_id = $id";
$result = mysqli_query($connection, $query);
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
redirect_to("index.php");
}
}
then went to the login.php script and added a query to update deactivated = 0 if the user logs in so the account reactivates

JSON/PHP/MYSQL login connection error

I'm new to PHP programming and I'm trying to test out a login page alongside JSON and MySQL. I managed to make most of it functional but I can't seem to find a way to make the query in which I verify the username and password to work.
Please help.
Here's the code:
login.js:
$(document).ready(function(){
$('#errorLogin').hide();
$('#formLogin').submit(function(e){
var username=$('#inputUser').val();
var password=$('#inputPassword').val();
$.ajax({
type:'get',
dataType: 'json',
url: 'dist/php/connection-login.php',
data: {
user: username,
pass: password
},
success: function(e){
console.log(e);
}
});
});
});
connection-login.php:
<?php
$con = new mysqli("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$result = mysqli_fetch_assoc($qry);
$row = mysqli_fetch_assoc($result);
if ($row != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
Your PHP should be more like:
connect.php - make sure this is a separate secure page
<?php
function db(){
return new mysqli('localhost', 'root', 'root', 'solucionar_manutencoes_db');
}
?>
I would change your JavaScript AJAX to a POST request, unless you have a reason for it.
connection-login.php
<?php
sesson_start(); include 'connect.php';
if(isset($_POST['user'], $_POST['pass'])){
$db = db(); $r = array();
$prep = $db->prepare('SELECT `lg_user` FROM login WHERE `lg_user`=? && lg_user=?');
$prep->bind_param('ss', $_POST['user'], $_POST['pass']); $prep->execute();
if($prep->num_rows){
$prep->bind_result($lg_user); $r['user'] = $lg_user;
$_SESSION['logged_in'] = $lg_user;
}
echo json_encode($r);
}
?
Now if your JavaScript AJAX result does not contain the a e.user then they are not logged in. Of course, you would probably want to store the original password as a SHA1 or stronger and use AES_ENCRYPTION or better for Personal Information, along with SSL.
I see several errors in your code. The first is that you are executing mysqli_fetch_assoc twice: once on the result, and then again on the array the first call returned. The next is that the $response variable was never declared. Here is the fixed PHP script:
<?php
$con = mysqli_connect("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$results = mysqli_fetch_assoc($qry);
$response = [];
if (count($results) != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
In your JavaScript make sure to use e.preventDefault() inside #formLogin's submit handler to prevent page reload when that form is submitted.

JQUERY & PHP POST - show 00 in console.log

I make this jquery to call a php file via post. I put a console.log to see the return of the Ajax. At moment return 00.
I'm not sure what it is the problem?
The code is:
$('input[type="submit"]').click(function(event){
event.preventDefault();
// Get the value of the input fields
var inputvalue = $(this).attr("value");
$.ajax({
url:"updateEstado2.php",
type:"POST",
data:{"codigo": inputvalue},
dataType:"text",
success:function(data){
console.log(data);
alert(inputvalue);
}
});
});
The PHP code:
<?php
session_start();
if(isset($_SESSION['username']) and $_SESSION['username'] != ''){
include("db_tools.php");
$conn = dbConnect("localhost", "5432", "dbname", "dbuser", "dbpass");
$estado = $_POST["estado"];
$codigo = $_POST["codigo"];
$query = "UPDATE produccion.ma_producto SET estado={$estado} WHERE codigo={$codigo}";
$result = pg_query($conn, $query);
if ($result == TRUE) {
header('Location: produccio.php');
} else {
echo "Error updating record: " . pg_last_error($conn);
}
pg_close($conn);
} else{
?><p>La sessió no està activa, si us plau ingresa aquí</p>
The alert window show the value of the variable correctly but the console.log show 0. I do not understand well...
Please Could you help me.
Please edit statement after if condition.
if ($result == TRUE) {
echo 'Done';
} else {
echo "Error updating record: " . pg_last_error($conn);
}

ajax function not working fine

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.

ajax cannot pass datastring to php

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.

Categories

Resources