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?
Related
I have a lot of jquery ajax methods and for each of them a small php file.
Is it possible to create one single php file and than on jquery side refer to a specific function in the php file?
Like this:
$.ajax({
type: "POST",
url: "functions.php", function01(),
....
next function:
$.ajax({
type: "POST",
url: "functions.php", function02(),
....
And if it is possible - is it maybe a wrong practice for overall performance?
You are looking for routing the requests to the right recipients.
This is a common practice among many MVC frameworks and it does not have notable performance impacts in contrast to maintainability of the code (– if done right).
A very simplified example:
<?php
// request.php
$allowedRequests = [
// these files will correctly handle the specific requests when included
'db' => 'db.php',
'file' => 'file.php'
];
$request = $_GET['request'];
if (isset($allowedRequests[$request)) {
include($allowedRequests[$request]);
}
Then, just pass another GET parameter on the client side:
$.ajax({
type: "POST",
url: "functions.php?request=db"
Depending on the request parameter, the correct file will be chosen and included.
Note: As I already said, this is a very simplified example. For instance, CakePHP supports storing grouped functionality (=controllers) in different files. Anyway, the gist is to redirect the whole request parameters to the correct part of your application.
You can, but not quite like that.
I suggest sending a parameter in the request that tells it what function to run.
$.ajax({
type: "POST",
url: "functions.php",
data: {
method: 'function01'
# and then whatever other data you send
}
});
Then in your PHP, just use the method param to call the right function.
<?php
$funcName = $_POST['method'];
call_user_func($funcName);
function function01(){
}
function function02(){
}
Note: You should probably check $_POST['method'] against a white-list so that your page is secure. Wouldn't want someone to send method=eval.
You could pass a $_POST var along with the rest of the AJAX data and use it to determine the function to run like so:
JS
$.ajax({
type: 'POST',
url: 'function.php',
data: {
action: 'function01',
... // Other Data
}
...
});
PHP
if ($_POST['action'] == 'function01'){
...
}
I hope this helps!
Your right, in fact you should try not to do it in another way. Think about 1 dispatcher file which calls the correct function. You do yourself a favor as you are now able to only define 1 error handler, 1 output handler etcetc.
As for your question: add 'data' to your request so you can identify the type of request. Depending on the type of request you can call the correct method( for example, with a switch to evaluate a $_POST value)
I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>
It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".
If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.
I'm starting a web programming, because so far I used only to web design.
My problem is that I´ve done a survey that show a form with 12 questions per department. The number of departments depends on a previous selector called "sections".
Thus, the form can show 12 questions fields if "section" has 1 department, or 120 if "section" has 10 departments.
I serialize and encode data to Base64 before submit:
// Setup call
$.ajax({
type: 'GET',
url: 'survey_actions.php&action=save',
data: { parameters: Base64.encode($("#mySurvey").serialize()) },
dataType: 'text',
beforeSend:function(){
// Load waiting panel
loader("on");
},
success:function(response){
[...]
I´m sure this is not the clean method and for that I am experiencing the following problem: when the number of fields to fill is low (for example 12), all works OK, but when the number is higher (for example 72), no all data is received by server.
The fields are named as follows: "sectorID_questionID". So on post, params string is:
...&1_0=X&1_1=X&1_2=X&1_3=X...
(X is the value that the user has given to the question).
So the question: what is the most appropiated way to solve it and send huge data to the sever using AJAX without get it trimmed?
Sincerely, thanks for your help :)
Change the ajax type to POST, rather than GET and get the data from $_POST. Your data could be going above the maximum query string length.
Ajax can only take data in a query string. So, if large data is not being sent properly, it may be a limitation of your server/application.platform. You may very well look into increasing the max_input_vars. And also make sure you use POST and not GET
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Just use the above syntax an I don't think you need to serialize your data
I'm building an AJAX form and I'm trying to send 3 fields by JSON.
Client-side, the form is serialised and entered into JSON format:
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $.base64.encode($('#form-signin').serialize()),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
Server side, my router splits the URL request up, sees that the first part contains 'ajax' then proceeds to specially pass the routing request to an AJAX handler.
my problem is that even inside the router, checking $_REQUEST, which is what is used to get the information about the post, the post data is not there. The same goes with $_POST.
Even the first page where the request hits (index.php), $_REQUEST does not have the data.
What am I doing wrong?
Server Side,
The request is sent to an index.php which includes the Autoloader and init script.
The init script initialises the database connection, sets the error, exception and session handling, then passes the request onto the router.
The router, in its construction method: sets the URL as an array (exploded $_SERVER['REQUEST_URI']), and then sets the relevant controller, method and additional parameters.
In this case, as we are doing an ajax request, special processing happens before we dispatch the request.
The method parameters are set to:
$requestParams = $_REQUEST;
unset($requestParams['url']);
This request parameter(s) along with additional information (url, controller, method and database object) are passed for dispatch.
In all cases, we are primarily dispatching using this method:
$dispatchedController = new $this->controller($this->database);
$method = $this->method;
return $dispatchedController->$method($this->params);
If I remember right from using a plugin a long time ago, the method $.base64.encode() returns a single string so what you are probably sending to the server is something like a single parameter with no value.
I believe you should be doing something like
data: "foo=" + $.base64.encode($('#form-signin').serialize()),
You are not sending json to the server just a base64 encoded string. Also you are expecting key/pair values. To send key/pair values just pass the serialized form data to the $.ajax function.
$('#form-signin').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel2';
$.ajax({
type: "POST",
url: url,
data: $('#form-signin').serialize(),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
});
}
});
event.preventDefault();
});
The code should work (assuming your HTML is not the problem here, e.g., '#form-signin' is the right selector for the right form).
You mentioned you are not able to get the data on the server side. However, are you absolutely sure you are even sending the data you need from the client? For example, have you analyzed the request using a tool such as Firebug?
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.