AngularJS posting data to a php mysql insert - php

I'm writing a webapp which successfully allows me to login to Facebook (I'm using Phonegap and the Phonegap Facebook plugin). I then want to store the logged in users name and ID. To start with as a simple test I wanted to get the following controller to run collect the ID, display it in the xcode console to confirm it was there and then send it to the php code below to then store in a mysql table. I can't seem to get it working and I think it's possibly the format of my data in the {}'s within the $http.post but it's a bit beyond my current knowledge to figure this one out. Any ideas?
function FacebookCtrl($scope) {
FB.api('/me', function(response) {
var fbid=response.id;
console.log('Testing, ' + fbid + '.');
$http.post('http://somedomain.co.uk/php/users.php', {uid: fbid})
console.log('Complete');
});
}
The php code at the receiving end is:
<?php
$data = file_get_contents("php://input");
$objData = json_decode($data);
$uid = $objData->uid;
try {
include 'database.php';
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO Userdata (oauth_uid) VALUES (:userid)');
$stmt->execute(array(
':userid' => $uid,
));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
The same php code works with another one of my controllers however the difference is that the other controller captures the data passed from a form so the http.post looks like this:
$http.post('http://somedomain.co.uk/php/submitdata.php', {Position1: $scope.position1}
And the code in the php that captures this data is:
$Position1 = $objData->Position1->Name;
As the code all works on another controller, I'm assuming that the issue is with how I'm formatting the data I'm passing between the {}'s?

Try to define success \ error callbacks
$http.post("http://somedomain.co.uk/php/users.php", {uid: fbid})
.success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
What will it say then?

Related

Compare user value to database and show result through ajax jquery

Guys m working on my first live project and i am stuck at a point, where i need help with ajax jquery. i can do this with PHP but i wanna do this with ajax.
Here if user enter a product code ,so i want to compare this product code value into my database and show product name in my other form ,which will open after user input value:
Here in first field i want product name:
Here in my table you can see product code and product name:
ok so here is my html code in last option when user enter product code
Here is jquery i am sending user data to 8transectiondata.php to compare
And this is php file and i want $data['product_name']; to show
Here's a generic answer.
JS FILE:
$(document).ready(function () {
$('#myButtonId').on('click', function () {
var code = $('#myCodeInputId').val();
if (code !== '') { // checking if input is not empty
$.ajax({
url: './my/php/file.php', // php file that communicate with your DB
method: 'GET', // it could be 'POST' too
data: {code: code},
// code that will be used to find your product name
// you can call it in your php file by "$_GET['code']" if you specified GET method
dataType: 'json' // it could be 'text' too in this case
})
.done(function (response) { // on success
$('#myProductNameInput').val(response.product_name);
})
.fail(function (response) { // on error
// Handle error
});
}
});
});
PHP FILE:
// I assumed you use pdo method to communicate with your DB
try {
$dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
exit('ERROR: ' . $e->getMessage());
}
$sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
$result = $dbh->prepare($sql);
$result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
$result->execute();
if($result->rowCount()) { // if you got a row from your DB
$row = $result->fetchObject();
echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
// if we use text method in ajax, we simply echo $row
}
else {
// handle no result case
}
I know what you want to do, but without specific code the best I can do is give you a generalized answer.
When a user fills out a field, you want to post that field to the server, look up a product and return some stuff.
The basics are going to look like this.
$(document).ready( function(){
//rolling timeout
var timeout;
$('#field').on('keyup', function(e){
if(timeout) clearTimeout(timeout);
timeout = setTimeout( function(){
var data = {
"field" : $('#field').val()
};
$.post( '{url}', data, function(response){
if(response.debug) console.log(response.debug);
if(response.success){
//open other form
$('{otherFormProductField}').val(response.product);
}
}); //end post
},450); //end timeout
});//end onKeyup
}); //end onReady
Then in PHP, you have to process the request. Pull the field from the $_POST array, look it up in the Database. Then build a response array and send it back to the client as JSON. I like to build responses in a structure something like this.
{
success : "message", //or error : "message"
debug : "",
item : ""
}
Then in PHP I will do this.
ob_start();
..code..
$response['debug'] = ob_get_clean();
header("Content-type:application/json");
echo json_encode($response);
This way, you can still print out debug info (in side the output buffer calls ) when developing it and don't have to worry about it messing up the Json or the header call.
-note- Use a timeout, that you reset on each key press (a rolling timeout). What it does is reset the previous timeout each time the key is released. That way it only sends the request once the user quits typing (instead of sending request on every keypress). I have found 450 milliseconds to be about the perfect value for this. Not too long not too short. Basically once they stop typing for 450ms it will trigger the $.post

Real time chat, message handling - Socket.io, PHP, MySQL, Apache

I am a beginner when it comes to web development. Recently i have been working on a real time chat website based completely on PHP and JS/jQuery (i'm not using any frameworks). Currently, my setup is just simple AJAX polling, which obviously isn't as good as i'd like it to be. My database is a MYSQL database.
I have read about websockets and my new initial plan was to create a NodeJS server with Socket.io which will handle messages (How to integrate nodeJS + Socket.IO and PHP?), and i thought about storing those messages in a MySQL database (MySQL with Node.js).
Here is what i have currently (not much, i'd like to clarify how to progress before i actually do progress). This is my test setup, the HTML used in actual chat is a bit different obviously.
Node.js Server:
// NODE
var socket = require( 'socket.io' );
var express = require( 'express' );
var https = require( 'https' );
var http = require( 'http'); //Old
var fs = require( 'fs' );
var app = express();
//Working HTTPS server
var server = https.createServer({
key: fs.readFileSync('/etc/letsencrypt/live/%site%/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/%site%/fullchain.pem')
},app);
// var server = https.createServer( app ); Won't work cause no cert.
var io = socket.listen( server );
console.log("Server Started");
io.sockets.on( 'connection', function( client ) {
console.log( "New client !" );
client.on( 'message', function( data ) {
console.log( 'Message received ' + data); //Logs recieved data
io.sockets.emit( 'message', data); //Emits recieved data to client.
});
});
server.listen(8080, function() {
console.log('Listening');
});
JS Client script:
var socket = io.connect('https://%site%:8080');
document.getElementById("sbmt").onclick = function () {
socket.emit('message', "My Name is: " + document.getElementById('nameInput').value + " i say: " + document.getElementById('messageInput').value);
};
socket.on( 'message', function( data ) {
alert(data);
});
My super-simple test HTML:
<form id="messageForm">
<input type="text" id="nameInput"></input>
<input type="text" id="messageInput"></input>
<button type="button" id="sbmt">Submits</button>
</form>
PHP requires a bit explanation - At the moment when someone connects to my website i run session_start(). This is because i want to have something like anonymous sessions. I distinguish between logged in and anonymous users through $_SESSION variables. An anon user will have $_SESSION['anon'] set to true, as well as will NOT have $_SESSION['username'] set. Logged in user will obviously have it inverted.
When it comes to the chat - it's available to both logged in users as well as anonymous users. When user is anonymous, a random username is generated from a database or random names. When user is logged in, his own username is chosen. Right now my system with Ajax polling works like this:
User inputs the message (in the current chat solution, not the testing HTML i sent above) and presses enter and an AJAX call is made to following function:
function sendMessage($msg, $col) {
GLOBAL $db;
$un = "";
if (!isset($_SESSION['username'])) {
$un = self::generateRandomUsername();
} else {
$un = $_SESSION['username'];
}
try {
$stmt = $db->prepare('INSERT INTO chat (id, username, timestamp, message, color) VALUES (null, :un, NOW(), :msg, :col)');
$stmt->bindParam(':un', $un, PDO::PARAM_STR);
$stmt->bindValue(':msg', strip_tags(stripslashes($msg)), PDO::PARAM_STR); //Stripslashes cuz it saved \\\ to the DB before quotes, strip_tags to prevent malicious scripts. TODO: Whitelist some tags.
$stmt->bindParam(':col', $col, PDO::PARAM_STR);
} catch (Exception $e) {
var_dump($e->getMessage());
}
$stmt->execute();
}
(Please don't hate my bad code and crappy exception handling, this is not any official project). This function inputs users message to the database.
To recieve new messages, i use setTimeout() function of JS, to run an AJAX check every 1s after new messages. I save the ID of last message that is displayed in JS, and send that ID as a parameter to this PHP function (and it's ran every 1s):
/* Recieve new messages, ran every 1s by Ajax call */
function recieveMessage($msgid) {
//msgid is latest msg id in this case
GLOBAL $db;
$stmt = $db->prepare('SELECT * FROM chat WHERE id > :id');
$stmt->bindParam(':id', $msgid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return json_encode($result);
}
The question is: How to implement something similar, but with my earlier mentioned setup of node.js server and websockets? I need to distinguish between logged in and anonymous users somehow. My first idea was to just run an ajax call from node.js server to PHP and pass message data, and PHP will insert it into DB exactly as it does right now. But the problem in this case is how to send the message out to the clients again? Usernames are applied while the message is being input into database, that means i'd have to call AJAX to save to the DB, and then call another AJAX to extract the newly input message and emit it to the clients, or make a function that inserts and extracts and returns extracted message. However, won't that cause problems when 2 messages are input at the exactly same time?
Is it somehow possible to access PHP session variables in Node.js? Then i could rewrite all DB querying to work in the Node.js server instead of PHP.
I apologize once more if my code or explanation is messy.
SO, for everyone that is wondering and will find this thread in the future: I DID NOT FIND AN ANSWER WITH THE SOLUTION I WANTED TO USE, HOWEVER I CAME UP WITH SOMETHING ELSE, AND HERE IS A DESCRIPTION:
Instead of making Node.js server send the AJAX request, i left it as i had before, the jQuery $.post() request from the client, to a PHP function.
What i did next was to implement a MySQL listener, that checked the MySQL binlog for changes. I used mysql-eventsmodule. It retrieves the newly added row with all data and then uses socket.io emit function to send it to connected clients. I also had to drop SSL because it apparently hates me. It's a small hobby project, so i don't really have to bother that much with SSL.
Best solution would be obviously to program the whole webserver in Node.js and just drop Apache completely. Node.js is awesome for real time applications, and it's a very easy language to learn and use.
My setup of Node.js + Socket.io + mysql-events: (ignore the unused requires)
// NODE
var socket = require( 'socket.io' );
var express = require( 'express' );
var https = require( 'https' );
var http = require( 'http');
var fs = require( 'fs' );
var request = require( 'request' );
var qs = require( 'qs' );
var MySQLEvents = require('mysql-events');
var app = express();
/*Correct way of supplying certificates.
var server = https.createServer({
key: fs.readFileSync('/etc/letsencrypt/live/x/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/x/cert.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/x/chain.pem')
},app); */
var server = http.createServer( app ); // Won't work without cert.
var io = socket.listen( server );
console.log("Server Started");
//DB credentials
var dsn = {
host: 'x',
user: 'x',
password: 'x',
};
var mysqlEventWatcher = MySQLEvents(dsn);
//Watcher magic, waits for mysql events.
var watcher = mysqlEventWatcher.add(
'newage_db.chat',
function (oldRow, newRow, event) {
//row inserted
if (oldRow === null) {
//insert code goes here
var res = JSON.stringify(newRow.fields); //Gets only the newly inserted row data
res.charset = 'utf-8'; //Not sure if needed but i had some charset trouble so i'm leaving this.
console.log("Row has updated " + res);
io.sockets.emit('message', "[" + res + "]"); //Emits to all clients. Square brackets because it's not a complete JSON array w/o them, and that's what i need.
}
//row deleted
if (newRow === null) {
//delete code goes here
}
//row updated
if (oldRow !== null && newRow !== null) {
//update code goes here
}
//detailed event information
//console.log(event)
});
io.sockets.on( 'connection', function( client ) {
console.log( "New client !" );
client.on( 'message', function( data ) {
//PHP Handles DB insertion with POST requests as it used to.
});
});
server.listen(8080, function() {
console.log('Listening');
});
Client JavaScript SEND MESSAGE:
$('#txtArea').keypress(function (e) {
if (e.which == 13 && ! e.shiftKey) {
var emptyValue = $('#txtArea').val();
if (!emptyValue.replace(/\s/g, '').length) { /*Do nothing, only spaces*/ }
else {
$.post("/shana/?p=execPOST", $("#msgTextarea").serialize(), function(data) {
});
}
$('#txtArea').val('');
e.preventDefault();
}
});
Cliend JavaScript RECIEVE MESSAGE:
socket.on( 'message', function( data ) {
var obj = JSON.parse(data);
obj.forEach(function(ob) {
//Execute appends
var timestamp = ob.timestamp.replace('T', ' ').replace('.000Z', '');
$('#messages').append("<div class='msgdiv'><span class='spn1'>"+ob.username+"</span><span class='spn2'style='float: right;'>"+timestamp+"</span><div class='txtmsg'>"+ob.message+"</div>");
$('#messages').append("<div class='dashed-line'>- - - - - - - - - - - - - - - - - - - - - - - - - - -</div>"); //ADD SCROLL TO BOTTOM
$("#messages").animate({ scrollTop: $('#messages').prop("scrollHeight")}, 1000);
});
});
Somehow, the binlog magic destroys the timestamp string, so to clean it up i had to replace a bit of the string itself.
PHP DB INSERT FUNCTION:
function sendMessage($msg, $col) {
GLOBAL $db;
$un = "";
if (!isset($_SESSION['username'])) {
$un = self::generateRandomUsername();
} else {
$un = $_SESSION['username'];
}
try {
$stmt = $db->prepare('INSERT INTO chat (id, username, timestamp, message, color) VALUES (null, :un, NOW(), :msg, :col)');
$stmt->bindParam(':un', $un, PDO::PARAM_STR);
$stmt->bindValue(':msg', strip_tags(stripslashes($msg)), PDO::PARAM_LOB); //Stripslashes cuz it saved \\\ to the DB before quotes, strip_tags to prevent malicious scripts. TODO: Whitelist some tags.
$stmt->bindParam(':col', $col, PDO::PARAM_STR);
} catch (Exception $e) {
var_dump($e->getMessage());
}
$stmt->execute();
}
I hope this helps someone at least a bit. Feel free to use this code, as i probably copied most of it from the internet already anyway :) I will be checking this thread from time to time, so if you have any questions leave a comment.

Passing an array from PhP to jQuery using JSON and $.ajax

First off, I apologise since this is my first time working with JSON.
My website has a client script that requests person data from the server. The server first queries the database (using mysql and mysqli) and then returns the data (names, ages, etc.) to the client side.
Specifically, I want to pass an associative array from the PhP side to the client side.
After doing some research, I decided to do this with AJAX JSON calls.
The client side call is done like this:
var person_id = $('#my_text_box').val();
$.ajax({
url: 'php/upload/my_server_script.php',
method: 'POST',
data: {id: person_id},
dataType: 'json',
cache: false,
success: function(response_data)
{
alert(response_data['name']); //The server should return an associative array
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log(jqXHR.responseText);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
The server side calls a method that will query the database and give the details of the person with the requested ID.
$id = $_POST['id'];
function getPersonData($id)
{
$personData = array();
(1 - Connect and SELECT name FROM Persons WHERE id = {$id}
2 - Fill the $personData array with result row
3 - Name will be saved in $personData['name'])
return json_encode($personData);
The AJAX call fails with the error 500 - Internal Server Error. When I check the contents of the server response on the browser (On Chrome, Network tab), it says there is no response (This request has no response data available).
The thing is, this code works perfect locally. But when I upload it to my cloud web server, the only AJAX calls in my website that fail are the ones that use JSON as the format for the data being transferred. The other ones work fine.
A couple of things I've tried:
First, checking if the array on the PhP side is empty or built with errors. It's not, all the correct values are there;
Second, including application/json to the cloud web server mime.type file (It's Apache);
Then, including a header('Content-Type: application/json'); in my server-side script.
Also, adding "contentType: 'application/json' " to the client-side $.ajax.
None of these four worked. What could I be forgetting?
Note: The browser's log reads as follows:
Arguments[3]
0: Object
1: "error"
2: "Internal Server Error"
callee: function (jqXHR, textStatus, errorThrown)
length: 3
__proto__: Object
*(url of my script file)*
Error: Internal Server Error error [object Object] ^
Note #2: Full PhP code:
//Fetch persondata for a specific ID, and encode the data in an array in JSON format
function JSONSelectPersonDataFromID($ID)
{
$personData = array(); //Array or array with results
//If querysuccess, commit. Else, rollback
$querySuccess = True;
//This method opens connection with root user
$conn = OpenDBConn();
$conn->autocommit(False);
try
{
if($videoID > 0)
{
$sql = "SELECT name FROM Persons WHERE id={$id}";
//Debugging
//echo $sql . "<br>";
$persons = mysqli_query($conn, $sql);
if(mysqli_connect_errno($conn))
{
$querySuccess = False;
}
if(isset($persons ) && (count($persons ) > 0))
{
//Loop through every scene
$personData = $persons ->fetch_array(MYSQLI_ASSOC);
}
else
{
return null;
}
}
else
{
$querySuccess = False;
}
}
catch(Exception $e)
{
$querySuccess = False;
}
if(!$querySuccess)
{
//Rollback
$conn->rollback();
die("Transaction failed");
}
else
{
//Commit
$conn->commit();
}
//Close the connection
DBClose($conn);
return json_encode($personData );
}
"Internal server error" means the server crashed somewhere but for security reasons the client only get that 500 error. Check the server's error log file, there should be the real origin of the error (some real error, file and line number). You should start there.
Does the PHP script that uses AJAX have permissions to read the other PHP Script?

AngularJS: cannot POST to server PHP file (getting 404)

Hi All and thanks for your time!
I am new to AngularJS and currently working on my first form with server side part.
I am running on VirtualBox, used Yeoman to set up.
my HTML has 2 fields: username and password, that are in turn passed to the js file:
function authUsers($scope, $http) {
$scope.url = '../api/authUsersService.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.loginAttempt = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
alert($scope.session.username);alert($scope.session.password);
$http.post($scope.url, { "username" : $scope.session.username, "password" : $scope.session.password}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
alert(data);
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert(data);
alert(status);
});
};
}
I am getting the 2 alerts (username, password).
This file and the HTML itself is under Angular's APP folder. outside the folder, in the same containing folder: I created 'API' folder. this is the file api/authUsersService.php:
<?php
$data = file_get_contents("php://input");
$objData = json_decode($data);
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "select userID from authUsers where username = " . $objData->username . " and password = " . $objData->password);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row["userID"];
} else {
echo "";
}
?>
when the HTML form is submitted, i am getting all the alerts from the controller (js file), including the ".error" ones. the data i am getting inside the error: "cannot post to /api/authUsersService.php" and the status is "404".
i couldn't find any solution. tried an .htaccess in the var\www\http folder, didnt help.
please help me successfully get to the PHP server code!
thanks!
Using "../" in a URL is a good indicator you're doing something wrong.
You can't go "outside" the root directory of your webserver, so you need to put it inside the "app" directory, so that it's web accessible.

getting error when i send the textfield value through ajax request to php using sencha touch

my view contains the following code
this.keypadDisplay = Ext.create('Ext.field.Text', {
xtype:'textfield',
disabled: true,
value: ''
});
my ajax request code is
handler: function(b, e) {
var thisUser = this.getValue();
alert(thisUser);
//params[this.getSubmitParamName()] = this.getValue();
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: thisUser,
method:'GET',
success: function(response, opts){
var text = response.responseText;
console.log(response.responseText);
alert(thisUser);
//alert(this.getValue());
//alert('Value: ' + this.getValue());
Ext.Msg.alert('success', text);
},
failure: function(response, opts){
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
}
here i'm getting the "this.getValue" successfully. i want to insert to this.getValue to the code table.
my code.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('form',$con);
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisUser.value']."')";
if(mysql_query($insert))
{
echo('values inserted successfully');
}
else
{
echo('failure' . mysql_error());
}
?>
here im getting the error as "Undefined index:thisUser.Value in .../keypadapp/code.php " on line 5.
can anyone help me to ? thanks in advance...
Assign param value to variable in ajax call:
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: 'thisuser='+thisUser,
Then in php, access the value:
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisuser']."')";
Try changing $_GET['thisUser.value'] to $_GET['thisUser_value'] dots in $_GET and $_POST get converted to underscores in PHP. See this for more info https://stackoverflow.com/a/68742/589909
Update
Looking closer at your code you can't get javascript values of an object in php like you are doing. I assume that thisUser is an object. So when passing it as a param its properties will be posted to the server individually. So if it had a property called foo you would get it like so. $_GET['foo']; also you could dump the get request to see what was sent. var_dump($_GET);

Categories