i am trying to use the Jquery ajax function to call a php page to run a query and return xm the only problem is i dont know how to read the Jquery API page
http://api.jquery.com/jQuery.ajax/
it gives this example
$.ajax({ url: "test.html", context: document.body, success: function(){
$(this).addClass("done");
}});
is there a better example to call a php page to run a sql query and return a json i can encode
See http://api.jquery.com/jQuery.getJSON/ . For example...
The PHP...
<?php
// users.php
$some_users = array(
array('name' => 'Nobby Clark', 'email' => 'nobby#mailinator.com'),
array('name' => 'John Doe', 'email' => 'john#gmail.com'),
);
print json_encode($some_users);
?>
The Javascript...
$.getJSON('users.php', function(data) {
var users = "";
for ( var i = 0; i < data.length; i++ ) {
users += "<p>" + data[i].name + " (" + data[i].email + ") </p>";
}
$('.userlist').html(users);
});
You would just replace the "test.html" with a PHP script that does what you want to do - look up data in a database and return it in JSON.
This is almost a duplicate of a similar question I answered earlier that should explain how to work with PHP and JSON and such, but basically you build an array with the data you want and then run it through json_encode() and output it.
Take a look at this question: jQuery Ajax: Can i store more than one "variable" on success? it has an example of sending json requests with jquery and encoding json at server-side.
If you scroll down that page you will see a bunch of examples that should fill in the blanks for you.
As for the server side stuff, use the PHP file you call to:
Connect to, then query the database for the data you want to return.
Make sure the data you want to return to the client (JavaScript) is in a PHP array.
Output the array using json_encode().
Kill the script.
Something like this:
// Query DB into an array
$data = array(
array('foo' => 'we got this from the DB'),
array('bar' => 'new row')
);
// Output as JSON
print json_encode($data);
die;
Related
I'm having an issue returning a JSON from PHP to Javascript. Below is my PHP to create the JSON:
$environment[] = array('id' => $env, 'adjacencies' => $hostnames);
foreach($hostnames as $hostname) {
$environment[] = array('id' => $hostname, 'name' => $hostname, 'data' => array());
}
return json_encode($environment);;
When I print the json_encode environment to a text file, it comes back as:
[{"id":"Dev","adjacencies":["tb23","tbwag","tbvg","tbut"]},{"id":"tb23","name":"tb23","data":[]},{"id":"tbwag","name":"tbwag","data":[]},{"id":"tbvg","name":"tbvg","data":[]},{"id":"tbut","name":"tbut","data":[]}]
It seems that this is printing out properly but when I return it to the Javascript its coming back as undefined/null. Below is the javascript with the ajax call:
var ajax = new AJAX();
var args = "id=" + $("#apps").val() + "&env=" + node.id + "&nocache=" + (new Date()).valueOf();
ajax.connect("POST", "http://" + window.location.hostname + "/project/graph/host", args, function(json) {
var output = '';
for (property in json) {
output += property + ': ' + json[property]+'; ';
}
alert(output);
});
I've obviously tried a lot of different things to get it to print out but haven't had any luck. In PHP, I've tried json_last_error and it came back as '0', which means that there isn't an issue with the JSON structure.
In the end, I'd like to use the following command in Javascript to continue building my graph:
var hostNodes = eval('(' + json + ')');
Any help is appreciated as to why I can't get this to come back!
Keep your PHP code in an unique file that receives one post parameters, then construct the json array if it set, and at the bottom you can do
echo json_encode($json);
flush();
I'm not a professional with pure javascript and I'm not familar with your approach, but you should consider using jQuery, at least I'm going to suggest one way to receive an json array so that you can easily work with it (you also make sure that the data is json):
$.ajax(
{
// Post select to url.
type : 'post',
url : 'myPHPAjaxHandler.php',
dataType : 'json',
data :
{
'select' : true
},
success : function(data)
{
// PHP has returned a json array.
var id, hostname;
for(var i = 0; i < data.length; i++)
{
id = data[i].id;
hostname = hostname[i].id;
// Construct a string or an object using the data.
}
},
complete : function(data)
{
// Optional.
}
});
Like I say, It's there for you to decide whether you pick it up or not. It can become handy for complex projects.
It looks like you're assuming that the data passed to the callback function will be your JSON already parsed into JS objects, but I don't see any indication that that would be the case; it's most likely the raw JSON data that must be parsed into JS objects using JSON.parse (NOT eval() - eval() is very dangerous, you should always prefer JSON.parse when working with true JSON data, as it will not permit XSS-style attacks as they are generally not "pure" JSON.)
So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.
I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.
I am currently working on a php project with the user of ajax. I need to populate values from a database into an html drop down box and I want to do this from an ajax post.
For all the other ajax so far in the project I have been using $.post but I do not need to post anything to the php script as it is just going to retrieve everything from the database. what I need to do is the php script retrieves the information from a database and populates the information into an array and then return the array to the calling php script that calls that ajax.
Is the array idea the best idea, if so how do I get the contents of the array from the ajax, or is there a better way and how do I do the ajax call if I am not doing a post of anything.
Thanks for any help you can provide.
The easiest way to do what you're describing is using JSON with your jQuery Ajax request, like so:
// PHP side
<?php
// Do your database query, and then echo out your desired data like so:
echo json_encode(array(
'test' => 'your data',
'test2' => array('you can also use', 'arrays'),
'test3' => array('or' => 'keyed arrays'),
));
die(); // don't echo anything other JSON, or you'll get errors
?>
// Javascript side
$.post("url.com", post_data, function(json)
{
// Do something with your data here:
alert(json.test);
alert(json.test2[1]);
alert(json.test3["or"]);
}, "json");
$.ajax({
url: "your_script.php",
global: false,
type: "POST",
data: {},
dataType: "json",
async:false,
success: function(results){
//append your json results to your DOM
$('#some_div').html('');
for(var i = 0; i < results.length; i ++)
{
$('#some_div').append('<p>' + results[i].html + '</p>');
}
}
});
and your PHP will need to json_encode the results...
die(json_encode(array(array('html' => 'first'), array('html' => 'second'))));
Here is a piece of code :
$username="anant";
$name="ana";
echo $username;
echo $name;
Now if using jquery $.post() i want to retrieve $username and $name ,how would I do it ?
Thanks!
I assume the code is your php based response to the $.post call. If all you are returning are values then the easiest thing to do is to return a json response. For example...
PHP Script:
$values = array(
'username' => 'anant'
'name' => 'ana'
);
header('Content-type: application/json');
echo json_encode($values);
JS $.ajax call:
$.ajax(
url: '/path/to/script.php',
type: 'post',
dataType: 'json',
success: function(data){
alert('Username: '+data.username);
alert('name: '+data.name);
}
);
Or if you wanna stick with $.post then follow kovshenin's answer for the syntax using $.post. But be sure you use my php code witht he header() call to properly set the content type of the http response. I just prefer to use the long hand.
I'm not a php expert but try something like:
php
$username="anant";
$name="ana";
echo json_encode(array("username"=>$username,"name"=>$name));
js
$(function() {
$.get('test.php', function(data) {
alert(data.username + ':' + data.name);
});
});
I hope this helps!
You will be better off with json_encode which javascript will understand just fine:
$res = array('username' => 'anant', 'name' => 'something');
echo json_encode($res);
Then use the following code in jQuery to retrieve the values:
$.post('/something', function(response) {
alert("Username is: " + response.username + " and name is: " + response.name);
}, "json");
Cheers.
Now that I know what you are trying to do post expects a fourth parameter the encoding type. If you set it to JSON you would encode your data like so
echo '{"username": ".'$username.'", name":"'.$name.'"}'; //Json may not be perfect
you can access it in jQuery using
data.username
First thing is you have to do a GET not a POST. You may need to change your server side code a little bit so that front end had a clue of how to identify different values (JSON will be better) but a simple , should work fine.
$username="anant";
$name="ana";
echo "$username,"
echo "$name";
your output will be then something like Anant001,Anant your username, name.
Then use a simple jQuery call to get it and split it by , and here is an example..
$.get('/getnames', function(data){
var tokens = data.split(",");
var username = tokens[0];
var name = tokens[1];
});