Updating Database from Javascript by calling PHP script - php

Ive been trying to get this for age
I am building a website which has an activity wall. I have the whole thing working except the like and unlike buttons. I have them currently just showing a text box I like or I don't like
<a href='#' onclick='like()'>Like</a>
or
<a href='#' onclick='unlike()'>Unlike</a>
Now these call these scripts
<script>
function like()
{
alert("I like");
document.getElementById("p1").innerHTML="<a href='#' onclick='unlike();'>Unlike</a> | 1 Life<hr/>";
}
function unlike()
{
alert("Dont like anymore");
document.getElementById("p1").innerHTML="<a href='#' onclick='like();'>Like</a> | 0 Lifes<hr/>";
}
</script>
I have a php script that connects to the database and adds or removes the like which I know works. I don't need to return anything to the javascript but how do I call that php script giving the postID and username??
Ok so using this I have modified it a little. But it still doesnt work :S
==LikeUnlink.php==
<?php
include 'phpScripts/OpenConnection.php';
$mode = $_GET['mode'];
$username = $_GET['username'];
$postID = $_GET['LikeID'];
echo $username."<br/>";
echo $mode."<br/>";
echo $postID."<br/>";
if($mode == 0)
{
$query = "INSERT INTO tbl1Ups (Username, ActivityID) VALUES ('$username', $postID)";
}
else
{
$query = "DELETE FROM `tbl1Ups` WHERE Username='$username' AND ActivityID=$postID";
}
$result = mysql_query($query) or die(mysql_error());
==MembersHome.php==
<script type="text/javascript">
function process(LikeId, Username, currentLikes, likeUnlike)
{
//your validation code
$.ajax(
{
type: 'GET',
url: LikeUnlike.php, //file where like unlike status change in database
data:{like:LikeId, username:Username, mode:likeUnlike},
success: function(data)
{
alert('It Works');
}
} );
}
</script>
==Like link==
<a href='Javascript:void(0)' onclick='process(".$row['ID'].", \"".$username."\", ".$likes.", 0);'>$linkText</a>

try this
<script type="text/javascript">
function process(LikeId) {
//your validation code
$.ajax( {
type: 'POST',
url: LikeUnlike.php, //file where like unlike status change in database
data:{like:LikeId},
success: function(data) {
//code you want to do after successfull process
}
} );
}
</script>
make changes in html
<a href='Javascript:void(0)' onclick='process(1)'>Like</a>
<a href='Javascript:void(0)' onclick='process(0)'>Unlike</a>

Related

How to refresh map only on click category?

