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);
}
Related
I am trying to get pre set session variables through ajax and display in my modal. its like a cart. But when i try to get them there is no result at all when i read the ajax result from chrome inspect network or the modal. below is my code. what am i doing wrong here?
<script>
$("#cart-button").click(function(){
$.ajax({
url: "includes/cart-read.php",
success: function(data){
console.log(data);
alert(data);
$('#modal-body').empty().append(''+data+'');
}
});
});
</script>
and in cart-read.php
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
$msg = $dice;
echo json_encode($msg);
}
}
session dices is an array with simple numbers. such as 4, 5, 6.
Make sure you have the following things in your code
Check if you have added session_start(); below after
Try putting an else case to your session check,
Try using an array to store and display the results.
<?php
session_start();
$result = array();
$msg = array();
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
array_push($msg,$dice);
}
if(sizeof($msg) > 0)
{
$result['status'] = true;
$result['message'] = $msg;
}
else
{
$result['status'] = false;
$result['message'] = 'No values';
}
}
else
{
$result['status'] = false;
$result['message'] = 'Session not set';
}
echo json_encode($result);
?>
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 can't get the code to work and redirect to 2 different pages depending if the information is correct or not...
So far I have this on my login page:
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'newfile.php',
data: $('#form').serialize(),
success: function (response){
alert(response);
if (success.text="Username or Password incorrect")
window.location.href = "index.php";
else if (success.text="login successful") {
window.location.href = "login_success.html";
} else {
}
}
})
})
and the information Im reading from is (from another page):
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
echo "login successful";
} else {
echo "Username or Password incorrect";
}
$conn->close();
?>
I hope this will work for you try this:
if (response=="usernames or Password incorrect") {
window.location.href = "index.php";
}
else if (response=="login successful")
{
window.location.href = "login_success.html";
}
else { }
Use this code in ajax success. Actually you are using simple ECHO in PHP and using response.text in ajax success.
UPDATE:
you are using = sign for comparing it should be == operator for compare.
UPDATE 2:
i suggest to use status as true false not long string in php like:
if ($result->num_rows >0) {
echo true;
} else {
echo false;
}
Than in ajax response:
if(response == true){
// Success url
}
else {
// failure url
}
The variable success will be undefined inside the success callback function. So the next line will not be executed. So the page will not be redirected. According to your php code , you need to check if response is equal to the corresponding result of not.
I am trying to write an insert query with jquery, ajax and php. The record is getting inserted but returns a status error. First I tried to echo the message in php as it didn't work I tried it with print json_encode but both returned the status as error. Why doesn't it return the responseText?
{readyState: 0, responseText: "", status: 0, statusText: "error"}
This is the addmember.php file
<?php
require '../database.php';
function random_password( $length = 8 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&*()_-=+;:,.?";
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
$password = random_password(8);
//$regno=$_POST['regNo'];
$adminno=$_POST['adminNo'];
$batch=$_POST['batchText'];
$type=$_POST["memberType"];
$initials=$_POST["initialName"];
$fullname=$_POST["fullName"];
$address=$_POST["address"];
$telephone=$_POST["contact"];
$email=$_POST["email"];
$nic=$_POST["nic"];
$dob=$_POST["birthDate"];
$priv=$_POST["memberType"];
$userid="";
$sql="select username from memberinfo where username='$adminno'";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result)==0){
$sql="insert into memberinfo(username,nic_no,class,name_initial,full_name,address,telephone,email,date_of_birth) VALUES ('$adminno','$nic','$batch','$initials', '$fullname', '$address', '$telephone','$email','$dob')";
$result1=mysqli_query($con,$sql);
$sql = "select * from memberinfo where username='$adminno'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$userid = $row['user_id'];
}
}
$sql="insert into userlogin(user_id,username,privilege,password) VALUES ('$userid','$adminno','$priv','$password')";
$result2=mysqli_query($con,$sql);
if ($result1 && $result2) {
$message = "<p>New record created successfully</p>";
} else {
$message = "<p>Error: " . $sql . "<br>" . $con->error.".</p>";
}
} else{
$message = "<p>Admission no already exists.</p>";
}
print json_encode($message);
$con->close()
?>
This is the .js file with the ajax function
$(document).ready(function(){
$('#addmember').click(function(){
console.log("addmember");
var adminno=$("#adminNo").val();
var nic=$("#nic").val();
var batch=$("#batchText").val();
var initials=$("#initialName").val();
var fullname=$("#fullName").val();
var address=$("#address").val();
var telephone=$("#contact").val();
var email=$("#email").val();
var dob=$("#birthDate").val();
var priv=$("#memberType").val();
//$("#result").html("<img alt='ajax search' src='ajax-loader.gif'/>");
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
dataType: "json",
data:{'adminNo':adminno, 'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response);
},
error:function(response){
console.log(response);
}
});
});
});
Status zero normally means the page is navigating away. Stop it from happening.
$('#addmember').click(function(evt){ //<--add the evt
evt.preventDefault(); //cancel the click
You are not returning valid JSON from the server. You're json encoding a string, but valid JSON requires an object, or array to encapsulate the day coming back.
So at the very least:
echo json_encode(array($message));
No need for the JSON response. Simply return the message from your PHP script as shown below (note the use of echo and the semicolon following close()):
PHP
$con->close();
echo $message;
Also, remove the JSON filetype from your AJAX call and instead append response.responseText rather than response:
JS
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
data:{'adminNo':adminno,'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response.responseText);
},
error:function(response){
console.log(response);
}
});
Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.