Been playing with this for too long now!
I'm using codeigniter.
I am trying to get some data back from an Ajax get request. Simply I want to check a MySQL DB to check if there is some data in there mathcing a given date. A simple true or false will be fine for the return.
Here is my request, followed by the PHP. The PHP does return the correct result into $data, but when it gets back to the Ajax request, the alert(data) is called and shows up as blank... nothing there.
Any ideas what I'm doing wrong?
Thanks
function get_appointment_data(request_date){
$.ajax({
url: 'http://localhost/doctor_today/booking/retrieve_cal_data',
type: 'GET',
data: request_date,
success: function(data){
alert(data);
}
});
}
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
return $data==null;
}
I am not familiar with codeigniter but you must output the result of the function. Instade of 'return' you must use 'echo' to return result to ajax request.
You have to echo the result, otherwise your ajax won't receive a result and the success handler won't execute. Here is what I'm going to use for this case, I'm using the simpler .post function for that task with one key difference - I specify 'json' at end of it which means I'll get a json object as a result from my .post (you can search Google for this). The next key is to use encode the result I wanna get in json format using PHP's json_encode function and echo its result. We don't really need to return a result via the normal 'return' statement. So...
The script:
var url = 'http://example.com/ajax_function';
var data = null;
$.post(url, data, function(data) {
if(data.ok)
alert('Everything is fine!');
else
alert('Ops!');
}, 'json');
The server side:
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
echo json_encode(array('OK' => $data==null));
}
If you call directly the PHP function it should output something like
{ "OK": "true" }
which later on will be translated to an javascript array
data[OK] = true;
which you can use as you wish.
Cheers,
Stan.
P.S. I haven't tested the code but it should pretty work.
Related
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.
Hello I have a problem with my ajax request in jquery.
When I use my get request without sending any data the response is as expected, I receive my array and can access the values:
$.get(
loadUrl,
function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
This works as expected and I recieve my value of "528" being my leftPlayer[4] value.
But when I change my request to send a piece of data to php in the request like so:
$.get(
loadUrl,
{ type: "left" })
.done(function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
My data received seems to be in string format to javascript.
My alert prints "5" (the 4th character if the array was a string)
When alerting leftPlayer. I find that in the first request in which I send no data the variable is printed as: 355,355,355,355,528,etc...
Whereas in the second request in which I DO send data it prints as:
[355,355,355,355,528,etc...]
Notice the []. It isn't recognised as an array.
The php file it accesses has absolutely no changes in each request, as I am testing at the moment. The data sent isn't even used in the php file at the moment.
Any ideas where I'm going wrong?
I've fixed my problem.
Like what "nnnnnn" said in his comment I'm passing my "json" parameter to the .done() function instead of the $.get() function.
I couldn't seem to get it to correctly view it as JSON though so I used the easiest method:
$.getJSON(
loadUrl,
{ type: "left" },
function(data) {
useReturnData(data);
}
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
Using $.getJSON instead does like what it says and expects JSON to be returned as default.
I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>
You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});
Hi I'm working on passing back an array from php to javascript. I learned online that I should use json_encode on the array when passing it back but now that i have it in the ajax i'm unsure how i can loop over it because doing things like response[0] gives me [ and response[1] gives me " although when writing the entire thing to the document using innerHTML i can see it looks like an array but using a for loop gives me each letter like i stated above with the response[0] equaling [ rather than the first entry. What am i doing wrong? Any help is greatly appreciated!
PHP
<?PHP
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$result = mysql_query("SELECT * FROM `Colleges` ORDER BY School");
$schools = array();
while ($row = mysql_fetch_array($result)) {
array_push($schools, $row['School']);
}
mysql_close();
die(json_encode($schools));
?>
Ajax
<script type="text/javascript">
function schools(){
$.ajax({
url: "Schools.php",
type: "POST",
success: function (response) {
//Loop over response
}
});
}
</script>
You should decode your JSON response (which is a string actually) to be able to work with it as with an object:
var respObj = JSON.parse(response);
The other way around is noticing jQuery that JSON will be supplied by the server (with either dataType: 'json' ajax parameter or Content-Type: application/json response header).
In the object you pass to the ajax method, you should try to add dataType: 'json' in order to specify that the result is json, or you could specify it in your php script calling header('Content-type: application/json'); before the call to die();
Doing so will result in your response being the object you expect instead of a string.
Finally, you could leave it as is, and call in your success callback response = $.parseJSON(response); which will take the response string and turn it into an object, see http://api.jquery.com/jQuery.parseJSON/
Use Following if it helps
res=jQuery.parseJSON(response);
for(i=0;i<res.length;i++)
{
alert(res[i].propertyname);
}
here property name implies to the keys on json .In your case it can be 'School' or just a number i or value can also be just res[i]
Javascript
for ( variable in response ) {
alert(results[variable]);
}
JQuery
$.each(response, function(ind, val){
alert("index:" + ind + ". value:" + val);
});
I'm trying to use jQuery.post() function to retrieve some data. But
i get no output.
I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.
My scriptfile looks like this:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
My PHP file looks like this:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.
since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
I don't think I'm passing the storeID parameter correctly. What is the right way?
How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" }
Is the getNameAndTime the name of the function in test.php ?
I have gotten one step further.
I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.
My js script now looks like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
This results in an alert window which ouputs the store data as string in JSON format.
(because I have changed "json" to "text").
The JSON string looks like this:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten#brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
Now, what I really want, is to ouput the data from JSON.
So I would change "text" to "json" and "alert(data)" to "alert(data.name)".
So now my js script will look like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
Unfortunately, the only output I get, is "Undefined".
And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".
So how do I output the name of teh store?
In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ?
(currently I have hardcoded the storeID, for testing)
Lose the quotes around "storeID":
Wrong:
jQuery.post("../functions.php", { storeID: "storeID" }
Right:
jQuery.post("../functions.php", { storeID: storeID }
bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.
However, a couple more notes:
It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
EDIT As far as your reply, if you break down what you are returning:
[
{
"id":"9",
"name":"Brandstad Byporten",
"street1":"Jernbanetorget",
"street2":null,
"zipcode":"0154",
"city":"Oslo",
"phone":"23362011",
"fax":"22178889",
"www":"http:\\/www.brandstad.no",
"email":"bs.byporten#brandstad.no",
"opening_hours":"Man-Fre 10-21, L",
"active":"pending"
}
]
This is actually an array (the square brackets) containing a single object (the curly braces).
So when you try doing:
alert(data.name);
This is not correct because the object resides as the first element of the array.
alert(data[0].name);
Should work as you expect.
Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]
so this would work.
wrong: alert(data.name);
right: alert(data[0].name);
Hope that helps.
D
Ok, thanks to Darryl, I found the answer.
So here is the functional code for anyone who is wondering about this:
javascript file
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML }, // this.cells[0].innerHTML is the content ofthe first cell in selected table row
function(data){
alert(data[0].name);
}, "json");
});
});
get_storeData.php
<?php
include_once('dal.php');
$storeID = $_POST['storeID']; //Get storeID from jQuery.post parameter
$sl = new storeLocator();
$result = $sl->getStoreData($storeID); //returns dataset from MySQL (SELECT * from MyTale)
while ($row = mysql_fetch_array($result))
{
$data[] = array(
"id"=>($row['id']) ,
"name"=>($row['name']));
}
$storeData = json_encode($data);
echo $storeData;
?>
Thanks for all your help guys!