communicate javascript with php script - javascript

I am trying to send data from Javascript to a php script. I am new to PHP,javascript and JSON etc. I am tryin to use jQuery Upvote plugin. I am reading the documentation from readme.md here. However, I find it too vague for my understanding.
I have added the following code in HTML body. The plugin is working fine in front-end.
<div id="topic" class="upvote">
<a class="upvote"></a>
<span class="count">0</span>
<a class="downvote"></a>
<a class="star"></a>
</div>
<div id="output"> </div>
<script language="javascript">
var callback = function(data) {
$.ajax({
url: '/vote',
type: 'post',
data: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred }
});
};
$('#topic').upvote({id: 123, callback: callback});
</script>
Can someone please tell how should I write the php counterpart so as to get the information about change of state of plugin? I think it is related to json maybe but I am stuck here..
EDIT: As per the suggestion, I have modified a bit of code and wrote PHP script.
In above code I have changed URL to my PHP script url: 'voter.php'.
This is the PHP code (in brief) :
<?php require_once('Connections/conn.php'); ?>
mysql_select_db($database_conn, $conn);
if ($_POST['up']!=0){
$query_categories = "UPDATE user SET score=1 WHERE u_id =5";
$categories = mysql_query($query_categories, $conn) or die(mysql_error());
}
else if ($_POST['down']!=0) {
$query_categories = "UPDATE user SET score=-1 WHERE u_id =5";
$categories = mysql_query($query_categories, $conn) or die(mysql_error());
}
The database connection is working fine, but still the database values are not updated by above code..

Your script sends AJAX Post request to the php script. You can access those post variables like this, using $_POST[] array:
$id = $_POST['id'];
$up = $_POST['up'];
$down = $_POST['down'];
$star = $_POST['star'];
Then you can populate the mysql table, etc.

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

working with ajax, mysql and php

