Get different JSON responses from PHP - php

I'm making an app on phonegap.
I'm doing a script that read a ticket code (two queries, first to update the ticket status if exist on the db and second to write a log on another table). This is working fine.
But now, I want to get different responses (Valid or Invalid) with json, but I can't find a way to read the data and showing different responses.
Script on index.html
$(function() {
$("#savedata").click(function() {
var fcode = $("#code").val();
var fuuid = $("#uuid").val();
$("#code").val(" ");
$("#uuid").val(" ");
$.ajax({type: "POST",
url: "http://phonegap.localhost/test/www/db/update.php",
data: ({code: fcode, uuid: fuuid}),
cache: false,
dataType: "text",
success: Send
});
});
function Send(data){
document.getElementById('entrada').innerHTML = ("Done!");
}
});
Update.php
<?php
require_once('conndb.php');
$code= $_POST['code'];
$uuid = $_POST['uuid'];
$data=array();
$sql = "SELECT code FROM ticket WHERE code='$code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$sql="UPDATE ticket SET redeem_status= 1 WHERE code = '$code'";
$resultado=mysql_query($sql);
$sql2="INSERT INTO log (id, codigo, hora, uuid, valido) VALUES (NULL, '$code', CURRENT_TIMESTAMP, '$uuid', 1)";
$resultado2=mysql_query($sql2);
}
$val['status'] = 1;
echo json_encode($val);
}else{
$sql2="INSERT INTO log (id, codigo, hora, uuid, valido) VALUES (NULL, '$code', CURRENT_TIMESTAMP, '$uuid', 0)";
$resultado2=mysql_query($sql2);
$val['status'] = 0;
echo json_encode($val);
}
?>

In your javascript code you expect TEXT data but in php-script you sending json. So change dataType to json and fix function Send
Here is simple solution
$(function() {
$("#savedata").click(function() {
var fcode = $("#code").val();
var fuuid = $("#uuid").val();
$("#code").val(" ");
$("#uuid").val(" ");
$.ajax({type: "POST",
url: "http://phonegap.localhost/test/www/db/update.php",
data: ({code: fcode, uuid: fuuid}),
cache: false,
dataType: "json",
success: Send
});
});
function Send(data){
if (data.status == 0){
document.getElementById('entrada').innerHTML = ("Error!");
}
else{
document.getElementById('entrada').innerHTML = ("Done!");
}
}
});

You just have to create a new PHP page which is reading data in your DB and then returning it as JSON (as you're doing right now) and bind an action on a button for example with jQuery in your phonegap app to launch an Ajax call to this page then on success, you use a function to apply what you receive on the smartphone screen.

Related

php function returning value for some pages, but fails to return values for other pages with same document structure

So here I want to get an ID for the specific user, using a php page, and then perform database insert using a function defined in a file named 'functions.php'. So basically, I am capturing values from a page using jQuery ajax() method and sending the data to a php page named 'follow_school.php'. The rest of what's happening would be clear from the code, I provide below:
jQuery code:
jQuery(document).ready(function() {
var school_name = jQuery('#school-name').text();
var session_var = jQuery('#session').text();
// console.log(session_var);
var button_text_onload =
localStorage.getItem("btnText_"+school_name+"_for_"+session_var);
console.log(button_text_onload);
if (button_text_onload !== null) {
jQuery('#follow-button').html(button_text_onload);
} else {
jQuery('#follow-button').html('Follow');
}
jQuery('#follow-button').click(function() {
// alert (session_var);
// console.log(session_var);
var button_text = jQuery('#follow-button').text();
// alert(button_text);
if (button_text === 'Follow') {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/follow_school.php',
data: {name : school_name,
email : session_var
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Unfollow");
jQuery('#follow-button').html('Unfollow');
}});
} else {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/unfollow_school.php',
data: {name : school_name,
email : session_var,
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Follow");
jQuery('#follow-button').html("Follow");
}});
}
});
});
follow_school.php
<?php
include_once "includes/db.php";
include_once "includes/functions.php";
$name = $_POST['name'];
$email = $_POST['email'];
$id = get_id($email);
/* for debugging purpose */
if ($id == null) {
var_dump($id);
} else {
echo $id;
}
echo $email;
/* insert operation */
insert_school($id, $name);
?>
functions.php
function get_id($email) {
global $conn;
$sql = "SELECT id FROM member WHERE email = '$email'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
return $row["id"];
}
function insert_school($id, $name) {
global $conn;
$sql = "INSERT INTO user_schools (user_id, school_name)
VALUES ('$id', '$name')";
$conn->query($sql);
}
NOTE: Here the database connection is perfectly fine, and these codes worked for some pages earlier. But apparently, other pages don't seem to run the code, or to be precise, returns "null" as id. Also, I would like to mention that, the table entries and fields are not null, or unspecified. They are perfectly fine, as I said, it worked for some pages.
Please can anyone guide me, as to what's going wrong here, because after dedicating so much of my time on this, i still am not able to understand the issue.
Thank you.

