Build jquery url in $.ajax call - javascript

I'm trying to make a $.ajax call and send some data to a php file, my php file is located in a
component's folder and my js file in the webroot folder, how can I make the url portion of the $.ajax point to the right php file, to get to the php file from the JS file I need to do the following
../../../src/Controller/Component/AuthComponent.php
but when I do the same in the $.ajax call like
$.ajax({
type: 'POST',
url: '../../../src/Controller/Component/AuthComponent.php' ,
data: "accessToken" + access_token,
dataType: 'json',
complete: function (response) {
console.log("data coming back from Auth.php" +response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
I only get
http://localhost:8765/src/Controller/Component/AuthComponent.php- 404 not found
How can I build the url?

If you are using a framework or if you have build routing yourself, for all other pages of the website. Then similar to those, you will have to create (assign) a new route to the method() added in your AuthComponent.php for example:
Route: http://localhost:8765/authcomponent/method_name
Pointing to: /src/Controller/Component/AuthComponent.php::methodName()
Then, your final JavaScript code will look like:
$.ajax({
type: 'POST',
url: 'http://localhost:8765/authcomponent/method_name' ,
data: "accessToken" + access_token,
dataType: 'json',
complete: function (response) {
console.log("data coming back from methodName() of AuthComponent.php file" +response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});

I would rather pass in the complete URL (if there's any chance you can pass on your domain to the JS code).
Sometimes, if you are compiling your code, the actual relative path might not be the same as your directory's ordering when running the code (e.g. the JS might be being compiled to run from a single location in a different folder within your site's dir).

you can't use absolute path as url ,if for example your document root is something called 'public_html' directory ,i mean your site name pointing to this folder and inside that your file AuthComponent.php is placed that your url is sitename/AuthComponent.php will make call to your file.

Related

POST (url) net::ERR_BLOCKED_BY_CLIENT

I am getting the below below when i try to the url
https://www.cshippers.com/orderManagement/OrderManagementReportAction.action?actionCommand=submit&menuRef=REP_APP005_0001MT
The error:
POST (url) net::ERR_BLOCKED_BY_CLIENT
The JavaScript Function:
$.ajax({
url:targetUrl, //supposed to be the url as mentioned in question
data: formData.serialize(),
cache: false,
type: 'POST',
success: function (dataofconfirm) {
openPage( url.substring(0, url.indexOf(".",2)) + ".action?menuRef="+menuRef );
/*hideLoader();*/
},
error: function (xhr, ajaxOptions, thrownError) {
hideLoader();
console.log( thrownError );
}
});
Usually, there are two problems:
Related to adblocker and you need to turn it off
You need to add an extra segment at the end of your URL
For example "https://--your api--/movie.json". You need to add the target node in your database, here it is movie, at the end of the URL.
Firebase needs this .json at the end of the URL you are sending requests to, otherwise your request will fail.
If you are using Firebase, it could solve your problem.
You can test your API with one of the online open API testing.

AJAX request fails .zip file OnceBuilder CMS

I'm building another full stack library but i'm so strugling on one AJAX request, which is so ridiculous. I have just found that, this function is strugling to get file archive but it can gets easly another files ( that can be solution but... i need zip file too) plugin 19 is static because it's just testing and only this file exists
#file_get_contents('https://oncebuilder.com/once/plugins/19/plugin.zip');
So basicly both AJAX function are the same
If i lunch the same function from preview mode file_get_contents gets crazy and return error, but if i lunch it from the listing or via browser its ok
AJAX function are both the same
$.ajax({
type: 'POST',
url: once.path+"/ajax.php?c=plugins&o=item_download&id=19",
contentType: "application/json",
dataType: 'json'
})
.error(function() { console.log("Request Error: item_download"); });

CodeIgniter Access Controller from PHP Require

I am using codeigniter for my project and I am stuck trying to figure this out.
I have some javascript that needs to perform an AJAX call to fetch some results based on a dropdown value that was selected.
function fetchLines(){
$.ajax({
url: baseURL + "resources/ajax.php?node=fetchLines",
type: 'GET',
cache: false,
data: {
lineType: 'business'
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
In this AJAX file, I am trying to include my controller and then access the function within it.
<?php
define('BASEPATH', "AJAX");
require_once('../application/controllers/Project.php');
switch($_REQUEST['node']){
case 'fetchLines':
$objLines = new Project();
$objLines->fetchLines($_REQUEST['lineType']);
break;
}
?>
My CI Controller then has a private function in it which I am trying to call to get the data I need:
private function fetchLines($lineType){
$lines = $this->project_model->fetchLines($lineType);
return $lines;
}
My goal here is to have an AJAX file or controller (if needed) be used for all my AJAX calls. It needs to be able to access a controller and return data.
With the current code above, I am getting the error: Class 'CI_Controller' not found in <b>C:\xampp\htdocs\blueprint\application\controllers
\Project.php
Is there a better way to handle situations like this? I'm not an expert with OOP but some reading suggested something along these lines.
why you are not sending this request to the controller method instead ?
function fetchLines(){
$.ajax({
url: baseURL + "controller-name/method-name",
type: 'GET',
cache: false,
data: {lineType: 'business'},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
NOTE and in controller you can access these values as
function method-name(){
echo $this->input->get('lineType');
}
Lets say my ajax file is in the controllers folder
And I want to re-use my controllers, i would do it like this :
$this->load->library('../controllers/your_controller');
$this->your_controller->_some_method($data);
Load the controller as library and used it like a library.
Hope this helps.
You should put the code that listens to AJAX call in a controller function only. The way you are trying to do is not a good practice at all.
If you want a method to be executed only if the request was an XHR i.e.AJAX request then use
if($this->input->is_ajax_request()){
//your code
}else{
redirect(base_url())
}

How to return cross domain html in jsonp callback

I'm trying to build embedded widget for websites. This widget will be called from external websites using javascript.
When my widget's script added to a webpage below code runs:
var widget = {
initialize : function(containerId)
{
(function($) {
var url = 'http://localhost:8002/callback.js';
$.ajax({
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
$("#" + containerId).html(data);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
}
}
this code is embedding my widget into given html container (div) And here is my callback:
jsonCallback(
{"html": "<html><body>mahmut tuncer</body></html>" }
);
So, when i give hardcoded html as json, it works. Now, what i need to do is: Load another html file as json before sending my callback back to requesting website.
If you are using JSONP and you're getting a cross-domain exception, that means the source you're trying to pull data from doesn't support JSONP. You might consider using node.js or something else to complete your task.

Retrieving parameters from a JQuery Ajax call when calling a JS file

I am trying to utilise JQuery Ajax to call a javascript file. I need to pass it some parameters but I am not certain how to when using javascript (PHP seems simpler). Here is my call:
function getDocument(parameters) {
$.ajax({
type: "GET",
url: "js/document.js",
dataType: "script",
data: "info=hellothere",
success: function(msg) {
},
error: function(jqXHR, textStatus, errorThrown){
}
});
}
All I would like to do, is print out the contents of the parameter 'info' in document.js
So essentially is should print 'hellothere'.
You're better off using PHP.
Change the URL to document.php, and within that file do the following:
echo $_GET['info'];
url: "js/document.js"
Should be the path to the Server file
You cannot send ajax request to your .js file using Ajax request
Send the request to the .php file and write up your method in there to process the data.
Ajax Request is primarily used to send data to and forth from the Client side to server side ..
If you want to access the data between two .js files better store that data in a cookie or a local storage

Categories

Resources