I have to transfer data from one div to another, I am using AJAX to do this.
<script type="text/javascript" src="lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aq").click(function(){
var name1 = $("#n1").val();
$.ajax({
type: "POST",
url: "risultato.php"
data: "name1=" + name1 ,
dataType: "html",
success: function(msg)
{
$("#risultato1").html(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
});
});
</script>';
<form name="modulo1'.$dationennx['id'].'">
<input type="hidden" name="name1" value="'.$dati['id'].'"
id="n1'.$dationennx['id'].'">
<a href="javascript:rispondithread(\'homeq\');"
id="aq">'.stripslashes($dationennx['oggetto']).'</a><br>
</form>
<script>
function rispondithread(h) {
$("#rispondithreadforum").attr("style", "display:block;");
}
</script>`
I am fetching the data from my table from the 'risultato.php' page, which i want to use to show a textarea on my main page with the fetched data.
<?php
$nome = $_POST['name1'];
$query = "SELECT * FROM login2.podcast
WHERE login2.podcast.id = '$nome'
ORDER BY login2.podcast.data DESC";
$dati = mysql_query($query);
while($ris = mysql_fetch_array($dati) ){
echo'
<textarea class="form-control textareaabc" readonly tabindex="8">'.stripslashes($ris['testo']).'</textarea>';
}
?>
It doesn't work if i try to fetch the data using mysql_query, but it does when i try echoing the post data in the page.
$nome = $_POST['name1'];
echo $nome
This writes the '$nome' variable in my main page.
$nome = $_POST['name1'];
echo'<input type="text" value="'.$nome.'" name="nome">';
i don't understand this. why it doesn't work? what's wrong?
It is highly likely that there is no data for the '$nome' variable in your table
Make sure that you are actually receiving data from the database, does it print out the textarea? If not, you do not have any id in your podcast table table matching the '$nome' variable.
Testing your code
Try checking if you actually get anything back when you print something out in that page, could you possibly be pointing to the wrong page?
other
Overall, i would recommend using PDO or atleast mysqli, MySQL is no longer supported since PHP 7 and deprecated since PHP 5. See: PHP.net documentation about mysql extension
sorry, i forget to include the connection to the database into the file risultato.php :P
thanks to everybody

Trying to print onto an html page via PHP

I'm making a custom WYSIWYG editor with a save function, and through the save function I have run some code to get everything within a certain div, save it into a data table or overwrite it. But right now, I'm trying to load the page back.
The process is as follows: you press the save button, and it runs a PHP script called save.php, which is seen below.
My issue is that I want it to load or echo the contents within a certain div on the original html page. How would I go about doing that? I need it to work like Javascript's innerHTML function, basically.
Below are the files I use, at least the relevant parts.
test.html:
<form method="post" name="blog-post" id="blog-post">
<input type="hidden" name="postID" value="1"><!--Get the post's id-->
<div class="blog-editor-bar">
<a href="#" data-command='save'
onclick="submitForm('save.php');">
<i class='fa fa-save'></i>
</a>
</div>
<div id="blog-textarea" contenteditable>
</div>
<textarea style="display:none;" id="blog-post-cont" name="post-content"></textarea>
</form>
test.js:
function submitForm(action){
var theForm = document.getElementById("blog-post");
theForm.elements("post-content").value = document.getElementById("blog-textarea").innerHTML;
theForm.action = action;
theForm.submit();
}
save.php:
$conn = mysqli_connect('localhost', 'root', '', '');
if (mysqli_connect_errno()){
echo "<p>Connection Failed:".mysqli_connect_error()."</p>\n";
}
//store stuff in database
//Get Variables
$postid = $_POST['postID'] ? $_POST['postID'] : null;
$post = $_POST['post-content'] ? $_POST['post-content'] : null;
//if exists, overwrite
if($postid != null || $postid != ""){
$sqlSave = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rSave = mysqli_query($conn, $sqlSave) or die(mysqli_error($conn));
if(mysqli_num_rows($rSave)){
$sqlOverwrite = "INSERT INTO wysiwyg.post(post) VALUES(?) WHERE idpost = ?";
$stmt = mysqli_prepare($conn, $sqlOverwrite);
mysqli_stmt_bind_param($stmt, "sd", $post, $postid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
newSave();
}
loadSave();
}
function newSave(){
$sqlNewSave = "INSERT INTO wysiwyg.post(post) VALUES(?)";
$stmt = mysqli_prepare($conn, $sqlNewSave);
mysqli_stmt_bind_param($stmt, "s", $post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
function loadSave(){
$sqlLoad = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rLoad = mysqli_query($conn, $sqlLoad) or die(mysqli_error($conn));
//This is the part I'm stuck on
}
Thank you all in advance for helping me out! I've been stuck on it for at least a few hours!
EDIT: Before people comment on SQL Injections, I have taken it into consideration. This is me getting the code working on my localhost before I run it through a ton of anti-sql injection methods that I have already done in the past. The code i provide is only important to the functionality at this point.
EDIT #2: The anti-injection code already exists. I guess i seem to have forgotten to provide that information. I repeat, the code I have provided here is only code relating to functionality. I have escaped the strings, trimmed, etc. and more, but that code is not necessary to provide for people to get an understanding of what it is i am trying to do.
You can use an AJAX request to communicate with the server, send data and receive a response. There are many good tutorials out there, but since I first learned it in W3Schools website I am going to refer you there.
JavaScript tutorial.
jQuery tutorial.
You can use an AJAX request which is written like this:
<script>
$(document).ready(function(){
$.ajax({ //start an AJAX call
type: 'GET', //Action: GET or POST
data: {VariableName: 'GETvalue'}, //Separate each line with a comma
url: 'Destination.php', //save.php in your case
success: function(data)){ //if values send do this
//do whatever
}
}); //end ajax request
});
</script>
This allows you to send information to your php page without refreshing
So in my example you can do this on the PHP side
<?php
echo $_GET['VariableName'];
?>
Will echo out "GETvalue as specified in the data section of the Ajax call"
EDIT************
In the AJAX call you can add dataType if you want json
$.ajax({
type: 'GET',
data: {VariableName: 'GETvalue'},
dataType: 'json' // Allows Json values or you can change it to whatever you want
url: 'Destination.php',

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

How can I send javascript values to PHP script?

this is my php code that creates a table using the results of a mysql query:
echo "<table id='table' class='selectQuery'>
while($row = mysqli_fetch_array($slctQuery)) {
// ; echo $row['id']; echo
echo "<tr class='someClass' idNumber="; echo $row['id']; echo ">
<td>";
echo $row['fname'];
echo "</td>
<td>";
echo $row['lname'];
echo "</td>;
</tr>";
}
echo "</table>";
and this part is my jquery code for changing style on click on table row:
<script>
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
idNum = $(this).attr('idNumber');
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
</script>
and this part is for style:
<style>
tr.selected {
background-color: brown !important;
color: #FFF;
}
</style>
and this is my php code for button
if(#$_POST['Search']){
/// what should I do?
}
So, now I want have my idNum value when my search button in form was clicked.
thanks for attentions
You can use ajax. If you have a form with id="myform" and (example) input fields: firstname, lastname, username and password, the following script should send data to the php:
$(document).ready(function(){
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
The ajaxfile.php can be something like that:
<?php
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
//here you have the variables ready to do anything you want with them...
//for example insert them in mysql database:
$ins = "INSERT INTO users (firstname, lastname, username, password ) VALUES ( '$firstname', '$lastname', '$username', '$password' )";
if(mysql_query($ins)){echo "SUCCESS";}else{echo "FAILURE";}
?>
Another example, similar to yours, is to take the row id from your table, pass it to ajax, have ajax (for example) make a query to the database and return the results:
// your script, modified for ajax:
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
var idNum = $(this).attr('idNumber'); //use "var" to -initially- set the variable
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: 'id='+idNum
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
Modified ajaxfile.php to suit the above example:
<?php
$id = mysql_real_escape_string($_POST["id"]);
//query database to get results:
$result = "SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1";
$row = mysql_fetch_assoc($result);
echo "Username: ".$row["username"]."Password: ".$row["password"]."Firstname: ".$row["firstname"]."Lastname: ".$row["lastname"].
?>
Since your question was rather ambigious, I put more effort to give you an idea about the basics of ajax so that you work out your own solution, rather than to suggest a potential solution -that at the end could not be what you were looking for...
And since we are talking about ajax basics, it is a good practice to secure your ajax files since they are accessible from any browser:
in the very beginning of any ajax file, right below the "?php" tag, you can add these lines below, to protect the file from being accessed by browser -but remain accessible to ajax calls:
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
Hope that helps you and others. T.
UPDATE:
It is ALWAYS a good practice to keep your php and javascript files separately... In the above examples there are ideally 3 files involved: the main php file, the scripts file and the ajax-php file.
So -preferably after the "body" tag of your "main" php file- you should include the scripts-file (after the jquery ofcourse!). Like that:
<!-- jQuery v.1.11.3-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- include scripts file -->
<?php include("scripts.php"); ?>
(notice that for jquery I use the regular "script" tags but for the scripts file I just do a "php include").
As you see above, the javascript file has also ".php" extension (not ".js"). This is a "trick" I like to do because it gives me the ability to execute php code within the js file. Of course, all javascript code in that file is included between "script" tags.
example of a hypothetical "scripts.php":
<script>
// I create a js variable that takes value from php
var phpDate = '<?php date("Y-m-d"); ?>';
alert(phpDate);
//or pass the contents of another php variable in your app to javascript:
var myPhpVar = '<?php echo $my_php_var; ?>';
//or put a php SESSION to a js variable:
var mySess = '<?php echo $_SESSION["my_session"]; ?>';
</script>
The above comes quite handy sometimes when you want to pass to javascript php variables that already exist in your application.
It is a very long answer (more like a tutorial!)... But now should be quite clear to you how to pass values not only from js to php but also vice versa!!!

Categories