how can i create a success back function? - php

$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){}
});
$("#follow"+I).hide(); ///showing the remove button after the data has been entered
$("#remove"+I).show();
return false;
});
});
The PHP file listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
?>
what I want to do is when I click the follow button, I want to check if the data has been entered into the database, before showing the remove button, basically checking on the background.

mysql_query will return TRUE or FALSE. You can echo that from the PHP script, and have the ajax call read it.
listen.php:
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
echo json_encode(array('response'=>$registerlistener));
?>
In your JavaScript:
$.ajax({
type: "POST",
url: "listen.php",
data: info,
dataType: 'json',
success: function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}
});
If you want, you can use the $.post shorthand:
$.post('listen.php', info, function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}, 'json');

Put the code you want to execute inside your 'success' callback function.
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){
$("#follow"+I).hide();
$("#remove"+I).show();
}
});

do it like this:
listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
if($registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')")):
echo "true";
else:
echo "false";
endif;
?>
pass parameter in success function, example "msg". whatever was echo'ed in listen.php will be in the msg variable now
success: function(msg){}
if(msg == "true")
{
//do something
}
else
{
//show error message
}
});

Related

Ajax not being called by select

Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.
Select Box
<form><select id="workingpattern">
<?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?>
<option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>">
<?php echo $workingpatterns[$k4]["text"]; ?></option>
<?php }}?>
</select></form>
Ajax:
<script>
$(document).ready(function(){
$('#workingpattern').change(function(){
var e = document.getElementById("workingpattern");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "saveedit2.php",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>
SaveEdit2.php
<?php
require_once("connect_db.php");
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:
$('#workingpattern').change(function(){
var value = $(this).val();
$.ajax({
url: "saveedit2.php",
type: "post",
data: 'value='+value,
success: function(data) {
console.log(data);
}
});
});
Try
Ajax
$('#workingpattern').change(function(){
var value = $("#workingpattern").val();
$.ajax({
dataType: "json",
url: "./saveedit2.php",
data: {'value':value},
success: function(data){
if(data['result']=="ok")
alert("Done");
else
alert("Error");
}
});
SaveEdit2.php
<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";
echo json_encode(array('result'=>$ajax_result));
?>

Check if username exist, then i want to update

I have a code that checks if the username is available if you want to change. But now I saw that if you update something else such as your password, you can assume to save as the user name already exists.
Listed below are the code I use, as you see, I have tried to think of something but did not go well at all.
PHP
$sql = "Select * FROM table WHERE Slug = '$slug' AND ID ='$id' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0){
echo 'true';
}else{
$e_sql = "Select * FROM table WHERE Slug = '$slug'";
$e_query = mysql_query($e_sql);
if(mysql_num_rows($e_query)>0){
echo 'false';
}else{
echo 'false';
}
}
Jquery/Javascript
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "User.php",
data: {
'slug': value,
'id': <?php echo $id; ?>
},
dataType:"html",
success: function(msg)
{ console.log(msg);
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"This Name is already used!"
);
$("#addSurvey").validate({
rules: {
name: {
required: true,
uniqueUserName: true
},
}
});
Basically problem is in your $.ajax request.
As you know $.ajax by default perform an asynchronous HTTP (Ajax) request.
Easiest solution for you is to make request synchronous.
To make request synchronous you should set option async: false - in this case code will be executed linearly and you will get return response; only when ajax request is completed.
So basically change part of ajax call to:
$.ajax({
type: "POST",
url: "User.php",
async: false,
data: {
'slug': value,
'id': <?php echo $id; ?>
},
dataType:"html",
success: function(msg){
response = msg === 'true';
}
});
May be useful:
jQuery.ajax() Documentation
set
response = (( msg == 'true' ) ? true : false);

Page reload not working when the page was called by AJAX

Let's say this is my AJAX
function call_page(id)
{
$.ajax({
type: "POST",
url: "call_me.php",
data: "id=" + id,
success: function(msg){ }
});
}
call_me.php was successfully called.
Let's say this is my call_me.php content
<?php
$var = $_POST['id'];
if(empty($var))
{
header("location: call_me.php?id=101");
}
else
{
do something...
}
?>
Assuming that the first condition 'if(empty($var))' is always satisfied.
The page must reload and the go to the else statement.
But this is not happening. I guess the page isn't reloading.
How can I correct this problem?
Thanks!
Try this
<?php
$var = $_GET['id'];
if(empty($var))
{
// here flag for redirection is set
echo 1;
}
else
{
do something...
}
?>
In AJAX:
$.ajax({
type: "POST",
url: "call_me.php",
data: "id=" + id,
success: function(msg){
// checking the response is for redirection
if(msg == 1)
// javascript code for redirecting to callme.php
window.location = "call_me.php?id=101";
}
});

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

jQuery autosave running success function, but not updating MySQL

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'];

Categories