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);
}
Related
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();
}
}
?>
it may seem stupid, but i'm in it for a week, help me ...
the "response" in xhr dev-tools chrome does not leave "0", it never returns the array I need ...
Javascript code to get data from wordpress
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
$.post("wp-admin/admin-ajax.php", { getHomeSliderSeries: id }, function (html) {
var data = jQuery.parseJSON(html);
if (data.status == "success") {
var listing = data.list;
var lister = [];
for (var i = 0; i < 20; i++) {
var row = listing[i];
lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
}
$list.parent(".itemsList").addClass("fadingOut");
setTimeout(function () {
$list.html(lister.join(""));
$list.trigger("destroy.owl.carousel");
createItemSlider();
$list.parent(".itemsList").removeClass("fadingOut");
}, 200);
} else {
return false;
}
});
});
PHP file to return data in array json to javascript show results in html.
wp-admin/admin-ajax.php (theme/inc/core/ajax.php)
function getHomeSliderSeries(){
// i Want see that bellow in xhr response to javascript:
//{"status":"success","list":{}}
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );
My language is not very good, i hope you undestand, thanks atentiton!!
Try ajax callback function in functions.php
function swt_ajax_data() {
$id = isset($_POST['id']) ? $_POST['id'] : '';
// Create an associative array for the response.
$responsedata = array(
'id' => $id,
);
$result = array();
// if need featch the data from the template un comment the bellow five lines and commented the sixth line
//ob_start();
//include('templatepatj');
//$opr_html .= ob_get_contents();
//ob_get_clean();
// $result['data'] = $opr_html;
$result['data'] = $responsedata;// POST array data.
}
return wp_send_json_success($result);
}
}
add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data');
add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data');
Localize your script and pass the admin ajax url
// Register the script
wp_register_script( 'ajax-script', 'path/to/myscript.js' );
// Localize the script with new data
$js_array = array(
'ajaxurl' => admin_url('admin-ajax.php'),
);
wp_localize_script( 'ajax-script', 'swtobj', $js_array );
// Enqueued script with localized data.
wp_enqueue_script( 'ajax-script' );
Try Js as like below.
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
var data = {
'action': 'swt_ajax_data', 'id': id
};
$.ajax({
url: swtobj.ajaxurl,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (response, textStatus, jqXHR) {
var response_data = response.data.data;
if (response_data != "" || response_data.length != 0) {
console.log(response_data);
// write your code here
} else {
// write your code here
}
},
});
});
The data you send in $.post is missing an action property. This property is responsible for telling the admin-ajax.php which function that is registered with a wp_ajax_{function_name} hook should be called.
The value in the action property should match the function_name in wp_ajax_{function_name} and wp_ajax_nopriv_{function_name} to be called properly.
Combine the action property with other properties that you want to send to the backend to pass the data that you need to send.
// Set the action and get the id.
var action = 'getHomeSliderSeries';
var id = $(this).attr("data-show-home-list-series");
// Create object to send data to backend.
// This must include an action property with
// the name of the function on the backend.
var postData = {
action: action,
id: id,
example: 'Send any data as a property. You can also nest objects and arrays.'
};
$.post("wp-admin/admin-ajax.php", postData, function(response) {
if (response.status == "success") {
console.log(response);
}
}, 'json'); // Expect JSON from the backend. Now you don't need to parse.
Now on the server side your getHomeSliderSeries should be called. All the other properties (action included) can now be accessed through the global $_POST variable with their corresponding keys.
For a response, create an associative array with the data you want to return. This is the equivalent of an object in JavaScript. Encode the array to JSON and send it back. Now the frontend should see an object as a response.
function getHomeSliderSeries(){
// Get the id from the post request.
$id = isset($_POST['id']) ? $_POST['id'] : null;
$example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null;
// Create an associative array for the response.
$response = array(
'status' => 'success',
'id' => $id,
'example' => $example_string
);
// Return the array as a JSON string.
return json_encode($response);
// Cuts connection by stopping the function.
die();
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );
This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.
I'm trying to create a JSON array in PHP that jQuery can use and access but for some reason It doesn't work. I get no error messages on the client side nor in the server logs and if I access enc.php directly, it does work, but I'm not sure if the output is correct (the array format).
What I want:
I would like to access the data with jQuery using data[i][0] for the ID ([i] because it's in a loop), and data[i][1] for the message and so on.
Maybe I'm trying to do this the wrong way, if so please help me by pointing me in the right direction or provide an example.
My code:
The current PHP code:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$fetchedid = $row['id'];
$fetchedkey = $row['chat_key'];
$fetchednonce = $row['chat_nonce'];
$fetcheduser = $row['chat_user'];
$fetchedmsg = $row['chat_msg'];
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
$out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($out);
}
Result:
{"id":297,"msg":"test message","user":"john"}
My jQuery (Ajax) code:
$.ajax({
type: "GET",
url: "enc.php",
dataType: "json",
success: function(data) {
console.log('Update success called');
if (data == 2) {
// No messages to fetch
} else if (data == 3) {
// Cookie Tampering detected
} else if (data == 5) {
$("#chat").remove();
alert("Den här chatten är stängd (tiden har gått ut).");
window.location.href = "/?logout=safe";
}
else {
for (i = 0; i < data.length; ++i) {
var mid = data[i][0];
$.cookie("cmid", mid);
var from = data[i][1];
var msg = data[i][2];
$("#chat").append('<div class="left spotmsg"><div class="chat-avatar pull-left"><img src="/img/them.png" alt="avatar" width="48" height="48"></div><div class="message"><div class="arrow-left"></div><p><strong>#'+from+'</strong></p><p class="txt">'+msg+'</p></div></div>');
}
$('textarea').focus();
$(".chat_area").animate({ scrollTop: $(".chat_area")[0].scrollHeight}, 1000);
}
}
});
You can access object using . notation. To access values use key. for example to access id use data.id. If you have object you can't loop using length.
var mid = data.id; //specify key to access id
$.cookie("cmid", mid);
var from = data.user;
var msg = data.msg;
$("#chat").append('<div class="left spotmsg"><div class="chat-avatar pull-left"><img src="/img/them.png" alt="avatar" width="48" height="48"></div><div class="message"><div class="arrow-left"></div><p><strong>#'+from+'</strong></p><p class="txt">'+msg+'</p></div></div>');
The issue is you are outputting individual JSON strings in your while loop which is not correct because the combined output is invalid JSON. The solution is to build an array and then output the array at the end.
$arr = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$fetchedid = $row['id'];
$fetchedkey = $row['chat_key'];
$fetchednonce = $row['chat_nonce'];
$fetcheduser = $row['chat_user'];
$fetchedmsg = $row['chat_msg'];
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
$out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
$arr[] = $out;
}
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($arr); // encode the final array
Now, your output can contain multiple chat messages and is valid JSON, such as:
[{"id":297,"msg":"test message","user":"john"}, {"id":300,"msg2":"test2 message","user":"john"}]
In the JavaScript, refer to the property names instead of [0], [1] etc:
var mid = data[i].id;
$.cookie("cmid", mid);
var from = data[i].user;
var msg = data[i].message;
the problem stems from the fact that your result is not the json for an array of objects but a simple object, so the line
for (i = 0; i < data.length; ++i) {
never iterates as data does not have a length. you want your result to look like
Result :
[
{"id":297,"msg":"test message","user":"john"}
]
that way it will also hold more than one john ;)
suggestion
so I believe your php should be :
$result = $stmt->get_result();
$out = array();
while ($row = $result->fetch_assoc()) {
//... your code doesn't change here
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
//here we append to $out
$out[] = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
header('Content-Type: application/json');
ob_end_clean();
//echo json_encode($out);// not yet...
}
echo json_encode($out);//but now!
here is my PHP code
$response = array();
$user1 = array();
$user1['name'] = 'Tom';
$user1['age'] = '13';
$user2 = array();
$user2['name'] = 'Jack';
$user2['age'] = '20';
$response[] = $user1;
$response[] = $user2;
echo json_encode($response);
and here is my .html file that use jquery to get data from PHP file like
$.post('file.php', {userid : '1234'}, function(data){
alert(data) //problem here
}, 'json');
the problem is how to get user1's name after I use $.post in that code.
Thank you :)
Because your user arrays are associative, they are being translated into json objects, not arrays.
access them with data[0].name
I think you need JSON.parse
var response = JSON.parse(data)
Now response is your JSON object that has all the data.