I am hitting roadblock after roadblock in my quest to get this JSON usable by PHP, so I'm wondering if someone can help me out here.
I have JSON being stored in the variable divisionsJSON:
var divisionsJSON = JSON.stringify(divisions);
Then I try to use .ajax to post with the following:
$.ajax({
url: "divisions.php",
type: "post",
data: divisionsJSON,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
(I copied this from another question on SO, but have nothing in my html with the id="result" - I think I can delete that part [deletion confirmed])
Then, my divisions.php page contains the following:
<?php
$url = "divisions.php";
$json = file_get_contents($url);
$json = utf8_encode($json);
$elements = json_decode($json);
var_dump($elements);
?>
My inexperience with PHP/ajax combined with my frustration with getting this to work has made me try a bunch of different things. So far I've either gotten NULL or nothing when I load divisions.php. My gut tells me that it's a problem with the ajax, but I'm so inexperienced with PHP that I can't say with confidence that my PHP is correct enough to where I should be getting something back. I've tried var_dump, print_r, echo, absolutely nothing is showing up on divisions.php related to the actual PHP/JSON. Any and all help would be greatly appreciated!
Response with updated code:
I am getting NULL with the following php without the utf8 line, and string(0) "" when I added in the utf8 line:
<?php
$json = json_decode(file_get_contents('php://input'));
$elements = utf8_encode($json);
var_dump($elements);
?>
Any ideas?
Edited for full php page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>untitled</title>
<link rel="stylesheet" href="styles/reset.css" />
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="application.js"></script>
<script type="text/javascript" src="divisions.js"></script>
<?php
print_r($_POST);
?>
</body>
</html>
I've tried multiple lines for the php, print_r($_POST);, json_decode($_POST);, etc. but I'm changing so many things based on what I'm seeing on other SO's and this page that I'm really in a daze.
EDIT: Would this code, which I intended to make an array, not produce JSON? Because it doesn't seem like I'm working with JSON atm.
var divisions = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].value != "N/A"){
var obj = { "login": arr[i].login,
"value": "http://www.value.net/index/" + arr[i].value};
divisions.push(obj);}
First of all, when dealing with JSON the best approach is to leave it alone as much as possible. Think if it as fragile goods. Anything you do to it could break it.
With that in mind, don't use stringify() and in fact you don't need to as JQuery will detect it and handle it for you (because they know it's fragile).
Second, the option data: in the $ajax() method needs to be given an object. Generally you would do something like this,
data: {mydata:divisionsJSON}
That way you can access the JSON on the backend via
$json = json_decode($_POST['mydata']);
Or, depending on how you have your divisions array set up, you could post it as the object data: is looking for and access it in PHP via $_POST['divisions_key'] = divisions_value; but that makes for all kinds of issues later and hard links the front end to the back end which is very bad (most of the time, exception is below).
Also, if you are expecting a JSON response you'll need to specify that in the original call using the dataType: 'JSON' option so JQuery can handle it appropriately.
$.ajax({
url: "divisions.php",
type: "post",
data: {mydata:divisions},
success: function(response){
$("#result").html(response.message);
},
error:function(response){
$("#result").html(response.message);
}
});
But, before we get too far, that division variable in JS is troubling. Where is that sourced from? Is it a form by any chance? If so, you can use serialize() such that
var divisions = $('#myform').serialize();
This will create key=>value pairs where the key is the name of the form field and the value is (obviously) the value of the field. You can access the values in PHP just as you would normally.
When considering the earlier question about how your array is structured, this is an acceptable case of posting data as the object. If it's a form then the form structure is going to be linked to the backend out of necessity anyway and so the direct use of the object in the data: option is just fine. It's that whole first concept of "leave it alone". The last case here leaves that object alone completely; from the time it leaves the DOM to the time it's received by the handler it's an object 100% of the time.
As #slamborne mentioned in the comment, the correct call is json_decode(file_get_contents('php://input')).
What your call is doing is actually making another call to divisions.php, which is why you're getting NULL back (it doesn't have any data to return to you, as divisions.php doesn't output anything).
Related
I minimized the code snippets to show only the code needed, and the url for the server side file is actually connected to a url on my server.
HTML FILE
<head>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid }
});
</script>
</head>
<body>
<?php include("serverSide.php"); ?>
</body>
serverSide FILE
<?php
$btid = $_POST['btid'];
echo($btid);
?>
DESCRIPTION
So what is going on is when the page loads, the javascript code runs. It creates a variable named btid equal to 1. This variable is then sent to a file on my server that is a php file. I want to echo that variable through php. But when I load the page, I get an error log stating that the code $btid = $_POST['btid']; has an Undefined Index.
I don't think your code is going to work as designed. You are using include("serverSide.php"); in the body of the HTML, but it is never going to have any $_POSTvalues unless you are posting a form.
Your ajax call is not doing anything with the value that is being returned.
I think you should remove the include("serverSide.php"); from the body of your HTML (it is serving no purpose in its current incarnation) and use the returned value of your ajax call to put the value of btid in the HTML (if that is where you want it).
When you use PHP's include as in <?php include("serverSide.php"); ?> PHP will execute the code on the file being included. That is what is causing your error, when the code is first evaluated it has no $_POST['btid'] because you haven't called it yet.
Your javascript will run on page load and make the ajax call correctly, but you are not using the response anywhere. In order to store the response from the Ajax call you need to add a success handler.
If I understood what you are trying correctly, your code should look more like this:
HTML FILE
<head>
</head>
<body>
<div id="response"></div>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid },
success: function(res) {
$('#response').text(res);
}
});
</script>
</body>
What we are doing is making the ajax call and when the call is successful we assign the returned value as the div content. Also, I switched the script tag to the end of the body because we need to be sure all the document has loaded before changing anything (could have used $( document ).ready()).
So here I am posting my first PHP function that I am proud of but I just recently learned about AJAX and wanted to test it out. Unfortunately I can't get it to work.
My experience: PHP (3 weeks). CSS3, HTML, Basic Javascript.
My Problem: Getting AJAX to work. I want ajax to get my data from the php file which gets the votes from my test server (Xampp) database. So each time the user clicks on good or bad AJAX should display the new results without refreshing the page. The issue is however that: A) My if statements work by checking isset($_POST) which wont work anymore if I call by AJAX. B) Preventing refresh. C) Making AJAX update after every click. I know im nearly there, im just missing something and I dont know exactly what it is to be honest.
What I tried: Checked my database connection. Checked if my php code worked without ajax and it does perfectly fine (I am just displaying half of the functionality here, a lite version, for the sake of simplicity). Tried to change submit to button. Cache clearing. Jquery is in the head of my document and the path is correct. Watched tutorials and read the documentation but I am just not heading anywhere, probably due to lack of experience.
Edit: Sessions and everything php works fine. I my session start and database connection are included on the very top.
Summary: How do I fix this ajax so that it always updates my numbers?
Let me know if you want me to explain parts of my php code. Im willing to comment the parts if neccesary.
JQUERY / AJAX CODE
function vote() {
var request = $.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html'
});
request.done(function(vote_sum) {
$("#votes").html(vote_sum);
});
}
HTML CODE:
<div id='votes'></div>
<form id="good" action="" method="post">
<input type="submit" name="good" onclick="vote()" value="+">
</form>
<form id="bad" action="" method="post">
<input type="submit" name="bad" onclick="vote()" value="-">
</form>
In HTML you don't need <form>, you are doing it with AJAX, right?
<div id='votes'></div>
<button onclick="vote('good');">+</button>
<button onclick="vote('bad');">-</button>
In JavaScript, it is easier to use post rather than ajax function
function vote(gb) {
$.post("php/core/voting_system.php", { vote: gb }, function(vote_sum) {
$("#votes").html(vote_sum);
});
}
In PHP, extract the vote and use it as needed (add validation/sanitation):
$vote = $_POST['vote']; // either 'good', or 'bad'
// do what you need with it
TL;DR version:
You didn't include a data field inside your $.ajax call. Also, your script isn't checking which button was pressed.
The long version
When you're performing your $.ajax call, you fail to attach any data to the request. This can be done easily like so:
$.ajax({
method: 'POST',
dataType: 'json',
data: ...someJSONData...
});
Usually, you're going to want to pass JSON to anything, because it can contain complex object structures that you would usually want to communicate between the client and the server. You're clearly not in this example, but if you're trying to learn this stuff, it's better to start off the right way.
Both javascript and php make using the JSON format extremely easy: JS JSON.stringify() and JSON.parse(), PHP json_encode() and json_decode().
function vote(e) {
// e.target.id stores the id of the button that was clicked
var data = {vote: e.target.id}
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
... callbacks and other properties ...
});
}
document.getElementById("good").addEventListener("click", vote);
document.getElementById("bad").addEventListener("click", vote);
This would be a simple example of how you could solve your problem. If you did a simple var_dump in your php script after running the data through json_decode() you would get a nice associative array:
[
'data' => 'good',
]
I hope this illustrates how easy it is to pass data around in this format.
Also notice I defined the event handlers in the javascript. This is generally better, because you keep all your javascript in one place and it makes things cleaner and easier to debug.
Like Jay said you're not sending POST data through the AJAX. You also need to echo your results from PHP.
function vote(event) {
event.preventDefault();
$.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html',
data: 'bad='+$('input[name="bad"]').val()+'&good='+$('input[name="good"]').val(),
success: function(data){
var votes = $("#votes").val().empty();
$("#votes").html(data+votes);
}
]);
}
I have built an area on my client's website that displays a song that is currently playing, as parsed from an XML file via PHP. However, my client wants the song to auto-refresh itself instead of him having to manually refresh the page.
I played around with parsing the file using jQuery.get() and also .ajax(), but because of the way the XML file is structured, it seems as though I can only get the artist and the name squashed into one string, or when I try to be specific it only returns [object Object].
I haven't even tried to tackle having the song's length be calculated and then refresh the feed based on that length. I may not seeing as this is apparently such an issue for me.
Any help or general guidance would be greatly appreciated.
Example working PHP code (obviously, non-AJAX):
<?php
$recentlyPlayed = simplexml_load_file('http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track');
$trackTitle = $recentlyPlayed->{'nowplaying-info'}[0]->property[1];
$trackArtist = $recentlyPlayed->{'nowplaying-info'}[0]->property[0];
echo "<h6>" . $trackArtist . "<span class=\"song-title\">" . $trackTitle . "</span></h6>";
?>
I've tried several different things to get this to work, but it seems the initial obstacle is trying to reference the data in the XML file using the attributes, rather than the node-names. The nodes are all named the same, and it's the attributes that differentiate them. So, as such this code will render correctly, unless the artist/song title are blank, then it renders the third field which is sort of cryptically-named "cue_time_start".
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval("songPull()",1000);
});
function songPull() {
$.get(
"http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
$(data).find("nowplaying-info").each(function(){
var artist = $(this).find("property").eq(0).text();
var title = $(this).find("property").eq(1).text();
$('body').html("<h1>" + artist + "<small class=\"song-title\">" + title + "</small></h1>");
console.log (artist);
console.log (title);
});
}
);
}
</script>
<body>
</body>
Any guidance, advice or examples of best practices when trying to do this sort of thing would be so very greatly appreciated.
I'm not exactly sure if this is what you want, but you could simply use attribute selectors to extract the data you want out of your XML document.
http://jsfiddle.net/P8dc6/
$.get("http://publicapi.streamtheworld.com/public/nowplaying?mountName=KROXFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
var $nowPlaying = $(data).find('nowplaying-info');
console.log($nowPlaying.find('[name=track_artist_name]').text());
console.log($nowPlaying.find('[name=cue_title]').text());
}
);
Also, never pass a string to setInterval or setTimeout, you can just pass the function reference directly:
setInterval(songPull ,1000);
How does codeigniter MVC work with AJAX?
More specifically, what is the most basic AJAX functionality that allows one to send data to a model, then back to a view? Could you explain the majority of the components involved in depth?
As a newbie to PHP/JS/Codeigniter and web development in general, understanding the concepts behind AJAX and how it connects with codeigniter was one of the more confusing things to wrap my head around.
The majority of answers on SO and other tutorial sites seemed to come from the viewpoint of someone very experienced, where it didn't make much sense to the laymen.
As such, I've decided to do a very 'basic' answer that should hopefully help most newcomers who are trying to understand how and why this code works. Keep in mind, that this is supposed to be a very basic explanation. Feel free to edit, but try to keep it simple and without jargon.
I'm not going to get into the details regarding definitions, as you can do that through google. I'll start with the first step, the javascript.
On your page, you'll want to find a spot for the actual AJAX. Be sure to have JQUERY loaded. for more information on that, Google 'Jquery', and load the library ASAP.
For this scenario, we'll add our script directly into the HTML, because its easier. Alternatively, you could load an external JS script similarly to how you load stylesheets.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<meta property="og:image" content="<?php echo base_url()?>img/logo/logo-big.jpg"/>
<!--[if lt IE 10]>You are living in the past...Upgrade you Browser!! OMFG (google chrome/fire fox)<![endif]-->
<html lang="en">
<head>
<script src="/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="1.8.21/jquery-ui.min.js"></script>
<link href="<?php echo base_url()?>css/account.css" rel="stylesheet" type="text/css"
</head>
<body>
<div class="ajaxContainer">
<form id="ajaxForm" method="get">
<input type="text" id="ajax_input" name="q" placeholder="Type Here"/>
<input type="submit" id="ajax_submit" value="" />
</form>
</div>
</body>
Inside the HTML, add the following script (anywhere, though I usually add it at the top):
<script>
$('.ajaxContainer').delegate('#ajaxForm', 'submit', function() {
$.ajax({
var submitdata = $('#ajax_input').val();
type: "POST",
url: '/ajax/getdata',
dataType: 'json',
data: { submitdata: submitdata },
success: function(data){
$('#ajax').html(data['content']);
}
});
return false;
});
</script>
As for the explanation:
1 $('.ajaxContainer').delegate('#ajaxForm', 'submit', function() {
I used jqueries delegate function to pick up the submit click. Simple enough. It scans all ids/classes within the specified div/class (.ajaxContainer).
2 $.ajax({
This is where the magic starts.
3 var submitdata = $('#ajax_input').val();
Here you will simply 'grab' the data that you want to use in your controller/model. This isn't necessary, but it certainly helps for this explanation. Here, we are taking the value inside #ajax_input and adding it to the javascript variable submitdata for use later on.
4 type: "POST",
Hopefully you are familiar with post/get and typical html form submission. In this example, we specify POST for how we will submit the data. You can change to GET if you want to. Play around with it.
Notice how each section is separated by a , Not overly complicated, just something to take note of. In fact, there are many other things you can add to this code. Take a look at jquery AJAX documentation for more info and play around. http://api.jquery.com/jQuery.ajax/
5 url: '/ajax/getdata,
This is the controller you are calling. I'll explain more later, however, you want to create and ajax controller and a function inside it named getdata. Again, youre simply pointing ajax to a URL. In theory, you could access the page manually by typing it in the address bar. Once you pass the data to that controller, you are working with PHP/codeigniter, and one step closer to successfully performing an AJAX call.
6
dataType: 'json',
data: { submitdata: submitdata },
Specify what type of data you expect to be returned with dataType.
data: sends POSTED data to your controller to be picked up and used in your model. the first submitdata: is the variable we made earlier, and the second represents the name you will be searching for in your controller.
At this point, we will move over to the controller. If you recall, we directed our AJAX call to the url: - /ajax/getdata,
I alluded to creating a controller/function that mirrored that URL. Heres what it would look like:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Ajax extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('logic_model');
}
public function getdata()
{
//First, grab the data being passed via AJAX through post
$submitteddata = $this->input->post('submitdata');
//Then send that data to your model to do whatever you want.
$data['content'] = $this->logic_model->dosomething($submitteddata);
// you need to echo the data. json_encode turns an array into a JSON formatted string. Without this, you will not receive a success, and you lose sir, goodday.
echo json_encode($data);
}
}
And our Model, aka: logic_model ->
public function dosomething(submitteddata)
{
return "Success!"
}
It returns Success! without will feed back into the controller, $data['content'] and then will be echoed.
We now return to javascript where it checks everything that happened and performs either the success: or failure: function (read documentation for more on failure).
7
success: function(data){
alert(data['content']);
}
As you can see, the function includes the parameter, data This represents the JSON we echoed in the ajax controller. It works just like an array. If successful, it should alert the returned string 'Success!"
And its THAT simple. Obviously, as your task changes, so do a few of the steps, but it will typically just expand on the above scenario.
Hopefully people find this helpful coming from someone who isn't that adept at PHP/AJAX yet, but has come a long way.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So I have an array of records retreived from a database. The array is in the format;
$rows[0]['id']=1;
$rows[0]['title']='Abc';
$rows[0]['time_left']=200;
$rows[1]['id']=2;
$rows[1]['title']='XYZ';
$rows[1]['time_left']=300;
//And so on upto 10-20 rows
What's the best way of transferring this array over to my javascript code? I'd like the javascript to be able to loop through all of the records, and using the 'id' attribute, update the div with that id with some information.
My javascript code is in an external .js file, but i'm able to execute php code in the HTML code of my page. So I could do something like this:
In my_file.js:
var rows=New Array();
In HTML code:
<html>
<head>
<script type="text/javascript" src="js/my_file.js"></script>
<script type="text/javascript">
<? foreach ($rows as $row):?>
<? extract($row);?>
rows[<?=$id;?>]['title']="<?=$title;?>";
//And so on
<? endforeach;?>
</script>
I tend to use a JSON object for this:
On the server side, JSON encode your data: json_encode($data);
On the JavaScript side, I write a function that takes a JSON object as a parameter and unpack it.
When you unpack the object, you can print the array's contents into a <DIV> tag, or where ever you would like on the page (jQuery does a pretty sweet job of this).
If you're doing inline data, I've always been fond of doing
<script type="text/javascript">
window.sitescriptdata = {};
window.sitescriptdata.foo = ( <?php echo json_encode( $structure ); ?> );
</script>
For basic stuff, saves you doing an AJAX callback. Also, if you want to glue data to a DOM node, the "metaobject" way is something I really love.
<div id="foobar">
<div><object class="metaobject">
<param name="data" value="<?php echo htmlentities(json_encode($data), ENT_QUOTES );?>" />
</object></div>
</div>
Now this may not look great, but its an effective way of associating data directly with a DOM node without needing to know the exact unique path to that node. Very handy if you have many many datasets that need to be attached to specific screen elements.
I usually use http://noteslog.com/metaobjects/ plugin for jQuery, but its so simple I have on occasion written it myself ( there was a time I couldn't find the plugin, but new how it worked )
When done, there will be
$("div#foobar > div").get().data.($yourarrayhere)
Visible to your code.
To follow up to your question (and my reply, I ran out of space on the comment reply), here is a very simplified subset of the code I use:
Javascript AJAX handler in jQuery:
$.ajax({
type: "POST",
url: "BACKEND.php",
timeout: 8000,
data: "var1=" + myVar,
dataType: "json",
error: function(){
$("#DIVID").html("<div class='error'>Error!</div>");
},
success: function(jsonObj){
$("#DIVID").html(jsonObj.mydata);
}
});
PHP Array:
$data['mydata'] = $myData;
In an AJAX example like here you can solve this problem on this way:
.php file (ajax return function)
$myArray = array("object_id"=>1, "object_title"=>"Testobject");
return json_encode($myArray);
.js file (javascript function)
...
if(g_httpRequest.readyState == 4)
{
var jsonRes = JSON.parse(g_httpRequest.responseText);
alert(jsonRes.object_title)
}
...
im still fairly new too say maybe this method isnt the most secure, but you can always turn your javascript array into a string and then pass it through the URL for the php to GET.
so:
for(var i=0;i < jsarray.length;i++)
{
var x = jsarray[i];
urlstring += "myvalue[]="+x+"&";
}
document.location.href = "mypage.php?"+urlstring;
and then the php would be:
$phparray = $_GET['myvalue'];
hope that helps