Use PHP + jQuery when click on a button - php

I have a button on my page :
<button class="play"></button>
When I click on it, it launches the video via jQuery
$('.play').on('click',function(){
player.play();
});
But I also want to add PHP code to save the user ID in the database when he clicks on that button.
How can I mix PHP & jQuery? I'm not used to Ajax, is it the solution?
Thanks for your help!

add a function:
function add_to_db(user_id){
$.post('add.php', {userId: user_id}, function(response){
//do something with the response
r = JSON.parse(response);
if (r.status === 'error'){
//handle the error
alert(r.message);
}
});
});
when you play do the following
$('.play').on('click',function(){
player.play();
user_id = //however you chose to set this in the page
add_to_db(user_id);
});
your add.php:
//perform your db update or insert
//if successful:
$response['status'] = 'success';
//else:
$response['status'] = 'error';
$response['message'] = 'update was not successful';
//look into try/catch blocks for more detailed error messaging.
//then send the response back
echo json_encode($response);

Try using ajax
$('.play').on('click',function(){
player.play();
$.ajax({
type: "POST",
url: "some.php", // your php file name
data:{id :"id"}, //pass your user id
success:function(data)
{
if(data==true)
alert("success");
else
alert("error");
}
});
}
some.php
<?php
$success=false; //Declare and initialize a variable
// do your code to update your database
//and check if the database is updated , if so set $success=true
echo $success;
?>

Related

Confirming A Database Row was deleted via PHP in aJax/jQuery

I'm trying to figure out the best way to relay back to ajax if the POST data sent to the .php file successfully deleted the data from the database. I'm not sure what to phrase what I'm looking for, but essentially I thought about a 'if() { } else { }' statement perhaps, but I'm not sure how to send the data back correctly into the success:function. Here is the basic code below that ajax is using. The PHP file is just standard code for running a deletion via php/mysqli.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
//IF() {
//EXECUTE SUCCESS & REMOVE DIV
//} ELSE {
//GIVE NOTICE OF DELETION FAILURE
//}
}
});
So anyone have any ideas how I could accomplish this?
On your php. depends on what you are using, you can check if the query was successful or not. then you can add anything on your return statement that you could use on your ajax success funtion.
Example:
on the php side using PDO
$success = true;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "DELETE FROM MyGuests WHERE id=3";
$conn->exec($sql);
} catch (PDOException $e) {
$success = false;
}
return json_encode([
'success' => $success
])
Then on ajax. you can use this
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
IF(data.success) {
//EXECUTE SUCCESS & REMOVE DIV
} ELSE {
//GIVE NOTICE OF DELETION FAILURE
}
}});
Some changes in your php file. if delete query return success then return true or 1 otherwise false or 0.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
if(data == 1){
alert("success");
} else {
alert("error");
}
}
});
it depends on what you send back from your php script, i recommend JSON which you could format as such
{
status:"success",//or error if failed
message:"record was successfully deleted"
}
in the php script you could have a Boolean flag to check if the record was deleted eg:
if($deleteFlag){
$response = array('status'=>'success', 'message'=>'record was successfully deleted');
} else {
$response = array('status'=>'error', 'message'=>'could not delete record!');
}
header('Content-type: application/json');
echo json_encode($response);

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Using Ajax to generate an alert box

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Using Ajax to generate an alert box after checking whether some data are stored in database [duplicate]

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Pass data from JQuery to database via Javascript/AJAX/JSON/PHP

I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}

Categories