jQuery (without $.ajax) $.POST+json retrieves "null" from PHP json_encode - php

My first time writing, but not the first here. I felt forced to ask here because none of those apparently alike questions here were able to give me a clear workaround or solution.
My projects involves a tic-tac-toe game, all jQuery, PHP and log file based. It's working fine, but for every information sent to the txt log, I have to star a new $.post to retrieve the information that will be displayed in different parts of the page, not all in a single list (specially O and X that are retrieved back to their original text element) ...
The game is real-time, multiplayer and is working fine, but is using two txt logs written by PHP which also manages the game: one log keeps the position (filled space) and the other what char was used (X or O). Nice, but I'm calling the two via $.post, storing their data in respective global variables and using them in a setInterval, to update on time for the other player. But as there are many other informations like name and remaining moves (from 9 to 1), I'd like to put everything in a single log, something easier to be retrieved all in a time and be displayed in their respective positions through the game page. My problem (now what I need to get working for now) here is retrieving them from PHP. During tests, I simulate three informations: position, char (O or X) and player's name, put them in an array and echo them with json_encode, as it follows (my jQuery post and then my PHP):
<script type="text/javascript" src="jquery.js"></script>
$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
alert (data); //returns null...
//alert (data.pos); //nothing, script ignores execution
//alert (data[0].pos); //returns null...
//alert (data[1].pos); //returns null...
//alert (data[2].pos); //returns null...
//alert (data[3].pos); //returns null...
//tests above based on some suggestions I'fe found through the web, ineffective...
},"json");
And my PHP:
<?php
//Simulating values being received during the game:
$pos='s3'; //simulation player's move on slot 3
$weapon='O'; //player puts O on slot 3
$name= 'fulano';
//Putting general player info into the array to be used by jQuery:
$coord= array();
$coord['pos']= $pos; //Sets the position where the player put his char
$coord['weapon']= $weapon; //The "weapon" to be put in respective "pos"
$coord['nome']=$name; //Player's name to be displayed during the game
echo json_encode($coord); //encoded json is returning {"pos":"s3","weapon":"O","nome":"fulano"} nicely
?>
Both are post, both using json, jQuery returns something, but is null, PHP echoes alright... $.ajax simply didn't make it either...
What I need: that $.post retrieves every datum so that I can store one by one in their respective global variables, but if alert can't even show one of them coming, something's wrong. Changed every variable names to avoid any kind of conflict, not solved...
I made this test just to make sure PHP json would be clearly gotten by jQuery, what's not happening here. My HTML is using default charset, I'm testing it in localhost, I have the main project working perfectly here, this was a side test to test specifically json response. I simply had no success in using $.ajax ({}) (my jQuery is 1.7.1), no matter what, the script simply stops executing, PHP keeps responding alright here, but jQuery is not giving me what it should other than "null", I've tested it on FF15 and IE8, problem is just with my json routine on jQuery, PHP is working fine and my $.posts here and on the main project, too. What could be going wrong here? Why is it simply returning data as null regardless to what I may try? I thank everyone in advance, I'm just asking because there were no examples here and outside that really gave me the answer, and 99,9% depend on Ajax, but Ibelieve it can be simpler like this.

Add this to your code
$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
$(data).each(function(){
alert(this.s3);
alert(this.0);
alert(this.fulano);
});
},"json");

Valid JSON is as follows: {"key":"value"} not {key:"value"}
Note: All quote encapsulated, not just the value. Hope that helps.

Related

Using RGraph to poll data from a Postgres DB and update using AJAX/JSON