Can some help me to solve this problem
I have a map on my website and i want to refresh map only on clicking on category my this is my product
<?php
/* $message = "in home";
echo "<script type='text/javascript'>alert('$message');</script>";*/
foreach($categories as $category){
echo '<li><img src="'.base_url('uploads/'.$category->image).'" alt="'.$category->cat_name.'" width="30" height="30"/></br><span>'.$category->cat_name.'</span></li>';
}
?>
</ul>
</div>
</div>
<script>
function changeData(category){
var urlCI = '.base_url('main/home/' .$category->adv_category).';
$.ajax({
type: "POST",
url: urlCI,
data:{'categoryReq':category},
success: function(response) {
if(response!=''){
$('map_marker').html(response);
}else{
return false;
}
}
});
}
</script>
my controller code is if you need other code please ask i will give. I give this just for refrence, thank you
public function home($cat=NULL)
{
//$cat=10;
//echo debug_backtrace()[1]['function'];
if($_POST)
{
print_result($_POST);
}
$sql="SELECT * FROM (`ad_category`) WHERE `status`=1 AND `del_status`=0";
$this->data['categories']=$this->db->query($sql)->result();
if($cat)
{
//$message = $cat;
//echo "<script type='text/javascript'>alert('$message');</script>";
//$this->data['middle_view']='home_again';
$this->data['ads']=$this->advt_m->get_advts($cat);
$this->input->post('map_marker',$this->data);
$this->data['subview']='home';
$this->load->view('__layout_main',$this->data);
}
else
{
/*$message = "Here 2";
echo "<script type='text/javascript'>alert('$message');</script>";
*/
$this->data['subview']='home';
//$this->data['middle_view']='home';
$this->data['ads']=NULL;
$this->load->view('__layout_main',$this->data);
}
var urlCI = '.base_url('main/home/' .$category->adv_category).';
probably should be
var urlCI = '<?php echo base_url("main/home/$category->adv_category"); ?>';
Split the Map div and its javascripts into another view.
Create function with all necessary functionalities for map. Add and load the it through Ajax call.
Ajax success:
success:function(response){
$('div').html(response);
//response will be the function which holds the $this->load->view('map');
}
map.php
<div id="map">
YOUR MAP GOES HERE
</div>
<script>
MAP SCRIPT
</script>
main.php (Your frontend)
<div id="map_here">
</div>
<script>
$.ajax({
type:"POST",
//Send some values
data:{
somevalue:'somedata',
category:"mine"
},
url:"<?php echo base_url();?>mycontroller/mapfunc",
success:function(response){
$('#map_here').html(response);
}
})
</script>
myconroller:
function mapfunc(){
//Using this value you can change the script
$data['category'] = $_POST('category');
$data['location'] = $_POST('somevalue');
//Process the works
$this->load->view('map',$data);
//On Ajax call this page can be loaded
}
Each ajax call it will reload the div.
any doubts just comment it...

Follow button with AJAX

I have created a button with which you can follow/unfollow a user, with AJAx and PHP.
If you click on the button, you follow, else, you unfollow.
There's a function that checks if the user you try to follow is already followed...
HTML
<div class="heart"><i class="fa fa-heart awesome"></i></div>
PHP
public static function Follow($user, $seguidor){
$sql = "INSERT INTO seguidores (id_canal, id_seguidor) VALUES ('$user', '$seguidor')";
$resultado = self::Conexion($sql);
return $resultado;
}
public static function CheckFollow($user, $seguidor){
$heart = "";
$sql = "SELECT * FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
$resultado = self::Conexion($sql);
$verificacion = false;
if(isset($resultado)) {
$fila = $resultado->fetch();
if($fila !== false){
$verificacion = true;
}
}
if($verificacion == false){
$heart = "<div data-id='".$user."' class='heart'><i class='fa fa-heart awesome'></i></div>";
} else {
$heart = "<div data-id='".$user."' class='heart like'><i class='fa fa-heart awesome'></i></div>";
}
return $heart;
}
public static function Unfollow($user, $seguidor){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
$resultado = self::Conexion($sql);
return $resultado;
}
AJAX
$(document).ready(function () {
$function() {
var element = $(this);
var data_id = element.attr("data-id");
$.ajax({
type: "POST",
url: "database.php",
data: data_id,
success: function(){ }
});
return false;
}
});
The problem is, how can I load those php funcionts everytime I click the button...
Click > follow
Another click > unfollow
Here's a few suggestions:
I notice you are creating HTML strings in PHP. If at all possible, you want to avoid doing that.
Keep all your HTML, CSS and JavaScript client-side. As you progress as a developer, you will start to see why. Think of them as templates.
In this case, you just need to return either "followed" or 'unfollowed" to the client callback. Could boil it down to a boolean!
So, in your template, define both the followed state and the unfollowed state. Use CSS to hide the appropriate one. This can be incredibly lightweight!
In these examples, you just set the follow attribute on your button.
So your javascript would look like:
// I would do something like:
find=document;
id="getElementById";
/* ... */
success: function (request, status)
{
if (!status)
return
;
find[id]("follow-1").setAttribute("follow", request.responseText)
}
(check the ajax api of the lib)
1.)
<button id="follow-1" follow="true">
<img src="transparent.png" />
</button>
+
button[follow="false"] > img
{ background: transparent url("unfollow.png");
}
button[follow="true"] > img
{ background: transparent url("follow.png");
}
2.)
<button id="follow-1" follow="true">
<img src="follow.png" />
<img src="unfollow.png" />
</button>
+
button[follow] > img
{ display: none;
}
button[follow="false"] > img:last-child
{ display: block;
}
button[follow="true"] > img:first-child
{ display: block;
}
I would suggest using framework such as CodeIgniter to handle the back-end as you can post data directly to public controller methods directly from ajax, but for rough idea on how it could work (you may need to fix up bugs / tweak as I wrote from memory):
Add to PHP to handle incoming requests:
//Minimal vulnerability protection while getting inputs.
$update_types = array("Follow", "CheckFollow", "Unfollow");
$update_method = in_array($_POST["update_type"],
$update_types)? $_POST["update_type"], "");
if ($update_method) {
//Call the update function & bounce the response
//in JSON back to the AJAX handler.
echo json_encode(call_user_func($update_method,
(int) $_POST["user_id"], (int) $_POST["seguidor"]));
}
Javascript:
$(document).ready(function () {
//Button click handler.
$("div.heart").on("click", function() {
var my_button = $(this);
var update_type = "";
if (my_button.hasClass('.like'))
update_type = "Unfollow";
else
update_type = "Follow";
$.ajax({
type: "POST",
url: "database.php",
data: {
"update_type": update_type,
user_id: my_button.attr("data-id"),
seguidor: "some value here - not sure based on code"
},
success: function(response) {
//response from server - check for errors...
//Update the UI - add heart if follow updated, remove it if not.
//You will need to modify your php functions to return result code and then either add "like" class or remove it - obviously this is not a complete rewrite of your app.
if ("/* result is followed */")
my_button.addClass("like");
else
my_button.removeClass("like");
}
});
});
});

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

