Calling controller function from JS file - javascript

Im using Yii framework, i want to call controller function from JS file,
My ajax code in JS file:
$.ajax({
type: "POST",
url: "operator/checkDisabledDates",
data: {
id: 1
},
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
where checkDisabledDates is my controller method name, and operator is my controller name.
i got wrong formation of url something like,
www.example.com/operator/agent/id/4/operator/checkDisabledDates
my ajax url just appends at last position of existing url,
i tried different combinations like,
url: "/operator/checkDisabledDates"
url: "../operator/checkDisabledDates"
url: "../checkDisabledDates"
nothing worked,
but when i use in below syntax it worked,
url: "../../checkDisabledDates"
Is there anyway to do this without hardcoding dots(.) like this???

I would suggest not using a relative path to call your controller.
Try using your domain as context
var domainName = 'yourSite.com'
url: domainName+"operator/checkDisabledDates"

I'm using in my project and it's working for me, please try this -
Define a Global Variable in JS file eg. -
var url_path = document.location.origin+document.location.pathname;
so now you can use like this
url: url_path+'?r=operator/checkDisabledDates'
or
url: url_path+'operator/checkDisabledDates'

Use this:
data = {};
data.r = 'operator/checkDisabledDates';
data.id = 1;
$.ajax({
type: "POST",
url: "index.php",
data: data,
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
Always works for me.

Related

How to escape brackets in an ajax request?

I would like to send a GET request with only one parameter from an input form via AJAX, using jQuery.ajax().
To simplify things, instead of
data: $("#the_form").serialize()
I tried to explicitly pass the value of the input:
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: {
tx_search_pi1['sword']: val
},
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
Now this breaks because of the brackets and quotes in
tx_search_pi1[sword]: val
(which is required by the recipient of the get request)
How do I escape the brackets (and maybe also single quotes inside= correctly?
I've tried-and-errored many combinations, eg. with
tx_search_pi1%5Bsword%5D
encodeURIComponent("tx_kesearch_pi1[sword]")
etc...
You can try this,
data: $("#the_form").serialize()+'&sword='val,
Full Code,
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: $("#the_form").serialize()+'&sword='val,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
And if you want to pass sword value then use,
data: {'sword':val}, // get using sword key
As per #Urs Comment the code should be,
// let it is initialised before,
// and it is an object like {}, tx_search_pi1 = {key:"1",...};
function lookupSearch(val){
tx_search_pi1['sword'] = val;
$.ajax({
type: "get",
url: "/search",
data: tx_search_pi1,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
try putting tx_search_pi1['sword'] this in a variable and pass it.
Like
var temp = tx_search_pi1['sword'];
And pass temp

jQuery not parsing json

I have a website and partner provide me this link https://www.fundingoptions.com/partner/integration/
I checked there is something related with oEmbed, but I not familiar with it.
This url https://www.fundingoptions.com/oembed/?affid=10 is returning json which I was parsing like this:
$(document).ready(function(){
$.ajax({
cache: true,
type: 'GET',
url: 'json/data.json',
data: { get_param: 'value' },
dataType:'json',
success: function (data) {
var names = data
$('#json').html(data.html);
}
});
});
But it does not work anymore, I am stuck now :(.

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

PHP RestServer Class - Ajax call

I'm practicing with the PHP RestServer Class. But I can't get the correct data from it if I use an Ajax call on it. I have the following code:
<?php
require_once "locationOfRestServer.php";
class HelloWorld
{
public static function sayHello()
{
return array("Response" => "Hello World");
}
}
$rest = new RestServer('HelloWorld');
$rest->handle();
And in my javascript file I use the following:
this.helloWorld = function() {
$.ajax({
url: 'locationOfHelloWorld.php'
type: 'POST',
dataType: 'json',
success: function(data){
console.log(data);
}
});
};
I get the following error:
error: "No method was requested."
Because; whenever I use it, I have to go to localhost/HelloWorld.php?method=sayHello which is actually working.
So I added the following line to the ajax call:
method: 'sayHello',
But it still keeps giving me the same error.
Try this,
$.ajax({
url: 'locationOfHelloWorld.php'
type: 'GET',// use GET method according to your working url
data:{method: 'sayHello'},// use method in data parameter
dataType: 'json',
success: function(data){
console.log(data);
}
});

Trying to make an ajax call to the IMGUR api, data is undefined?

I'm passing in authorization headers elsewhere, so I've gotten past that problem. If I alert(data) I get an object[Object], but am at a loss as to how to extract the data from that object. Any help would be greatly appreciated! Thanks!
var albumAPI = "https://api.imgur.com/3/album/" + albumID + "/images";
$.ajax({
url: albumAPI,
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data[0].link);
},
error: function() { console.log("ERRORZ"); },
beforeSend: setHeader
});
If you look at the data, it contains a property called data which is an array - so get the link to the first image
alert(data.data[0].link);

Categories

Resources