How to manage Ajax success function?

if (isset($_POST["getCanvas"]) ) {
$projectName= mysqli_real_escape_string($db2, $_POST['whichProject']);
$query = "SELECT objectsList FROM projectObjectstable WHERE projectName='$projectName'";
// $query = "SELECT objectsList,backgroundImage FROM projectObjectstable WHERE projectName='$projectName'";
$jsonCanvas= mysqli_query($db2,$query);
$row = mysqli_fetch_row($jsonCanvas);
$myLine=$row['0'];
echo $myLine;
}
With code above i get one column from table. I need two columns. I woud like to try next:
$query = "SELECT objectsList FROM projectObjectstable WHERE projectName='$projectName'";
$jsonCanvas= mysqli_query($db2,$query);
$row = mysqli_fetch_row($jsonCanvas);
$myLine=$row['0'];
echo $myLine;
$query2 = "SELECT backgroundImage FROM projectObjectstable WHERE projectName='$projectName'";
$jsonBackground= mysqli_query($db2,$query2);
$row2 = mysqli_fetch_row($jsonBackground);
$myLine2=$row['0'];
echo $myLine2;
}
For it I need next solution here. How to modificate ajax success function to get two variables (projectList and backgroundImage) on canvas?
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage3/PgetJson.php',
data: {
"getCanvas":1,
"whichProject":whichProjectToSave
},
datatype: "text",
success: function(strdate){
canvas.loadFromJSON(strdate, function() {
canvas.renderAll();
});
}
});
An extra information would e appreciated. What options exists to debug php code in browser, as it is possible to do with js ?
Thank you
As it was said before, you need to use json_encode function to send parameters in JSON format to your JS. You have to put your variables inside an array before calling to echo. As it's used below.
$query = "SELECT objectsList FROM projectObjectstable
WHERE projectName='$projectName'";
$_row= mysqli_query($db2,$query);
$row = mysqli_fetch_row($_row);
$jsonCanvas=$row['0'];
$query2 = "SELECT backgroundImage FROM projectObjectstable
WHERE projectName='.$projectName.'";
$_row2= mysqli_query($db2,$query2);
$row2 = mysqli_fetch_row($_row2);
$jsonBackground=$row['0'];
$to_json['jsonCanvas'] = $jsonCanvas;
$to_json['jsonBackground'] = $jsonBackground;
echo json_encode($to_json);
exit();
And in your JS, you collect your information in the success function:
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage3/PgetJson.php',
data: {
"getCanvas":1,
"whichProject":whichProjectToSave
},
datatype: "json",
success: function(strdate){
/*Here on data you will receive
strdate['jsonCanvas'] & strdate['jsonBackground']
*/
});
}
});
I would also recommend making your sql calls in one query if your calling to the same table and passing the same variable as an argument.

Save to database without a form using jQuery and PHP

I'm trying to save some data to a database without the use of an html form and was wondering if anyone could help me as I'm no expert in PHP. So far I have got:
JQuery
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: //Data to send,
success: function () {
$('.success_message').html("success");
}
});
});
There is no issue at the first stage as all my values are stored in the variables correctly. I just don't know in what format to send them across to save.php.
save.php
<?php
require_once 'dbconfig.php';
//Connects to database
if($_POST)
{
//Not sure what to post here
$current_date = date('Y-m-d');
try{
$stmt = $db_con->prepare("INSERT INTO entry(user_id, date, weight, bmi, calories_consumed, calories_burned, calorific_deficit) VALUES(:user, :date, :weight, :bmi, :consumed, :burned, :deficit)");
$stmt->bindParam(":user", $user_id);
$stmt->bindParam(":date", $current_date);
$stmt->bindParam(":weight", $summary_weight);
$stmt->bindParam(":bmi", $summary_bmi);
$stmt->bindParam(":consumed", $summary_consumed);
$stmt->bindParam(":burned", $summary_burned);
$stmt->bindParam(":deficit", $summary_total);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
I'm not sure how to post this data to save.php and then how to process it to be sent to the database. I've also added a variable of current_date to send the current date to a field in the database.
Can anyone help me and fill in the blanks? Or maybe I'm going about this the wrong way?
Send your data in an object, like so:
// Declare data as an empty object
var data = {};
// Assemble the properties of the data object
data.summary_weight = $('#summary_weight').text();
data.summary_bmi = $('#summary_bmi').text();
data.summary_consumed = $('#summary_consumed').text();
data.summary_burned = $('#summary_burned').text();
data.summary_total = $('#summary_total').text();
data.user_id = $('#user_id').text();
$.ajax({
type: "POST",
url: "save.php",
// pass the data object in to the data property here
data: data,
success: function () {
$('.success_message').html("success");
}
});
Then, on the server side, you can access directly via $_POST superglobal:
$summary_weight = $_POST['summary_weight'];
$summary_bmi = $_POST['summary_bmi'];
// etc...
You can send all this data in the data parameter as given below:
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: {summary_weight: summary_weight, summary_bmi:summary_bmi, summary_consumed:summary_consumed, summary_burned: summary_burned, summary_total:summary_total, user_id:user_id },
success: function () {
$('.success_message').html("success");
}
});
});
And the, process it in save.php like this
$summary_weight = $_POST['summary_weight'];
and use it in the query to save it in database.

