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'];
Related
I want to use the value of limit and offset into my PHP code but I can't.
Here is my code:
var maxData = 0;
var limitt=6;
var offsett=1;
$.ajax({
url: "../model/conn.php",
type: 'POST',
data: 'getData='+'&limit='+limitt+'&offset='+offsett,
}).done(function( data ) {
$("#d1 ").html(data);
while (limitt<maxData){
limitt= limitt+6;
offsett=offsett+6;
}
});
<?php
if(isset($_POST['getData'])) {
$serv = "localhost";
$user = "root";
$psrd = "";
$db = "nonc";
$conn = mysqli_connect($serv, $user, $psrd, $db);
$limit=$_POST['&limit'];
$offs=$_POST['&offset'];
$sql = "SELECT * FROM non_confor limit $offs, $limit;";
$resltt = mysqli_query($conn, $sql);
$checkk = mysqli_num_rows($resltt);
?>
When I run my PHP page they show me that I have errors on $limt and $offs, because they don't receuve the data from AJAX.
First thing, you are using POST method for form submission and passing data as a query string which is making an error. Correct that as below:
$.ajax({
url: "../model/conn.php",
type: 'POST',
data: {
'getData': 1, // passing 1 as you are using getData in php.
'offset': offsett,
'limit': limitt
},
}).done(function(data) {
$("#d1 ").html(data);
while (limitt<maxData){
limitt= limitt+6;
offsett=offsett+6;
}
});
After this, you need to make modification in your PHP code as below:
$limit=$_POST['limitt'];
$offs=$_POST['offsett'];
After this, your code should work fine. Hope it helps you.
This is a syntax problem , here is the correction :
$.ajax({
type: 'POST',
url: '../model/conn.php',
data: {
'getData':limit,
'offset':offsett
},
success: function(msg){
// rest of your code
}
});
Data attribute should have as value a json format
I have ajax call in my index page, when the user enter a username into the text box it's need to insert into a mysql db table,can't find a way to do it?
This is my code
$(document).ready(function () {
$('#enter_email_id').change(function () {
var str = $('#enter_email_id').val();
var webFormURL = "get_acc_info.php?q=" + str;
$.ajax({
url: webFormURL,
async: false,
success: function (response) {
$('.test_acc').html(response);
}
});
This is insert db php page
<?php
session_start();
$_SESSION["username"];
function insert_Details(){
include 'Db_Connection.php';
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES('$_SESSION[username]',".NOW().",'$_POST[searched_email]')";
}
?>
for security reasons you should use mysqli_real_escape_string() for input values.
I've got to fix your code, but you should replace $_SESSION["username"] value with what you want, use this code:
JavaScript:
$(document).ready(function () {
$('#enter_email_id').change(function () {
var str = $('#enter_email_id').val();
var webFormURL = "get_acc_info.php?q=" + str;
$.ajax({
type: 'post',
url: webFormURL,
async: false,
success: function (response) {
$('.test_acc').html(response);
}
});
PHP:
$_SESSION["username"] = 'test_username';
function insert_Details(){
//create mysqli connection
include 'Db_Connection.php';
$string = mysqli_real_escape_string($mysqli_link,$_POST[searched_email]);
$session = mysqli_real_escape_string($mysqli_link,$_SESSION[username]);
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES('$session',NOW(),'$string')";
if(mysqli_query($mysqli_link,$sql) ) {
echo "OK";
}
}
?>
I have a list of options (categories) of projects that the user can see. By selecting the categories, the div below should update with the lists of projects matching said categories.
Despite using the following answer, almost verbatim, Send array with Ajax to PHP script, I am still unable to retrieve any results, and yet no errors show up either.
The jquery:
// filter for projects
var $checkboxes = $("input:checkbox");
function getProjectFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
$checkboxes.on("change", function(){
var opts = getProjectFilterOptions();
//alert(opts);
var categories = JSON.stringify(opts);
$.ajax({
url: "/web/plugins/projcat.php",
type: "POST",
dataType: "json",
data: {data : categories},
cache: false,
success: function(data) {
$('#projects').html(data);
//alert(data);
}
});
});
the php (still in testing, so not filled out):
<?php
if(isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
print_r($data);
}
?>
Where is the error?
Try this:
JS
...
// dataType: "json", // remove that; you're not sending back JSON string
data: {categories : categories},
cache: false,
...
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
// .. process the $data
print_r($data);
return;
}
?>
Your desired array is in $_POST['data'] and not in $_POST['projcats']. Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'].
So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}
I have jQuery Ajax request that sends data to a PHP page that then insert a record into MySQL.
With my current setup, this all works fine.
However, as part of the PHP script, i use mysql_insert_id() to retreive the ID of the last record.
I need the Ajax Success function to return this ID value as a javascript variable.
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = array('LastID' => mysql_insert_id());
$LastID = json_encode($LastID);
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "json",
success: function(data) {
var LastID = data;
alert(LastID);
}
});
I've read of using PHP's json_encode to create a JSON object and then pass that back, but i've had no luck.
How can i return this value?
just use
echo $LastId;
to send a response.
If you pass only one value you dont need JSON:
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = mysql_insert_id();
echo $LastID;
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "text",
success: function(data) {
var LastID = data;
alert(LastID);
}
});
with JSON:
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$jsonArray= array('LastID' => mysql_insert_id()); //*1 value is named LastID
echo json_encode($jsonArray);
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "json",
success: function(data) {
var LastID = data["LastID"];//use the same name as above (*1)
alert(LastID);
}
});
Maybe it is because your LastID is in array so the resulting object would be a JS array.
If you just need the ID don't use JSON encode and just pass the ID in Javascript.
So in PHP:
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = mysql_insert_id();
echo $LastID;
}