Working with NXT API using Ajax PHP and Javascript - javascript

So I am trying to create my own BlockChain website using NXT API. They have listed the possible operations you can make on their website but there is no source code at all. After hours searching I found this project on github, It's the NXT API implemented in Node.js and also he explains how to use it in the browser I managed to make it work on my website but many functions of his API are not updated and didn't work for me. So I had to do it from scratch based on the php example from NXT page.
I am going to explain how I am trying to run that php function from my HTML page
Following the answer of calling a PHP function with AJAX, I created a PHP file called getGuaranteedBalance.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'get_guaranteed_balance':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$server= $_POST['arguments'][0];
$accno= $_POST['arguments'][1];
$number_of_confirmations= $_POST['arguments'][2];
$command = "nxt?requestType=getGuaranteedBalance&account=$accno&numberOfConfirmations=$number_of_confirmations";
$data = file_get_contents($server . $command);
// example results: {"guaranteedBalance":2700000}
$obj = json_decode($data);
$guaranteed_balance = $obj->{'guaranteedBalance'}; // nxt cents
$guaranteed_balance = floatval($guaranteed_balance) / 100.0; // nxt
$aResult['result'] = $guaranteed_balance;
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
And this is how I call it using AJAX from my HTML page:
<script language="javascript">
jQuery.ajax({
type: "POST",
url: 'Functions/getGuaranteedBalance.php',
dataType: 'json',
data: {functionname: 'get_guaranteed_balance', arguments: ["http://localhost:6876", "2488827424806206243", 50]},
success: function (obj, textstatus) {
console.log("Hii "+obj.result.toString());
if( !('error' in obj) ) {
console.log("Hiiiiiiiii"+obj.result.toString());
} else {
console.log(obj.error);
}
}
});
</script>
On the console, the only message I get is: XHR finished loading: POST "http://localhost:6876/getGuaranteedBalance.php" jquery.min.js:4 actually it should return the balance value which is 974400000000.
I have tried everything changing the parameter to data instead of variables obj or adding alerts everywhere but nothing worked. When I access from browser doing the request manually the request works which means the problem is in the code...
REQUEST:
http://localhost:6876/nxt?requestType=getGuaranteedBalance&account=2488827424806206243&numberOfConfirmations=60
It would be really helpful if someone has a better Idea of implementing this API or if you know one already implemented please share it.

Related

How to fix success problem while getting data from php to javascript file?

