I've checked for duplicates and none of them are strictly related to this problem.
I have the following javascript code
var value = $.ajax({
type: "POST",
url: "bank.php",
data: {sum:money},
cache: false,
async: true
}).done(function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
and php in bank.php
if(isset($_POST['sum']))
{
$money = mysql_real_escape_string($_POST['sum']);
$query = "UPDATE banks SET currency = 1 WHERE amount = '.$money.'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
I receive in the browser console "success" for the ajax operation but nothing happens in the database. Take note that "currency" is a tinyint(1) and amount is an int(10) [I'm using sql tables as you might have guessed]. What am I doing wrong? (bank.php also includes the header to link to my database, so that's not the problem because I tested others queries there).
I believe the code isn't going through the if(isset($_POST['sum'])) validation but don't understand why. Any suggestions?
Try this :
$query = "UPDATE banks SET currency = 1 WHERE amount = ".$money.";
Hope this help u.
Related
I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?
Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)
I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work
I am newbie to php and mysql. Using Cordova plugin for visual studio 2015 i have created a simple mobile application in which a user selects a serial number and on selecting it data is showed on the chart. Also there is a toggle switch button through which i can change the state of the switch from on-off or off-on. While changing the state the data is inserted into DB.
Now, i want is to do is that whenever i select a serial number the last state of the toggle should be shown on the switch. Means if the user has previously change the state from on to off for a particular serial number than this change should be shown if the same serial number is selected again.
For this i have done the following
My PHP CODE
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = isset($_REQUEST['Command_Name'])?$_REQUEST['Command_Name']:"";
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
//print_r($result);
echo json_encode( (array) $result->fetch_object());
mysqli_close($con);
echo $cmd_Name;
My html(ajax) code
$.ajax({
method: "GET",
url: "http://localhost:Port/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = $.parseJSON(JSON.stringify(data));
console.log(dt);
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
} else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function () {
toastr.success('Data not fetched', '', { timeOut: 2000 })
}
});
Now whenever i run the app this part of code executes and it always goes to the else part. i.e if my serial number's last state is On it shows me off as shown in the below image
In above image you can clearly see that the command_Name = on but still it goes to else part.
I must be doing something wrong, and that i don't know.
Any help would be highly appreciated.
I am loading boolean data from mySql. the db is 0 or 1. However JSON wants true or false for a form to load properly. I have 30 fields in the actual table. And yes I can convert the 0 1 to true false in the select using a case statement. But there must be an easier way to do this?
I have lots of boolean fields in the actual production. Maybe JSON doesn't handle this and only handles plain type="text"?
Otherwise I can load it all with PHP and set the values on load
Here is the original JSON
[{"drscomplete":"0"}]
and this is what I need for the checkbox to work properly on a form
[{"drscomplete":"true"}]
Here is the load php
$SQL ="SELECT * from dealfinalize d where d.ID=" . $id;
$resultArray = array();
$result = mysqli_query($con,$SQL);
if($result->num_rows >0 )
$resultArray = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($resultArray);
and here is the ajax
jQuery.ajax({
url: "dealfinalizeload.php",
data:'id='+id,
type: "POST",
success:function(data){
var data2 = $.parseJSON(data);
$('div#white_content_dealfinalize').loadJSON(data2);
alert(data);
},
error:function (){
alert("Error loading tasks");
}
});
You can use case
select t1.column1,
case when t2.column == 1
then 'true'
else 'false'
end OrderedAll
from yourtable t1
I recently posted a question about deleting multiple rows in the database and basically re-used the code to update multiple rows in the database, but now I am having issue once the database has been updated and the page refreshes it keeps loggin me out an I'm not sure why.
Here is the ajax:
function editUser(){
var url = 'edit-user.php';
var ids = document.getElementById("edit-user-id").value;
var role = document.getElementById("role").value;
var status = document.getElementById("accountStatus").value;
var data = 'userID=' + ids.toString() + '&role=' + role + '&status=' + status;
$.ajax({
url: url,
data: data,
cache: false,
error: function(e){
alert(e);
},
success: function () {
var selects = $('#users-table').bootstrapTable('getSelections');
ids = $.map(selects, function (row) {
return row.id;
});
$('#users-table').bootstrapTable('refresh', {
silent: true
});
location.reload();
}
});
}
And here is the PHP:
require("../config.php");
try{
$role = $_GET['role'];
$status = $_GET['status'];
$ids = array($_GET['userID']);
$inQuery = implode(',', $ids);
$query = 'UPDATE users SET role = :role, account_status = :status WHERE user_id IN ('.$inQuery.')';
$query_params = array(
':role' => $role,
':status' => $status
);
$stmt = $db->prepare($query);
$stmt->execute($query_params);
// Set variable message of affected rows
$count = $stmt->rowCount();
$user_updated = ''.$count.' user(s) updated successfully.';
$_SESSION['user_updated'] = $user_updated;
} catch (Exception $e){
$error = '<strong>The following error occured:</strong>'.$e->getMessage();
$_SESSION['error'] = $error;
}
I tried changing cache: true, but that didn't work. Again, I do not want to be logged out. Any ideas what I am doing wrong?
EDIT: I have narrowed it down to only happen when the page refreshes. I removed this piece of code location.reload(); from the ajax call and it does not redirect me back to the login page, but if i hit F5 or click refresh it logs me out.
This is too long for a comment:
Nothing is jumping out at me that would cause you to lose what is set in the $_SESSION['user']. Try dumping $_SESSION on each page just to keep track of it and disable the redirect for now (just put an error message or something). You can dump the array like so:
print_r($_SESSION);
Do you also know your prepared statement is broken? I don't see the point of the array or the implode for $ids and $inQuery. It should be something like:
$stmt = $db->prepare(
'UPDATE users
SET role = ?, account_status = ?
WHERE user_id = ?'
);
$stmt->execute(array($_GET['role'], $_GET['status'], $_GET['userID']));
There is no point in using IN if you only have one entry. You also aren't protecting your query from anything because you are still inserting the values into the prepare statement.
It appears that I needed to move session_start() to the top of the config.php file to make sure that it is the very first thing called on the page. Everything seems to be working ok right now.
I have a plugin that uses a click to edit AJAX POST request, I have the script all made up, but when I went to go test it, it never changed my database values that I was trying to modify, so I changed the URL you set to a function to report the request into my google console, it returns the following,
Object {name: "", value: "derp#derpp.com", pk: 23}
Here is the PHP script I am trying to AJAX to,
<? $query = "
UPDATE users SET email = '".$_POST['value']."' WHERE id = '".$_POST['pk']."'
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
?>
My overall issue, is that the content is not being changed by the AJAX, I tested the script manually and everything works.
EDIT
I am not manually doing an AJAX request, its being used off of a plugin, called X-Editable The Documentation can be found here
did you checked the data which you are sending is actually inside post request. I would check if i am using a proper jquery post request such as
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
just sending post data doesn't helps. Moreover if you are not passing any dummy value such as javascript.getTime function its a good idea to use it coz sometime the xmlhttp object doesn't recognises as new query.
Therefore your url should be "url:'dummy='+dt.getTime()+'&var1='+$textbox1.val()"
hope this helps you.
post data type must be application/x-www-urlencoded , if use $_POST function in php .
HTTP /yourURI HTTP/1.0
Content-Length:xxx
Content-Type:application/x-www-urlencoded
Connection:clsoe
name=&value=derp%40derpp.com&pk=23
can't post object to Server,as body...
HTTP /yourURI HTTP/1.0
Content-Length:xxx
Content-Type:application/json
Connection:clsoe
{name: "", value: "derp#derpp.com", pk: 23}
revised query... If you have an integer based value, it can't be quoted;
$query = "UPDATE users SET email = '".$_POST['value']."' WHERE id = ".$_POST['pk'];
or using string replacement
$query = "UPDATE users SET email = '{$_POST['value']}' WHERE id = {$_POST['pk']}";