Delete record with ajax via id

Having trouble deleting a record from mysql databse using ajax/jquery. Issue I am having is that it does not delete from the database but does delete from the list. What am I doing wrong here?
Here is my code:
jQuery(document).ready(function(){
$(".deleteitem").click(function(){
var parent = $(this).closest('li');
var id = parent.attr('id');
$.ajax({
type: "POST",
data: "id=" +id,
URL: "delete.php",
success: function(msg){
$('#'+id).remove();
}
});
});
});
My php file delete.php:
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_POST['id'];
if (isset($id)) {
$query = "DELETE FROM img_slider WHERE id = '$id'";
mysqli_query($query) or die('Error, insert query failed');
}
The HTML markup:
<li id='".$row['id']."'>
<a href='#' class='deleteitem'><img src='../img/delete.png'></a>
</li>
Firstly test to make sure calling the delete file with a valid id works. The javascript below should work fine.
<script type="text/javascript">
<!--
$(function() {
$('.deleteitem').click(function(e) {
e.preventDefault();
var id = $(this).parent('li').attr('id');
$.get('delete.php',{ id: id}).done(function(data) {
if(data=='Error, insert query failed') {
// dont delete from list
alert('Failed to delete '+id);
} else {
//delete from list
$('#'+id).remove();
alert('Deleted '+id);
}
});
});
});
//-->
</script>
EDIT: updated the script to assist parent-id handling.
Are you able to say where the error is coming from? Most modern browsers should offer you some insight into what line, or what section the error is occurring on.
The script above should replace all your javascript.

Jquery not connecting to .php

I am having some trouble with my jquery. I am not sure if it is connecting to doc.php but I am not getting anything inserted into my database.
I have an insert command in doc.php which I know is working.
I'm trying to create a way to update prices in a database, from doc.php, that searches out items one at a time.
The doc.php is searching by var, then updating in the same page.
The foreach loop function then, takes the var one by one, sends them to the doc.php page that then searches by var and updates into the database.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die (mysql_error());
$sql = "SELECT var FROM table";
$query = mysql_query($sql) or die (mysql_error());
while ($result = mysql_fetch_array($query)) {
$variable = array($result['var']);
foreach ($variable as $variable1) {
?>
<script src="jquery-1.7.2.min.js" type="text/javascript">
$(function() {
var valueToSend = '<?php echo $variable1; ?>';
$.ajax({
url: "doc.php",
dataType: "json",
type: "POST",
data: { Variable: valueToSend },
success: function (m) {
alert(m);
},
error: function (e) {
alert("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
}
}
?>
First of all, what do you want to do with this code? If you want to read & write to db using php, ajax call is unnecessary. If you want to practice ajax & php you need to read some howto because your code is somewhere strange ;). This is nice collection of tutorials for jQuery and some for PHP read some and practice.

Categories