I have used before these jquery-ajax and php codes. Everything was fine but know there is a problem that success function not working. However, php codes are working, I can add data to mysql database, but I couldn't post info back to javascript file again by use "echo" or any way. Is this problem could originate because of server? I need your support.
I have checked php file is working or not and there was no problem about php. In javascript file in ajax codes, I have tried beforeSend and complete functions, everything were fine. But success function not working.
JS codes:
var userCookie = 1;
var question_txt = document.getElementById("question_txt").value;
var category_slct = document.getElementById("category_slct").value;
$.ajax({
type: "POST",
url: websitePHP + "ask.php",
data: {
user : userCookie,
quest : question_txt,
cat : category_slct
},
beforeSend: function(){
},
success: function(data){
alert(data);
if(data == 'ok'){
alert('Question added');
}
}
})
PHP codes:
include("ayar.php");
$userID = $_POST['user'];
$categoryID = $_POST['cat'];
$question_txt = $_POST['quest'];
$askedTime = time();
$addQuestion = $vt->prepare("INSERT INTO ".$QUESTIONS." (userID, categoryID, question, image, link, sight, pinned, bestAnswerID, askedTime, publishedTime, published)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$addQuestion->execute(array(''.$userID.'',''.$categoryID.'', ''.$question_txt.'', '', '', 0, 0, '', ''.$askedTime.'', '', 0));
echo 'ok';
exit();
I need to get back response from php to js by success function in ajax.
Thanks for your help,
Best regards.
Can you try
return 'ok'; instead of echo 'ok'; and removing exit(); function

Ajax call to submit text into database don't work

I have a page where users can put comments below photos, everything works fine in php, comments go to the database and displayed below the photo.
Now I'm trying to make it work with ajax but I have some troubles.
I have an javascript document with this:
$(document).ready(function(){
$("#btnSubmit").on("click", function(e){
var update = $("#activitymessage").val()
$.ajax({
method: "POST",
url: "./ajax/save_comment.php",
//data: { update: update}, - first version, not correct
data: { activitymessage: update},
datatype: 'json'
})
.done(function(response) {
console.log("ajax done");
console.log (response.message);
var ht = "<li>" + update + "</li>";
$("#listupdates").append(ht);
});
e.preventDefault();
});
});
The php page (save_comment.php) where I tell what to do with the input text:
<?php
spl_autoload_register(function ($class) {
include_once("../classes/" . $class . ".class.php");
});
$activity = new Comment();
if (!empty($_POST['activitymessage'])) {
$activity->Text = $_POST['activitymessage'];
try {
//$activity->idPost = $_GET['nr'];
//$activity->idUser = $_SESSION['user_id'];
// with this it works, but not yet correct
$activity->idPost = 66;
$activity->idUser = 3;
$activity->SavePost();
$response['status'] = 'succes';
$response['message'] = 'Update succesvol';
} catch (Exception $e) {
$error = $e->getMessage();
$response['status'] = "error";
$response['message'] = $feedback;
}
header('Content-type: application/json');
echo json_encode($response);
}
There is also the file Comment.class.php with the 'Comment' class and the function SavePost(). This works without ajax, so I assume the function is correct.
What works
the comment (var update) is printed on the screen into the list.
The console says : "ajax done"
What don't work
The input text don't insert into the database (and disappears when page refresh)
The console says: "undefined" (there must be something wrong with the 'response I use in this function)
I hope you guys can help me out. Thanx
update
I changed the: data: { activitymessage: update} line in the js file, and set manually values for the $activity->idPost = 66; $activity->idUser = 3; And everything works !
Only one thing I want to get fixed
the values of the $_GET['nr'] and $_SESSION['user_id'] are now set manually. Is this possible to get these automatic?
The $_GET['nr'] is the id of the page were the photo is and the comments. In this way I can make a query that returns all comments for this page.
The $_SESSION['user_id'] is the id of the user,so I can echo the username and profile photo.
You are sending data with the key being update not activitymessage
Change data to:
data: { activitymessage: update}
Or change $_POST['activitymessage'] to $_POST['update']
Also you have no $_GET['nr'] in url used for ajax. Nothing shown would help us sort that out but you would need the url to look more like:
url: "./ajax/save_comment.php?nr=" + nrSourceValue,
Not sure why you need to use $_GET['nr'] and don't use $_POST for that also and and nr property to data object being sent

Getting undefined on my Ajax call

I'm getting undefined in the console when trying to log the "data.billAmount" statement. Why is this happening and how do I fix it?
I tried doing JSON.parse and JSON.stringify but those didn't work. I tried using dataType: 'json' but that didn't work. I'm not sure what else to try. I'm stuck.
PHP:
if (#$_POST['action'] == 'addBill')
{
$billName = $_POST['bill_name'];
$billAmount = intval($_POST['bill_amount']);
$data = array(
'billName' => $billName,
'billAmount' => $billAmount,
);
echo json_encode($data);
$stmt = $db->prepare("INSERT INTO bills (billName, billAmount) VALUES(?,?)");
$stmt->bindParam(1, $billName);
$stmt->bindParam(2, $billAmount);
$stmt->execute();
}
JavaScript:
$(".addBill").on("click", function(e) {
e.preventDefault();
var billAmount = $('.billAmount').val();
var billName = $('.billName').val();
$.ajax({
type: "POST",
url: "index.php",
data: {
billAmount: billAmount,
billName: billName,
action: 'addBill'
},
success: function(data) {
console.log(data.billAmount);
}
});
});
Suggest you to move functionality which is responsible for adding bill into separate file. Then make AJAX call to that file and everything would works well, because if you want a particular value point request to particular file which echo that value for you...
No needs to looking for workaround when that could be done in clear and right way by separating functionality into smaller junks.
In case if you insist to use index.php
after
$stmt->execute();
put one more line
exit();
As Mohamed-Yousef commented on question.

Server is crashing

I am running a longpolling script to grab data from the database. It was working fine until moving my script to an MVC.
I have viewed the chrome developer tool and it's showing nothing in there, but the page just carries on loading, and when I go to refresh it won't load, I have to shut down my xampp server or close my browser... Here's my script:
class SystemController extends Controller
{
public function lastbid()
{
set_time_limit(0);
// main loop
while (true) {
//get the product info
$getbidresult = ProductModel::bidprice(Request::get('item'));
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = Request::get('timestamp');
// get timestamp of when file has been changed the last time
$lastbid = isset($getbidresult->timestamp) ? $getbidresult->timestamp : 0;
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $lastbid > $last_ajax_call) {
// put last bid info into an array
$result = array(
'bidamount' => isset($getbidresult->amount) ? System::escape($getbidresult->amount): 0,
'timestamp' => System::escape($lastbid)
);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep(10);
continue;
}
}
}
}
This is how I am grabbing the data with JS.
function getContent(timestamp)
{
var queryString = {
'timestamp': timestamp
};
$.ajax(
{
type: 'GET',
url: '<?php echo Config::get('URL'); ?>system/lastbid?item=<?php echo System::escape($recentitem->id); ?>',
data: queryString,
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#bidprice-<?php echo System::escape($recentitem->id); ?>').html(obj.bidamount);
getContent(obj.timestamp);
}
});
}
$(function()
{
getContent();
});
$(document).ready(function() {
});
I've looked in apache logs with no avail unless I am looking in the wrong place. Does anything in the code look out of place, It doesn't to my knowledge but I may be overlooking something.
I have the script in a foreach, so I can initiate the div, for each product.
Edit, viewed apache and mysql logs and it showing nothing. Could it be a memory leak?
I think I have fixed it with the help of someone from an external website. It was to do with the sleep()
I have fixed it using:
session_write_close();
I will do more testing to see how it hold up before reporting back. With the reason why etc.

A Better way of doing Fade Out with PHP

I amc creating A Login script with php and javascript.
What I want to do is log the user in without the page refresh which I have archived so far, With some help from Stack Flow users, I am fairly good with PHP but new to the Javascript client side.
Anyway, When the user enters the correct data and the session gets started how do I get it to call the fade out function?
Heres the PHP Side
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
echo "
Yes, Now we can start the session right here, when your ready.
<script>
$('#field').fadeOut();
</script>";
} else {
echo "The username or password you entered is incorrect";
}
} else {
echo "<b>Blank Fields</b> <br>
You must enter A Username/Password Combination";
}
?>
Incase yous need it, there is the client side aswill (modified by some users to make the functionality better)
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Since PHP is Server Side and Java Script controls the Client side, Probably the best way to do or call it is this way, But its worth A ask anyway.
Besides this everything is working out well.
If you want you can help change the way loading data is coded/works, But the functionality is working perfectly so theres not much need.
The ajax success method needs to check the response from the server to see if login was successful and then take the appropriate action:
// php
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
echo 'correct';
} else {
echo 'The username or password you entered is incorrect';
}
// js
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
if (data === 'correct') {
$('#field').fadeOut();
} else {
$('#content').html(data);
}
}
});
}
Returning JSON instead of raw HTML is much more flexible. Quick example:
PHP Side
<?php
require "../core/database.php";
$json = array('success' => false, 'error' => null);
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
$json['success'] = true;
}
else {
$json['error'] = "The username or password you entered is incorrect";
}
} else {
$json['error'] = "<b>Blank Fields</b> <br>You must enter A Username/Password Combination";
}
echo json_encode($json);
Your AJAX function:
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
var loginResult = JSON.parse(data);
if(loginResult.success){
//Login successful - fade out whatever form or fields
//that you want to
$('#field').fadeOut();
} else{
//Add error message to an error div or whatever
$('#error').html(loginResult.error);
}
}
});
}
I'll start by saying that your PHP should be using the newer mysqli_* functions or the PDO object for all of your database queries. Further, you should be using prepared statements which will safeguard you against SQL injection attacks.
Another thing to note is that in a PHP file that is not going to output anything to the browser, or in other words, is just going to run some code, you don't need a closing tag. In fact, you don't want a closing tag. That is because anything after the closing tag will get sent to the browser, which will get included in the response of your AJAX success function. That includes things like spaces and new lines.
Now, on to your PHP. You are going to want to output some JSON so that you can check for success or failure in your AJAX.
PHP
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
//Create an array to represent our JSON data.
$json = array(
"successCode" => 0
);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//echo "Yes, Now we can start the session right here, when your ready."
$json['successCode'] = 0;
} else {
//echo "The username or password you entered is incorrect";
$json['successCode'] = 1;
}
} else {
//echo "<b>Blank Fields</b> <br>
//You must enter A Username/Password Combination";
$json['successCode'] = 2;
}
//Set that our content type is JSON
header("Content-type: application/json");
echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.
In our PHP, we have created a $json array which will story the successCode that we will be responding to the client. This will tell the client if the login was a success or failure, and even what type of failure occurred. It will then be up to the client to decide how to display that success or failure to the user. This allows multiple applications to use the same server side source, but display the errors differently if desired.
At the end of the PHP, we have set the header Content-type to specify that we are sending back application/json to the client. Then, we encode the PHP array as JSON, and output it to the response.
jQuery/Javascript
//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
"Yes, Now we can start the session right here, when your ready.",
"The username or password you entered is incorrect",
"<b>Blank Fields</b><br />You must enter A Username/Password Combination"
];
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
//First, make sure that data and data.successCode are defined.
if (data && data.successCode) {
//Here, you are getting back the JSON data from the login call.
$('#content').html(errorMessages[data.successCode]);
//If the successCode is 0, which means it was successful, then we want to fade out the #field div.
if (data.successCode == 0) {
$('#field').fadeOut();
}
} else {
//There must've been a server error. You'd handle that here.
}
}
});
}
Why put the error messages on the client instead of the server? Because it allows you to easily change how the error messages are displayed, without having to touch the server side code. The server just outputs an error code, and the client decides how to handle that code.
The Javascript array, errorMessages, defines the error messages corresponding to their index in the array. The error message at index 0 would correspond to successCode = 0, and so on. If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code.

Categories