I have a json file in the form of:
[{"label":"apple","desc":"fruit"},
{"label":"banana","desc":"fruit"},
{"label":"celery","desc":"vegetable"},
{"label":"plum","desc":"fruit"},
{"label":"","desc":"fruit"}]
How would I go about performing GET requests on this data? For example
http://www.mysite.com/data?desc=vegetable would display [{"label":"celery","desc":"vegetable"}] to the browser and
http://www.mysite.com/data?label=apple&desc=fruit would display
[{"label":"apple","desc":"fruit"}] to the browser
Here is a working example that I would like to emulate:
http://ws.geonames.org/searchJSON (returns nothing)
http://ws.geonames.org/searchJSON?featureClass=P&style=full&maxRows=12&name_startsWith=paris (returns matching cities.)
Jquery and php are the tools I'm using. I'm trying to set this up so I can use jQuery UI autocomplete with a remote JSONP datasource.
http://jqueryui.com/demos/autocomplete/#remote-jsonp
You'll probably have better results storing it in a database (e.g. MySQL). Then, you can query based on label and desc columns. Then, access the resulting row(s) with fetchObject and convert the object directly to JSON with json_encode.
You might need a few different versions of the query depending on what GET parameters they pass in.
$.ajax({
type: 'GET',
url: '/getFood/',
dataType: 'json',
success: function(data) {
// do whatever you want with the data here (like show in a div)
},
// replace with whatever you wanna send in the querystring
data: {'desc':'vegetable',},
});
On the server side check the 'desc' parameter in your GET request and send appropriate response.
Related
I'm New in AJAX.
When passing ID to update product. Any explanation for this. Thank you in advance.
This
$.ajax({
type: 'post',
url: 'my_controller/update_product_exe/' + id, //This line
dataType: 'json'
});
to this...
$.ajax({
type:'post',
url: 'my_controller/update_product_exe',
dataType: 'json',
data: {id: id} // this line
});
The difference is the url itself. Appending id to the first url will change it and therefore send the request to that specific url. But, it's not sending any data during request. Example:
// let's say id = "1234"
$.ajax({
type: 'post',
url: 'my_controller/update_product_exe/' + id, // This will be 'my_controller/update_product_exe/1234'
dataType: 'json'
});
And for the second one:
$.ajax({
type:'post',
url: 'my_controller/update_product_exe',
dataType: 'json',
data: {id: id} // This will be {id: "1234"}
});
On the second one, you are passing data; on the first one, you are just modifying your url by appending some string to it.
If you just want to know about the difference in both ajax requests than:
In first request, you are not passing the data in ajax request but sending an ID in URL, in CI controller, you will get this id by using URL Segments.
In Second request, you are sending the data in ajax request, so you can get the data in controller by using $_POST
Now, which one is the better, both of them having difference, when you need to pass some input values using ajax than you can choose second one. You can send multiple data in this request.
You can also use second request for achieving the first request target, in this case you can just pass the ID in ajax data. You can send multiple data but you must need to take of segement URLs.
Conceptually you are using a GET in the the first example and a POST for the second. HTTP verbs have a meaning and POST is meant to send information to a server. Even if you can get the id by using a GET this does not make it semantically correct. For the moment you only have an id which is limited in size and is only one parameter, but even in a small application one usually sends to a server several parameters and maybe some kb of data. GET parameters are limited in size and POST is better suited for this.
For all this reasons the second version that is using POST is the correct one.
Here are some extra resources on the differences between GET and POST.
http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post
http://www.diffen.com/difference/GET-vs-POST-HTTP-Requests
What is the difference between POST and GET?
When should I use GET or POST method? What's the difference between them?
I'm trying to retrieve database information based on what row a user clicks in a table, then later use that data in another page to display other database information. I don't know the best way to achieve it. Should I use Ajax and $.post() or are there other better/simpler ways?
I can retrieve the data from the table by
echo "<tr data-href=". $row["id"] . " class=\"tableclass\"><td>"
and then in jQuery
$(".tableclass").click(function () {
data = $(this).data("href");
alert(data);
The alert shows that I do get the database information (column ID). Now, I would like to post that information, preferably in a secure manner, to another PHP page where I can retrieve it and use it to get other information from the database.
How do I post it and then how should I retrieve it in the next php page?
Both works in same manner.
1. $.post is just a call with $.ajax(), just with the type set.
2. $.ajax() defaults to a GET
$.post( "/ajax", {"data" : json }) //is nothing but
$.ajax({
type: "POST",
url: "/ajax",
data: {"data": json}
});
If you want the data to be passed securely, use json or don't do thing if the request is not properly authenticated.
Typically, when you make an AJAX request, cookies are also sent: along with the request so you should just be able to use the same authentication method that you use for your regular requests with your AJAX requests.
Nothing much to do that, you need to use $_POST to access all the values in php in file save.php
need to pass data to android app through ajax by using php.
the data is pulled from mysql database through a select query
please provide me code example how to perform the task
i had search the internet and i find the below code for reference
http://www.grobmeier.de/android-does-not-fire-ajax-reqests-because-they-are-caches-ajax-requests-at-least-on-jquery-mobile-10072011.html#.UGvLbU3A-RI
how to perform the select query to fetch the data array.
please correct me if the example is not proper.
$.ajax({
url: "yoururl.html",
context: document.body,
cache : false,
data: {
username : $('#username').val(),
password : $('#password').val(),
},
success: function ( data ) {
// do something
}
});
What you need is a regular HTTP request (made from AJAX, of course): you send variables to the server by the method you choose. Something like: http://www.example.com/script.php?var1=foo&var2=bar Those variables can be accessed within script.php this way:
<?php
echo $_GET['var1'], PHP_EOL; // shows foo
echo $_GET['var2'], PHP_EOL; // shows bar
?>
If you use POST method instead of GET you must use $_POST[<whatever>] to access you variables.
Once you got the values within PHP you can execute the query you need to persist that data.
There is a ton of this arround Internet, if you make a minimal search you will find exactly what you want.
In an earlier post today the answer has led me down the route of using a JSON feed to populate elements in my page.
Something new to learn!!
the JSON data is created from a PHP script which retrieves the data from a Mysql database. The php script retrieves a specific record which I need to pass to the php script with the getJson call.
I've had success with creating the url with the parameters added as a GET method but I can't find an example of a POST method - the parameters should go as an optional parameter. here's what I have so far...
function loadData(index) {
alert(index);//debug
$.getJSON('loadJSONholeData.php' ,
{hole: index} ,
function(data) {
I've found examples for a twitter feed which shows a parameter like option: "cat", but can't find an option where the value is in a variable.
I don't understand how to use the parameters - where am I going wrong. Appreciate this is probably a fundamental issue but I'm learning.
Thanks
Update:
I've revised the code per the responses below and used both suggestions to pass the POST parameter, but the receiving PHP code is not reading the POST parameter and just returns the default query values.
I even used as static value of 1 both as a value and as a string but no joy.
Here's my receiving PHP code which accesses the POST values:
$hole = 3;
if (isset($_POST['hole'])) {
$hole = $_POST['hole'];
}
I'm missing something basic here. The value in 'index' definitely exists as it shows in the debug and JSON data is being returned )(but the default). I can go back to my GET method but want to see this work!!
Thanks
Update: Success!!
I played around further with the revised code. I removed the content type parameter from the code and it all works now, the PHP is returning the correct query.
I assume then that by specifying the JSON type in contentType it passes the POST parameter in a different way to PHP which expects it in anpther way?
Onwards and upwards - thanks
The $.getJSON() method does an HTTP GET and not POST. Try something like this -
$.ajax({
url: 'loadJSONholeData.php',
data: JSON.stringify({hole: index }),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
//(result.d) has your data.
}
});
Each key/value pair in the arguments object will represent a parameter in the HTTP POST. You can use variables as values, but I believe they will be converted to strings, so it's better to do the conversion yourself (so you can make sure they have the correct format). A simple example:
var dynamicValue = foo();
$.post('my/url', { var1:"static value", var2:dynamicValue }, function(data) {
// Your callback; the format of "data" will depend on the 4th parameter to post...
}, "json"); // ...in this case, json
Now, in case your server is expecting a json encoded object/list, you can pass it by using JSON.stringify:
function foo() {
return JSON.stringify({ my:"object" });
}
JSON should be available in most modern browsers, in case it's not, you can get it here (json2.js, under "JavaScript").
I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You might do that with $.post method of jQuery (for example) :
var myJavascriptArray = new Array('jj', 'kk', 'oo');
$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
// do something with received data!
});
Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.
Is it that ?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.
You might want to take a look at Creating JSON Data in PHP
IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.
You may be looking for a way to Serialize (jQuery version) the data.
jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:
here is the synatax:
jQuery.ajaxSetting.traditional = true;
here is the example
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend, //this will be an array eg.
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)
myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']
echo $_POST['arrayItems'] ;
will echo something like: array=>{[0]=>'first thing', [1]=> second thing}