Using AJAX to return JSON from PHP - 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.

Related

if statement in success ajax

I'm having trouble implementing if statement in ajax success function.
<?php
include('../Config/config.php');
$myquery = "SELECT * FROM voters WHERE Precinct = '".$_POST['precinct']."'";
$execute = mysqli_query($mysqli, $myquery);
if (mysqli_num_rows($execute) >= 1)
{
echo "Precinct is full.\n Recheck precinct number.";
}
?>
function checkerprecinct() {
var precinct = $("#precinct").val();
$.ajax({
type: "POST",
url: "precinctchecker.php",
data: "precinct=" + precinct,
success: function(data) {
console.log(data);
if (data === "") {
alert("Data is empty!");
} else {
alert(data);
}
}
});
}
I would like to use this as a validation.
I want to alert the user if the sent data contains similar data from the database.
try this code
change with your code
PHP Code:
$data = array();
if (mysqli_num_rows($execute) >= 1)
{
$data= array('code'=>100,'message'=>"Precinct is full.\n Recheck precinct number.");
//echo "Precinct is full.\n Recheck precinct number.";
}else{
$data= array('code'=>101,'message'=>"Data is empty!");
}
echo json_encode($data);
exit;
ajax code:
var data = JSON.parse(data);
if (data['code'] == 100) {
alert(data['message']);
}

submit ajax form with condition

hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});

Passing json to php and getting response

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}");

How to insert a variable in a query from .ajax post

I thought this will be very simple but i think there is a bug when posting a variable from .ajax to a query. Is there any other way I ca get my result?
here is my jquery:
jQuery_1_4_2(document).ready(function()
{
jQuery_1_4_2('.mainfolder').live("click",function()
{
event.preventDefault();
var ID = jQuery_1_4_2(this).attr("id");
var dataString = 'folder_id='+ ID;
if(ID=='')
{
alert("Serious Error Occured");
}
else
{
jQuery_1_4_2.ajax({
type: "POST",
url: "display_folder.php",
data: dataString,
cache: false,
success: function(html){
jQuery_1_4_2(".right_file").prepend(html);
}
});
}
});
});
here is my display_folder.php
<?php
$folder_id = $_POST['folder_id'];
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
Can anybody explain why this not work? i tried to echo $folder_id and it is working, but when you put it inside the query it is not working.
Note: This is not a dumb question where i forgot my connection of db. Thanks
I agree with both you and here I am providing (just for clean display) the same with some little formatting.
var dataString = 'folder_id=1';
$.ajax({
url: "folder.php",
type:'post',
async: false,
data:dataString,
success: function(data){
alert(data);
}
});
and php part where I am getting folder_id properly.
<?php
$postid = $_POST['folder_id'];
//echo $postid;
$link = mysql_connect("localhost","root","");
mysql_select_db("test", $link);
$query = mysql_query("select * from post where id='$postid'");
while($row=mysql_fetch_array($query))
{
echo $row['text'] . "<br>"; //a, b etc in each row
}
?>
So it should work.
Try this in your php code
<?php
$folder_id = addslashes($_POST['folder_id']);
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>

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)

Categories