I'm a bit out of depth on this one so I hope someone has some insight. :)
I'm attempting to update a div using AJAX. The AJAX call sends a dropdown selection's value to a PHP file, which will be performing a pgsql query to grab some data. I've read in the RGraph tutorials that this data needs to be formatted to a JSON format so that RGraph can interpret it, and then fed to the JS that runs the RGraph views.
This question might actually be 2 separate questions, but I'll ask anyway:
Is there a standard way to grab the query's results in PHP and output them into a JSON format?
Where would I want to trigger the JS that uses the JSON data? I've tried hardcoding some initial data but the graphs don't seem to show up. However, I know the jQuery is performing the AJAX calls correctly because I see the div update (with an in-between "Loading..." message and then back to blank, indicating to me a null response), so I think I'm just not scoping this properly.
P.S. No, this time I'm not making a $_POST/$_GET mistake.
Any help would be appreciated. Thanks!
EDIT 1: Got this one. It was actually way easier than I thought. Still not scoping properly, however. Any help with how RGraph grabs a JSON object and displays it as a graph, and how to use AJAX to refresh the div with a new graph?
There's some SVG based AJAX demo pages here:
There was a bunch of links to the SVG basic AJAX demos here, but now the demos are no longer online - they are in the download archive. So download it here: https://www.rgraph.net/download.html#stable
There's a JSON documentation page here:
https://www.rgraph.net/svg/docs/the-svg-ajax-functions.html
And the code example from it is this:
<script>
GLOBALS = {};
function draw()
{
RGraph.SVG.AJAX.getJSON('/ajax/getdata.html?json', function (json)
{
if (GLOBALS.bar) {
RGraph.SVG.clear(GLOBALS.bar.svg);
}
GLOBALS.bar = new RGraph.SVG.Bar({
id: 'chart-container',
data: json.data,
options: {
// Add your own options to configure the chart
}
}).draw();
});
}
draw();
</script>
If you follow this example, create a page on your website that gets the data from your database and outputs it like this page does:
https://www.rgraph.net/getdata.html?json
Note that there's no HTML output by that page - just the JSON.
Then you can fetch that page using the RGraph.SVG.AJAX.getJSON() function like the code above does - from your webpage that has the chart on it - eg foo.html
So the foo.html is what would contain that RGraph code above.
And if you wanted it to repeat then you could add a timer so that subsequent fetches update it:
setTimeout(function ()
{
draw();
}, 1000);
I think that covers everything. I've probably left something out though.

jquery callback with php.... just want the value, not redirect

I thought this was going to be rather simple but I'm a bit rusty.
I call this javascript/jquery code:
$.get("plugin.php", {up_vote:surl},
function(data){
//alert(data);
document.getElementById('numvotes').innerHTML = data;
});
......
And when it returns I get the value, which is some number that is returned as a string, then right after the number a long text about redirecting is displayed. How do I get rid of that? I just want the value.
Here is what is returned:
8 (if you are not redirected after 10 seconds, please click here)
What is causing this to redirect? Or, how do I just get rid of that '(if you are ....) text?
You could try using
data = data.match(/^\d{1,}/);
$('#numvotes').html(data);
if the result is always going to be in the same format that you gave in your question.
It is actually your plugin.php sending the redirect text (and probably some other html too). Try to browse directly to plugin.php?up_vote=surl and you'll see what happens.
Furthermore, if you are using jquery anyway, why not change document.getElementById() to:
$('#numvotes').html(data);

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

Someone to explain a part of this jQuery code to me using the dhtmlxcombo plugin

I have this code fragment
var combo = new dhtmlXCombo("combo_zone4", "alfa4", 230);
combo.loadXML("create_store2.php");
combo.attachEvent("onChange", onChangeFunc);
combo.enableFilteringMode(true, "select_store.php");
function onChangeFunc() {
var d=combo.getSelectedValue();
var product=$("#selProduct");
product.find('option').remove();
$.ajax({
url: "select_store2.php",
data: "store=" + d,
My questions are what are those 3 files used for, and why we need three different files to be called.
Fragment 1:
combo.loadXML("create_store2.php");
create_store2 seams it returns some XML data, some <option> tags.
Fragment 2:
combo.enableFilteringMode(true, "select_store.php");
select_store seams it returns some XML data, some <option> tags.
Fragment 3:
url: "select_store2.php",
select_store2 seams it returns some JSON data, this is probably the result of the autocomplete call.
I never used the dhtmlx components but the API does give off some serious red flags, data can really only be loaded with xml responses ?
Here's what I gathered from the API.
loadXML loads additional options from an XML file (i take it you can set these in script too)
enableFilteringMode enables suggestions as you type, i think the create_store2.php call in loadXML gives the combo also its initional data set.
the jquery ajax call I presume changes the contents of a combo box with the values supplied by select_store2.php filtered by the selected value of combo but i'd need to see the rest of the code to know for sure. Since this is jquery this data is returned in json and I presume manually processed later on in the code.

Using Ajax to Send Data Back to the Server

I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.

Categories