MySQL table not updating at all with JSON - php

I'm working on a CRUD project. All of my other functions are working except update. I have included a catch to see if there are any errors in the SQL statement and it doesn't catch anything. When I press save changes, the code is executed but doesn't reflect any changes in my table. I have checked all of the error logs also and nothing is apparent. Any ideas? (I had to remove the details from the fields as they contain identifiable information).
function edit(rowID) {
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'json',
data: {
key: 'getRowData',
rowID: rowID
}, success: function (response) {
$("#editRowID").val(response.rowID);
$("#fullName").val(response.fullName);
$("#dob").val(response.dob);
$("#ethnicity").val(response.ethnicity);
$("#gender").val(response.gender);
$("#nhsNo").val(response.nhsNo);
$("#hospNo").val(response.hospNo);
$("#idMarks").val(response.idMarks);
$("#address").val(response.address);
$("#tableManager").modal('show');
$("#manageBtn").attr('value', 'Save Changes').attr('onclick', "manageData('updateRow')");
}
});
}
function manageData(key) {
var fullName = $("#fullName");
var dob = $("#dob");
var ethnicity = $("#ethnicity");
var gender = $("#gender");
var nhsNo = $("#nhsNo");
var hospNo = $("#hospNo");
var idMarks = $("#idMarks");
var address = $("#address");
var editRowID = $("#editRowID");
if (isNotEmpty(fullName) && isNotEmpty(dob) && isNotEmpty(ethnicity) && isNotEmpty(gender) && isNotEmpty(nhsNo) && isNotEmpty(hospNo) && isNotEmpty(idMarks) && isNotEmpty(address)){
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'text',
data: {
key: key,
fullName: fullName.val(),
dob: dob.val(),
ethnicity: ethnicity.val(),
gender: gender.val(),
nhsNo: nhsNo.val(),
hospNo: hospNo.val(),
idMarks: idMarks.val(),
address: address.val(),
rowID: editRowID.val()
}, success: function (response) {
alert(response);
}
});
}
}
$fullName = $conn->real_escape_string($_POST['fullName']);
$dob = $conn->real_escape_string($_POST['dob']);
$ethnicity = $conn->real_escape_string($_POST['ethnicity']);
$gender = $conn->real_escape_string($_POST['gender']);
$nhsNo = $conn->real_escape_string($_POST['nhsNo']);
$hospNo = $conn->real_escape_string($_POST['hospNo']);
$idMarks = $conn->real_escape_string($_POST['idMarks']);
$address = $conn->real_escape_string($_POST['address']);
$rowID = $conn->real_escape_string($_POST['rowID']);
if ($_POST['key'] == 'updateRow') {
$conn->query("UPDATE suspects SET fullName='$fullName', dob='$dob', ethnicity='$ethnicity', gender='$gender', nhsNo='$nhsNo', hospNo='$hospNo', idMarks='$idMarks', address='$address' WHERE id= '$rowID'");
exit('Record for '.$fullName.' updated.');
}

Related

405 (Method Not Allowed) (POST) method with ajax jQuery

im trying to send some data through ajax jQuery to a php file with POST but i keep getting POST 405 Method Not Allowed error, any ideas to solve this issue will be appreciated, heres the function that makes the call
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://127.0.0.1:5500/ajax.php',
method: 'POST',
dataType: 'text',
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}
and here is the ajax.php file code
<?php
if (isset($_POST['key'])) {
$conn = new mysqli(host:'localhost', username:'root', passwd:'root',
dbname:'mysqldatamanager');
$name = $conn->real_escape_string($_POST['name']);
$abbrev = $conn->real_escape_string($_POST['abbrev']);
$desc = $conn->real_escape_string($_POST['desc']);
if($_POST['key'] == 'addNew') {
$sql = $conn->query(query:"SELECT id FROM country WHERE
countryName = '$name'");
if ($sql->num_rows > 0) {
exit("Country already exists!");
} else {
$conn->query("INSERT INTO country (countryName,
countryAbbrev, countryDesc) VALUES ('$name', '$abbrev',
'$desc')");
exit("Country has been added succesfully!");
}
}
}
?>
Please try below code.
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://localhost/ajax.php',
type: "POST",
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}