Get feedback from query to webpage

So I have a div that I want to convert to a success alert after a successful insertion into the database. The AJAX success function of course runs only on successful POST to the PHP page, so how would I go about getting feedback from my insert query? Nothing shows up in my network tab that relates to the query.
$.ajax({
type: "POST",
url: "follow.php",
data: {usrid: <?php echo "$sess_user_id1"; ?>, usrname: "<?php echo $sess_username; ?>", gender: <?php echo "$sess_gender"; ?>, markid: <?php echo "$markerid"; ?>, type: "<?php echo $type; ?>", usrhomelat: <?php echo "$sess_homelat"; ?>, usrhomelng: <?php echo "$sess_homelng"; ?>, blurb: ($("#textarea").val())},
success: function (data, msg) {
alert("Congratulations ");
$("#thanks").html(msg);
},
error: function () {
alert("At this time, you could not be added");
}
});
Then on my follow.php page, I have my query, which, I know shouldn't be in mySQL(I will convert before taking the site live):
$query = "INSERT INTO markerfollowing (userID, username, gender, markerID, type, usrhomelat, usrhomelng, blurb)
VALUES ('$user_id_follow', '$username2', '$gender', '$marker_id', '$type', '$usrhomelat', '$usrhomelng', '$blurb');";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
As you can probably tell, I am an amateur, so any assistance is greatly appreciated. I don't even know what search terms to use to address this issue. Thanks!
Well, as far as I can see your ajax call looks ok. Your problem lies in the data you are sending back and how you handle it.
If you do it in your way you just get a simple string. You could go for a call expecting json data like this.
Php part returns an array in json form.
$return = array();
if (!$result) {
$return['success'] = 0;
$return['message'] = 'Invalid query '.mysql_error();
} else {
$return['success'] = 1;
$return['message'] = 'Successfully saved!';
}
echo json_encode($return);
The ajax call changes like this (we'll be expecting a json object so we tell the ajax call what to expect from the server in dataType):
dataType: "json",
success: function (data) {
if (data['success'] == 0) {
alert("Congratulations");
$("#thanks").html(data['message']);
} else {
alert("At this time, you could not be added");
// You could also use the data['message'] that got sent back here.
}
}
The error function should not be used for transporting data from the follow.php script because it gets called if there was a more basic transfer type of error.
I hope that helps you with your problem.

JQuery Ajax Updating MySQL Database, But Not Running Success Function

I am currently using the JQuery ajax function to call an exterior PHP file, in which I select and add data in a database. Once this is done, I run a success function in JavaScript. What's weird is that the database is updating successfully when ajax is called, however the success function is not running. Here is my code:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head>
<body>
<div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div>
<script>
function addtask() {
var tid = (Math.floor(Math.random() * 3)) + 1;
var tsk = (Math.floor(Math.random() * 10)) + 1;
if(tsk !== 1) {
$.ajax({
type: "POST",
url: "taskcheck.php",
dataType: "json",
data: {taskid:tid},
success: function(task) {alert(task.name);}
});
}
}
</script>
</body>
</html>
And the PHP file:
session_start();
$connect = mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$task = $_REQUEST['taskid'];
$uid = $_SESSION['user_id'];
$q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1";
$gettask = mysql_fetch_assoc(mysql_query($q));
$q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)";
$puttask = mysql_fetch_assoc(mysql_query($q));
$json = array(
"name" => $gettask['taskname']
);
$output = json_encode($json);
echo $output;
Let me know if you have any questions or comments, thanks.
Ibelieve it runs but alert wont show because of error -
success: function(task) {alert(task.name);}
You have to decode JSON first with jQuery.parseJSON(), task is just a string
it shoudld look somthing like this
function(m)
{
var task = jQuery.parseJSON( m );
alert(task['name']);
}
Edit:
Ok ...
Try to use developer tools in your browser and place breakpoint on your success function, if it doesnt even lunch try to add error callback for your ajax call
error: function(xhr, exc)
{
alert(xhr.status);
alert(exc);
}
Edit2:
and there is your problem - your ajax is not only returning json data, but php warning too, and now I see where is your problem - you are fetching data after insert, delete
$puttask = mysql_fetch_assoc(mysql_query($q));
Now I feel bad for not noticing it sooner...

Categories