php variable through jquery ajax to external php - php

i found a php/jquery/ajax script that has a textfield that is sent after the user clicks the input to an external php script to be written into a mysql database.
http://gazpo.com/2011/09/contenteditable/
whats missing is the userid passed into the external php file:
$sql = "UPDATE customer SET comment = '$content' WHERE userid = 12345 ";
here is what i do:
i am catching the user id in the main file with:
$s = $_GET['contact'];
from the url parameter.
then i put it in to my db select in the main php:
$sql = "select customer from user where userid = $s";
then there are some div
<div id="content">
<div id="editable" contentEditable="true">
followed by the ajax script:
$(document).ready(function() {
$("#save").click(function (e) {
var content = $('#editable').html();
var content_two = $('#editable_two').html();
$.ajax({
url: 'save2.php',
type: 'POST',
data: {
content: content
},
in the save.php there is this:
$content = $_POST['content']; //get posted data
$sql = "UPDATE customer SET comment = '$content' WHERE userid = "XXXX" ";
So: how do i get the $s variable from my url parameter into the "XXXX"

As others pointed out in comments that seem to be quitly ignored , you really need to check this out, since the way you build your query is very insecure. Please read about SQL injection.

Add userid to the data you pass from your ajax call back to save.php.
data: {
content: content,
userid: <?= $s ?>
}
This is a guess without seeing the rest of your code and how the code actually renders the page.

Thanx alot for the hint.I changed theses lines:
In Ajax/Jquery section of the main php file:
$("#save").click(function (e) {
var content = $('#editable').html()
var nr = <?php echo $s; ?>;
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content,
nr: nr
}
And in the external save.php i added this:
$s = $_POST['nr'];
and also included the variable into $s into my sql update section:
$sql = "UPDATE ADRESSEN SET BEMERKUNG = '$content' WHERE NR = $s ";
This is for a telefonsoftware, when somebody calles me up the software is opening a webpage with the main.php and this variable is using the sql select to show the customer informations, then i write a commend into the editable field and it gets written back into my sql databbase.
So! If somebody is looking for a way to path a url command variable via $_get into a php and then into ajax bach into an external file, i hope he google finds this keywords and is showing this page to help him :)
here its in short:
www.url.com/?contact=12345
php catch url parameter:
$s = $_GET['contact'];
sql select:
$sql = "select user, userid from customer where userid = $s";
in AJAX/jquery ad:
var nr = <?php echo $s; ?>;
and later on
nr: nr
in external save php:
$content = $_POST['content']; //get posted data
and
$sql = "UPDATE customer SET comment = '$content' WHERE userid = $s ";

Related

Implement Ajax for a PHP Function

I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).

How to handle AJAX error if sql update fails?

I have a php file, which updates the SQL, if the "follow this user" button is clicked, and an AJAX calls this PHP file. The code below works, it follows the user! My problem is: If, for some reason the SQL update fails, I want the AJAX to drop an error message (e.g. an alert), but I really don't know how this could be possible. The AJAX doesn't know whether the update succeeded or not.
Here's my code:
PHP
if(!empty($_GET['a']) and $_GET['a']=='follow')
{
$id = sql_escape($conn,$_GET['id']);
$me = $user2[0];
//the user's id who clicks on the follow button
$query = sql_fetch(sql_query($conn, "select * FROM
forum where id='$id'"));
//check who created this forum, so we know who to follow
$follow_this_user = $query['user'];
//the user to follow
$now = date('Y-m-d H:i:s');
$already_follow_user = sql_fetch(sql_query($conn,
"SELECT * FROM follow WHERE user_id=".$me." AND
followed_user =".$follow_this_user." "));
//check if user already followed by this user
if(empty($already_follow_user[0])) {
//if not followed
sql_query($conn,"INSERT INTO follow
(user_id, followed_user, date) VALUES
('".$me."', '".$follow_this_user."', '".$now."');")
or die(mysqli_error($conn));
}
}
AJAX:
$(document.body).on('click', '.followable', function(){
//User clicks on the follow text, which has "followable" class
$.ajax({
//type: 'GET',
url : '/ajax/ajax_follow.php?a=follow&id=<?php print $topic[id]; ?>'
//the $topic['id'] is the id of the current topic, which
//I need to know who created this forum, to follow that user
//(as mentioned above in the php code)
});
I need data and error, but no idea how to get them working. I tried many things, but I just can't get the data.
Add this to your ajax request:
success: function(data) {
alert(data);
}
And simply echo something on your PHP page.
For example:
$result = mysql_query($sql);
echo $result;
If you want to recieve more data, JSON is your friend.

how to open html page using trigger

i am using database trigger
when database row updated i want to get real time notification like change happened now
suppose i am using message table in my database
suppose user inserted value in message table. i want change should be noted using
trigger at real time and then i want open an html page when row inserted in my
message table then html page should open or an alert box show notification
that"you received a new message".
Please help me to solve this problem
for example
CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DB AutoMailer',
#recipients = 'user#example.com',
#body = 'The DB has changed',
#subject = 'DB Change';
in above example mail is sending but i want to open html page i need syntax to open html page
Well below is a example of what you need exactly:
javascript
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "file.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
then php
$sql = "SELECT count(*) as count FROM i_case";
$qry = pg_query($connection, $sql);
$row = pg_fetch_assoc($qry);
echo $row['count'];

update table in mysql when user loses focus of a textarea?

I want users of my site to be able to update their profile information by clicking into a textarea. When they type in some text and click out of the text area (on blur), I want this to update a table in my database called 'bio'.
I have been working on this for several days, I'm ashamed to admit but I am really new to php and sql so I am learning as I go along. I have tried to make sense of a script but it's probably completely wrong. Can someone please advise me of what I need to do?
Here's my code:
<textarea id="bio" style="width: 456px;
margin-top:3px;
text-align:left;
margin-left:-2px;
height: 120px;
resize: none;
border: hidden;" textarea name="bio" data-id="bio">
<?php echo $profile['bio'] ?>
</textarea>
<script type="text/javascript">
$('textarea').on('blur',function () {
var bioVal = $(this).val(),
id = $(this).data('id');
$.ajax({
type: "POST",
url: "includes/changebio.php",
data: {bio:bioVal , id:id},
success: function(msg) {
$('#bio-' + id).val(msg);
}
})
});
</script>
Here's the url php file that should do the work:
function update_profilebio() {
global $connection;
global $profile_id;
$query = "UPDATE ptb_profiles
SET bio=''
WHERE ptb_profiles.user_id = \"$profile_id\"
AND ptb_profiles.user_id = ptb_users.id";
$update_profilebio_set = mysql_query($query, $connection);
confirm_query($update_profilebio_set);
return $update_profilebio_set;
}
I checked HTML+JavaScript code and AJAX POST request is sending data correctly to the PHP script (You may check this in Chrome Developer Tools or with Firebug add-on).
This changebio.php script has only definition of this update_profilebio() function ? Definition alone won't execute this function, you need to call it.
<?php
update_profilebio(); // tells php to call the function, defined below
function update_profilebio() {
global $connection;
global $profile_id;
$query = "UPDATE ptb_profiles
SET bio=''
WHERE ptb_profiles.user_id = \"$profile_id\"
AND ptb_profiles.user_id = ptb_users.id";
$update_profilebio_set = mysql_query($query, $connection);
confirm_query($update_profilebio_set);
return $update_profilebio_set;
}
?>
Also, SQL query has two conditions and I don't understand this part "...AND ptb_profiles.user_id = ptb_users.id ". You update only one column in one table, the only thing you need is user id which you provide in first where condition.
Your HTML + jQuery code looks ok, just cheng php output <?php echo $profile['bio'] ?> by adding htmlspecialchars, that will help you avoid some trouble
<?php echo htmlspecialchars($profile['bio']); ?>
The thing that fails in your code is SQL query; you are setting bio to empty text. Also you have condition on matching user_id with other table id, but you have not joined this table in your query. Just requiring user_id to be equal to given integer is enough. Also remember to escape user input properly, to prevent them from injecting malicious code into your database.
SQL should look like this:
$bio = mysql_real_escape_string($_POST['bio']);
$query = "
UPDATE
ptb_profiles
SET
bio='{$bio}'
WHERE
ptb_profiles.user_id = " . intval($profile_id);
You got your quoting wrong, try something like this
$query = "UPDATE ptb_profiles SET bio='".$_REQUEST['bio']."'
WHERE ptb_profiles.user_id = ".$profile_id;
SQL usually uses single quotes, PHP uses both.

Need to pass value of php in jquery script

I need to pass the PHP retrieved value from database to Ajax function for further querying in database my code is given below.
The PHP Script:
$query = mysql_query("SELECT * FROM employee") or die(mysql_error());
while($res=mysql_fetch_assoc($query)){
echo $res['emp_id'];
$emp_id=$res['emp_id']
and submit button with id name-submit
The Javascript
$('input#name-submit').on('click',function(){
var empid = $('php echo $emp_id; ');
alert(empid);
the script is running just below the php script.
Exactly as you are doing, but by putting the full opening tag in there. Change the second JS line to:
var empid = $('<?php echo $emp_id; ?>');

Categories