In my PHP/jQuery application, I have a javascript file, in which I can call an external PHP file (post_data.php) like this:
$.ajax({
type: "POST",
data: "some data",
url: "post_data.php",
Now, instead of calling php file, i would like to call a CodeIgniter contoller function Data/post_data, so how can I call that function instead of post_data.php?
The javascript file in which i would like to call is located:
root/js/test.js
while the function is located here:
root/application/controllers/data/post_data
The ajax need to have a full url:
$.ajax({
type: "POST",
data: "some data",
url: "http://www.yourdomain.com/urpath/post_data"});
The reason is the Javascript file that call the Ajax is not aware of the server location of the .php file. So, by using the absolute path you make sure that your call will be done. Also, to test it before using the Javascript file, copy and paste the url into your browser. If no 404 error is displayed, than you have your good path.
To add to Doaks response, you can also do it like this
$.ajax({
url: "<?php echo site_url('data/post_data'); ?>",
type: "POST",
data: data,
You can use $.post() JQuery function it's more simple and optimized for POST request. Also for routing, you can set just controller and method. It's enought.
$.post("admin/newphone", {
phone: $('input[name="phone"]').val()
},
And link to JQuery docs http://docs.jquery.com/Post
Related
I've been using cURL and ajax to load data from APIs. I also have a local geo.json file. I did
function borders() {
$.ajax({
url: "libs/geojson/countryBorders.geo.json",
type: 'POST',
dataType: 'json',
success: function(result) {
//my code
}
})
}
While this works, my tutor told me to not access the geojson file in the javascript file, but to break it into a PHP and ajax routine. My question is: how would I do this? For APIs, I've saved the API calls to a variable and used curl methods to decode the data, however, I'm not sure what to do with local files.
function showmypage(calculated){
var sorteddata = JSON.stringify(calculated);
myurl = URL + 'personalloan/getPLOffersbyfilter/eligibility';
var request = $.ajax({
url: myurl,
method: 'POST',
data: {data:sorteddata},
dataType: 'html'
}).done(function(msg){
$(".divoffersfilter").load(myurl);//here is error
console.log(msg);
});
}
I want to send array (calculated is array name) to the controller and this and load a dynamic PHP page using content in that array. But, here it treats ".load()" function separately. the ajax is processing the request and giving back the response but the response is not loaded on view file.
Note that you are making two ajax requests to the same URL.
The first one is with the code
var request = $.ajax({
url: myurl,
...
The second ajax call is in your .done block.
$(".divoffersfilter").load(myurl);
The .load() function is shorthand that essentially amounts to this.
$.ajax({
url: myurl,
method: 'GET',
success: function(data){
$(".divoffersfilter").html = data;
}
});
Without seeing the code that executes at the URL it is not possible to provide advice on which ajax approach to use. But you probably should not use both.
I'm trying to create a simple "Register your interest" action. I have the front end working but I'm not sure how to link the AJAX to the PHP file. Where do I put the PHP file?
My current code for the AJAX is:
$.ajax({
url: "register-interest.php",
type: "GET",
dataType: "json",
data: {
type : "registerInterest",
email : userEmailLog,
user : userNameLog,
product : productTitle,
sku : productSku
},
success: function (response) {
JSON.stringify(response);
},
error: function (err) {
JSON.stringify(err);
},
complete : function() {
//$('.user-accept').addClass('unhide');
loading();
}
});
First you check url variable is correct or not and then provide response any data like
success: function (response) {
JSON.stringify(response);
},
Your url value is:
"register-interest.php"
This implies that the php file that processes the AJAX request needs to be available at the same directory level as the page that includes the javascript file that is performing the AJAX request.
Example:
If your page is at http://example.com/my/ajax/page.html
Then the javascript will perform the AJAX request to the URL http://example.com/my/ajax/register-interest.php
Alternatively if you change the JS url value to read "/register-interest.php", then the AJAX request will be made to: http://example.com/register-interest.php
Where you need to put it on your server depends on how your web server's webroot's folder structure is organised, but you should be able to work back from the URL the javascript will be requesting to work this out.
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)
Is it possible to refer an AJAX POST to a specific function within a PHP file?
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: "some data...",
success: function(){
alert('Success!');
}
});
Or is there a way to have functions.php receive data and know what to do with it? If not, are there any other suggestions for getting data over to mySQL (using PHP/jQuery)? Thanks!
The data sent to the php file using POST can be accessed in php using:
$datasent = $_POST['name'];
Given that you sent data as:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
Not directly. You'd need to post certain data, and have PHP check the POST variables to choose the correct function.
Perhaps have a look at some tutorials (unfotunately the jQuery links for php tutorials are broken).
Is it possible to refer an AJAX POST to a specific function within a PHP file?
No. jQuery doesn't know what PHP is, even less what a PHP function is. jQuery talks to server side urls. Whether those urls are static html files, PHP scripts, Java servlets, Python I don't know what, CGI scripts, is not really important.
So you could use the data setting to pass parameters to this server side url which based on the values of those parameters could invoke one or another function.
If you want to call a specific function, change ur jquery:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {function:"doSomething",name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
In your php add:
call_user_func($_POST['function']); // This will call what ever function name is passed as parameter
function doSomething(){
echo $_POST['name'];
}