Passing json to php and getting response - php

I am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}

Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});

Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");

Related

Ajax cannot display json data from php. What's wrong with json format?

I have read all the related questions that reference to this topic, but still cannot find answer here. So, php and ajax works great. The problem starts when i try to include json, between php and ajax, to passing data.
here is my ajax:
function likeButton(commentId, userId, sessionUserId) {
// check if the comment belong to the session userId
if(sessionUserId == userId) {
alert("You cannot like your own comment.");
}
else if(sessionUserId != userId) {
var like_upgrade = false;
$.ajax({
url: "requests.php",
type: "POST",
dataType: "json",
data: {
keyLike: "like",
commentId: commentId,
userId: userId,
sessionUserId: sessionUserId,
like_upgrade: like_upgrade
},
success: function(data) {
var data = $.parseJSON(data);
$("#comment_body td").find("#updRow #updComLike[data-id='" +commentId+ "']").html(data.gaming_comment_like);
if(data.like_upgrade == true) {
upgradeReputation(userId);
}
}
});
}
}
Note, that i try not to include this:
var data = $.parseJSON(data);
Also i tried with diferent variable like so:
var response = $.parseJSON(data);
and also tried this format:
var data = jQuery.parseJSON(data);
None of these worked.
here is requests.php file:
if(isset($_POST['keyLike'])) {
if($_POST['keyLike'] == "like") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sessionUserId = $_POST['sessionUserId'];
$sql_upgrade_like = "SELECT * FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result_upgrade_like = mysqli_query($conn, $sql_upgrade_like);
if($row_upgrade_like = mysqli_fetch_assoc($result_upgrade_like)) {
$gaming_comment_like = $row_upgrade_like['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update_like = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update_like = mysqli_query($conn, $sql_update_like);
$sql_insert_like = "INSERT INTO gaming_comment_likes (gaming_comment_id, user_id, user_id_like) VALUES ('$commentId', '$userId', '$sessionUserId')";
$result_insert_like = mysqli_query($conn, $sql_insert_like);
$like_upgrade = true;
//json format
$data = array("gaming_comment_like" => $gaming_comment_like,
"like_upgrade" => $like_upgrade);
echo json_encode($data);
exit();
}
}
Note: i also try to include this to the top of my php file:
header('Content-type: json/application');
but still not worked.
What am i missing here?
Don't call $.parseJSON. jQuery does that automatically when you specify dataType: 'json', so data contains the object already.
You should also learn to use parametrized queries instead of substituting variables into the SQL. Your code is vulnerable to SQL injection.

Using AJAX to return JSON from PHP

Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});

jQuery .ajax query to insert data inside a database is not working

I am building a website that uses jQuery/AJAX to send data to a php page, and from there insert it into a database. For some reason, the code isn't inserted and I get no response at all.
my javascript:
function insert_data(){
var title = debate_title.value;
var subtitle = debate_sub.value;
var sides = debate_sides.value;
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 404) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 500) {
window.location.replace('errors/noConnection.html');
} else if (exception === 'parsererror') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'timeout') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'abort') {
window.location.replace('errors/noConnection.html');
} else {
window.location.replace('errors/noConnection.html');
}
}
});
});
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sidesm, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
}
My PHP code (post_debate.php):
<?php
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
exit($final_id);
}else{
die("404 SERVER ERROR");
}
?>
Thanks!
EDIT - NOT SOLVED YET
My new PHP code:
<?php
header("content-type: application/json");
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
print (json_encode(array("Id"=>$final_id)));
}else{
die("404 SERVER ERROR");
}
?>
my new Javascript .ajax:
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sides, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data['Id']);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
Your code is expecting JSON as a response...
dataType: "json",
(Documentation Here)
But you're returning a non-json value without an appropriate content-type header.
Try changing your PHP script from
exit($final_id);
to (untested)
header("content-type: application/json");
print (json_encode(array(
"Id"=>$final_id
)));
Also, put a breakpoint on your success callback in your Javascript code (using Firebug or a similar tool) and examine what data contains. It should now be an associative array so you can do
window.location.replace('show_debate.php?id=' + data['Id']);
Improvement:
Instead of doing a SELECT to get the recently inserted Id, use mysql_insert_id(). Something like this...
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$final_id = mysql_insert_id();
print (json_encode(array("Id"=>$final_id)));
Also, an alternate way to test what your PHP is returning if you can't see the response in your development tool is to browse to the page directly (You'd have to change all your $_POST to $_REQUEST)

Parsing values in JSON

I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.

Categories