I have a global variable that I want to pass into Ajax. Ajax is very new to me and I've done some research and testing but I am stuck. I don't know if the variable is being passed into the Ajax function for my first question.
I'm not really interested in Json, however I did also make an attempt with that and it's not correct either.
I am not looking to get a response from the php back to the page, the page is updating using the existing js and html.
My second dilemma is that my php file is being activated when it should, however it's posting 0 into the database field. Another problem here too is that it's updating all users money to this same 0 entry so some how it's isset is not set correctly yet. I believe my bindValue is coded correctly, I am really unsure if I need to break down the POST to the php page and if so if I have to use the value, how would I do that? Also when I add WHERE userid = userid to UPDATE the game stalls completely.
Any help even a small fix would be greatly appreciated.
Here are the files. Thank you in advance for helping me get my head around Ajax.
game.js
money = 2000;
function updateMoney() {
if ( pot <= 0 ){
if ( money <= 0 ){
document.getElementById("aaa").innerHTML = "Lost? Here's A Loan !!!";
money = 1000 ;}
}
document.getElementById("money").innerHTML = money;
}
function enterWager(){ // doMath function inside here
var x=parseInt(document.getElementById('textbox').value,10); // Displays the textbox for placing a
wager
if (money <= 0) {
x = 0 ; }
document.getElementById("bet").innerHTML = parseInt(x,10);
if(isNaN(x)||x < 1 || x > 250)
{
document.getElementById("aaa").innerHTML = "You're Out Of Money!!!";
}
document.getElementById("textbox").style.display = 'none';
document.getElementById("button").style.display = 'none';
function doMath() { // PVPCoinTransaction() and
transferCoins() are off right now. Plus 4 tests failed
and
are also off at end of function.
if (pot == 0){
countWagers = 0;
}
if (money <= 0) {
money = 0 ; }
if (x > money) {
x = money ; }
money = money - x;
pot = pot + x;
}
doMath()
function updateDatabase() {
// POST test not working
// $.ajax({
// url: 'php/credits/credit.php', //
// type: "POST",
// dataType:'json', // add json datatype to get json
// data: ({money: 145}), Do I put div here and how?
// success: function(data){
// I dont need to return anything, just update db field!
// }
//});
// this section reaches php but posts 0 into database field
//data = money // I don't think this is working.
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.open("POST", "../php/credits/credit.php", true);
xml.setRequestHeader("Content-type", "application/x-
www-form-urlencoded");
xml.send(money);
}
updateMoney()
updateDatabase()
credit.php
<?php
session_start();
if(empty($_SESSION['userid'])) // check user login
{
header("Location: ../login/index.php");
}
include('../../login/database.php');
if (isset($_SESSION['userid'])) {
// $money = null;
// $money = $_POST['money'];
try {
$db = DB();
header("Content-Type: application/json");
$stmt = $db->prepare("UPDATE usersystem SET money=:money");
$stmt->bindValue(':money', $_POST['money'], PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
?>
Your server expects a key called money in your $_POST array. This means that in order to receive the data properly you need to send the data with a key as well. In PHP this data looks like an associative array and in JavaScript as an object, both having keys and values.
The easiest way to accomplish a key-value structure is to create a string with a key=value structure. This is similar to how forms send their data to servers and requires no modification on the backend for receiving the data.
var package = `money=${money}`;
There is nothing wrong with XMLHttpRequest (there is with ActiveXObject ;) ), I would recommend to learn the Fetch API. It is an updated and simplified specification of making HTTP requests to and from the server. You've indicated that you don't need to receive a response, that means that a basic POST request with sending data looks like the example below.
fetch('../php/credits/credit.php', {
method: 'POST',
body: package
});
The first parameter is the URL, the second an options object. The method property speaks for itself. The body property is the data you're sending (comparable to xml.send(package);).
Now if your URL is correct then an HTTP request with the correct data should be send to your server.
// $_POST should have received data, and because you've send it as a
// key-value it will be represented as an associative array with,
// you guessed it, keys and values.
$money = $_POST[ 'money' ];
// $money will always be a string in this form, so you'll
// need to convert it if you need it to be a number.
$money_as_number = intval( $money );
To test if this works open the network tab in the developer tools of your browser. You can check if an HTTP request occurs and checkout if the correct payload has been sent.
Okay so this is what works in the console ...
function updateDatabase() {
var package = money;
console.log(package);
fetch('../php/credits/credit.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(package)
});
}
console log = 1975 game.js:1608:9
I just need the 1975 value to post to the database via my php now. it's still posting 0 into my database.
I solved it. Thank you for setting me on the right path!
<?php
session_start();
if (isset($_SESSION['userid'])) {
$money = json_decode(file_get_contents('php://input'), true);
$money_as_number = intval( $money );
$userid = $_SESSION['userid'];
try {
$db = DB();
$stmt = $db->prepare("UPDATE usersystem SET money=:money WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_INT);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
?>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
hey i want to crawl data from the site with this code (js)
var i = 0
var oldValue = -1
var interval = setInterval(get, 3000);
function get(){
var x= $($('.table-body')[1]).find('.h-col-1')
if(i!=5){
if(oldValue != x){
oldValue = $(x[1]).text()
console.log($(x[1]).text())
++i
sendPost($(x[1]).text())
}
}else clearInterval(interval)
}
function sendPost(par) {
var te= $.ajax({
type: "POST",
dataType: 'jsonp',
url: 'http://localhost/sa.php',
data: {json:JSON.stringify({
num : par
}) },
}).done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
console.log(xhr.responseText);textStatus
});
console.log(te)
send data from localhost and save on my sql and this php code
sa.php
<?php
header('Access-Control-Allow-Origin: *');
$sitename = "http://localhost/";
$hostname = "localhost";
$username = "root";
$password = "";
$database = "db";
$connect = mysqli_connect($hostname, $username, $password, $database);
$insert = "INSERT INTO main(number, time, date) VALUES ('%s','%s','%s','')";
$data = json_decode(file_get_contents("php://input"), true);
$result = mysqli_query($connect,sprintf($insert,$data['num'] ,date("H:i:s"),date("Y-m-d")));
?>
and then
success send from js request from local server why dosen't save on the my sql ??
I think the answer lies into your insert query:
$insert = "INSERT INTO main(number, time, date) VALUES ('%s','%s','%s','')";
Please count the number of columns defined and the number of values you're trying to insert. These two should, obviously, match.
If you wish to figure out why a MySQL query failed, just print or log the error:
http://php.net/manual/en/mysqli.error.php
You should check the value of file_get_contents("php://input").
As you are sending a key-value pair:
data: {json:JSON.stringify({
num : par
}) },
you should get the data using $_POST['json'].
So:
$data = json_decode($_POST['json'], true);
The alternative, change the javascript instead of the php, would be something like:
data: JSON.stringify({
num : par
}),
But to be honest, I don't know how jQuery will handle that data so it might need some tweaking.
Apart from that, you have an sql injection problem; you should use prepared statements with bound parameters instead.
I'm having a little trouble figuring out how to fix this error I'm getting. My code is as follows.
It all starts with a AJAX request whenever the user moves their mouse on the webpage.
$('body').mouseover(function() {
$.ajax({
url: '/core/home.php',
data: {action: 'refresh'},
type: 'post',
Next, the PHP file (home.php) executes a couple methods to get all the needed data and sends it back to AJAX Request.
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
json_encode($arr);
return $arr;
}
Once the AJAX Request receives a success, the following executes
success: function(output) {
obj = JSON.parse(output);
// Separate the parts of the JSON string
vacs = obj[0];
users = obj[1];
// Show the result at the correct position on the webpage
$('#vac_num').html(vacs);
if(vacs == 1) $('#vac_txt').html('is'); else $('#vac_txt').html('zijn');
$('#users_num').html(users);
if(users == 1) $('#users_txt').html('is'); else $('#users_txt').html('zijn');
}
});
});
Unfortunately this code results into an error: Unexpected end of JSON input.
Any help is much appreciated.
Rather than returning variable you need to echo it
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
echo json_encode($arr);
}
I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!
You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);
Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.
I have this function in php
public function get_updated_session_value()
{
$sql = "SELECT IF(Session = 12345678 , 1,0) AS login FROM `psf_users` WHERE id = 236";
$var = $this->addDb($sql)->execute();
$Session = $var['login'];
return json_encode('2');
}
and the javascript code to fetch this value,
function check() {
$.ajax({
url : 'auctions.php',
type : 'get',
// dataType: 'json',
data : {page:'__request', module:'PSF_auctions', action:'get_updated_session_value'},
success: function(data) {
console.log(data);
}
});
}
also, this function runs every 5 seconds via
setInterval(check, 5000);
the problem is, console.log(data); prints nothing, i believe that means it is not getting any data (or json response) from the php function. am i missing something?
It can't work as you're returning the value. The difference between returning a value and emitting a response is that the latter writes a response on the HTTP stream whilst the first one merely returns the control to the parent with a specific value.
Sanjay has spotted it very well, and I'd recommend that you use a very simple function to wrap up your responses:
function emit_response( $status_code, $data ) {
http_response_code( $status_code ); // 200 is it's success. find more http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
die( json_encode( array(
"status_code" => $status_code,
"data" => $data )));
}
Then modify that echo (though it's fine as well) with
emit_response( 2 );
and since the response is valid JSON, JavaScript will love it; in your callback, you can simple do this:
success: function(res) {
var response = JSON.parse( res );
// response.data will be 2. :)
// ... rest of the code ...
Replace return with echo like this:
public function get_updated_session_value()
{
$sql="SELECT IF(Session = 12345678 , 1,0) as login FROM `psf_users` WHERE id=236";
$var= $this->addDb($sql)->execute();
$Session= $var['login'];
echo json_encode('2');
}
I have two problems. One is totally in PHP the other in Javascript. But both are equal in what I'm trying to get.
index.php
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
success: function(data) {
alert(data);
// Returns: {'status':1}
// I want to get "1"
// data[0] -> doesn't work
}
});
insert_info.php
// Connects to another file
include_once('verify_info.php');
$verify = new verify_info();
$arr = array("status:" => 1);
$extension = $verify->verify_file($_REQUEST['array'][9]);
if($extension[0] == 0){
$arr = array("status:" => 0);
}
echo json_encode($arr);
verify_info.php
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
$arr = array();
if(!in_array($info['extension'], $extensions)){
$arr = array("status:" => 0);
}else{
$arr = array("status:" => 1);
}
return $arr;
}
In insert_info.php, I would like to get by $extension[0] the status retrieved from the function verify_file();
After that I output as json_encode the value to Javascript and I would like, again, to parse the info.
What am I doing wrong? Thanks.
Edit 1: alert(data.status); doesn't work either.
Edit 2: alert(data.status); would never work since I echo {'status:', 1} (problem with that two points in the middle)
Correct way for solving the issue of javascript:
var obj = jQuery.parseJSON(data);
alert(data.status);
I'm still trying to get fixed the php.
Edit 3: All solved. Thank you guys.
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
if(!in_array($info['extension'], $extensions)){
return false;
}
return true;
}
As I said in my comment, your setting your key in PHP to "status:" is the trailing colon necessary on the end of your key? I don't think it's necessary, PHP arrays already offer mechanisms for fetching them and your JSON will contain the string without processing it so your key once you hit your JS code will still be "status:" where most likely you intended for "status".
Regardless of whether you will make this change or not that doesn't break anything. In your Javascript code, as #charlietfl pointed out, you should be setting the dataType of the return to "json" so you're JS Ajax call would look like:
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
dataType: "json",
success: function(data) {
// Assuming no change on the backend
alert(data["status:"]);
}
});
If, however, you altered the string to remove the colon then accessing the status element of data would be data.status as #A.Wolff pointed out in his comment. This doesn't work because of the trailing colon in the key - but accessing the data with a string key will still work.