jQuery gathering inputs without submit

I'm trying to get values from inputs without any action from user and then save it via php to txt file.
This is what I got so far:
var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {
$('#display').append(email)
$.ajax({
type: "POST",
url: 'inputs-saving.php',
data: ({usremail:email}),
success: function(data) {
}
});
}
var newemail = $("#test").val();
}, 1000);
it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.
I have also tried to add something like "var newemail = email", but can't make it work corectly.
You can do like this
$('#test').on('change',function () {
var email= $(this).val();
if(email != '') {
$('#display').append(email);
$.ajax({
type: "POST",
url: 'inputs-saving.php',
data: ({usremail:email}),
success: function(data) {
}
});
}
});
Here test is the email filed id.
I thing it will help you.
$("input").blur(function(){
//place your logic
});
blur will not trigger every time you change the text, only when you remove focus from that box
There is variable scope problem , Try this:
var newemail = '';
var x = setInterval(function() {
var email = $("#test").val();
if (email != '' && email != newemail) {
$('#display').append(email)
$.ajax({
type: "POST",
url: 'inputs-saving.php',
data: ({
usremail: email
}),
success: function(data) {
currentemail = email;
}
});
}
}, 1000);

PHP Ajax file upload not working

Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.
function save()
{
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append('files',files[i],files[i].name);
}
var datastring = $("#businessform").serializeArray();
$.each(datastring,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
Here's the PHP
$success = 0;
$logo = "";
$logo_error = 0;
$sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
$fields = array(
':bname'=>$_POST['businessname'],
':phone'=>$_POST['businessphone'],
':email'=>$_POST['businessemail'],
':id'=>$_POST['vendorid']
);
$q=$con->update_query($sql,$fields);
if($q)
{
//save logo
$businessid = $con->lastID;
if(!empty($_FILES['files']['tmp_name']))
{
$ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
{
$logo = "logo".$businessid;
move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
}
else
{
$logo_error = 1;
}
}
$success = 1;
}
echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));
The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.
Thank you so much.
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);
function save()
{
var datastring = FormData($("#businessform")[0]);
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}

Simple ajax function in cakephp 2.x not working

I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}

jQuery autosave running success function, but not updating MySQL

My jQuery autosave is running the success function, but not updating the MySQL database. What am I doing incorrectly?
jQuery:
function autosave() {
var t = setTimeout("autosave()", 5000);
var translation = $("#doc-translation").val();
if (translation.length > 0) {
$.ajax({
type: "POST",
url: "update-draft-submission.php",
data: translation,
cache: false,
success: function() {
$(".autosaved").empty().append("saved");
}
});
}
}
PHP:
<?php
session_start();
//retrieve our data
$iddoc = $_GET['iddoc'];
$trans = translation;
$transowner = $_SESSION['userid'];
$true = 1;
include "../dbconnect.php";
$query = "UPDATE translations
SET trans='$trans'
WHERE iddoc='$iddoc'
AND transowner='$transowner'";
mysqli_query($query);
mysqli_close();
echo "Saved";
?>
You are not fetching the data in your PHP correctly:
$iddoc = $_GET['iddoc'];
$trans = translation;
iddoc is not passed as a GET parameter anywhere
"translation" is not a variable (neither do I think it is a constant)
Your SQL will break if it does not get the required values in the query.
Update your javascript so:
$.ajax(
{
type: "POST",
url: "update-draft-submission.php",
data: data: {translation:translation,iddoc:"XXX"},
cache: false,
success: function()
{
$(".autosaved").empty().append("saved");
}
});
Replace XXX with your iddoc value.
Then in PHP fetch them as:
$iddoc = $_POST['iddoc'];
$trans = $_POST['translation'];

Categories