I am trying to pass two variables to my controller using ajax. There are no errors but the data is null when I get it in the controller.
Web.php
Route::get('/donate/select-card', 'CardController#chooseCard')->name('select-card');
CardController.php
public function chooseCard()
{
$from = Input::get("fromAmount");
// $to = $request->input('toAmount');
dd($from);
}
'null' is the output here
Script.js
fromAmount = $(this).find('p span:nth-child(1)').text().split("₹ ")[1];
toAmount = $(this).find('p span:nth-child(2)').text().split("₹ ")[1];
$.ajax({
type:'GET',
url: '/donate/select-card',
data: { fromAmount : fromAmount, toAmount : toAmount }
});
What I want is to have the fromAmount & toAmount in my controller.
Thanks in advance.
This is the ajax data from network:
public function chooseCard(Request $request)
{
return $request->all();
}
** Inject the Request class
** See the response from dev tool.
That one was tricky :)
In your HTML you have a link that is wrapping this call to the ajax. This is messing with
<a href="/donate/select-card">
<button type="button" onclick="test123()">click here for ajax Call</button>
</a>
So clicking on this will send you to "/donate/select-card" but won't be trough the ajax.
For the same reason, once you try to use POST, you get:
The GET method is not supported for this route. Supported methods: POST
The href is with priority and it is GET while the route is expecting a POST.
Make sure you remove all links and default behaviours around the html you use to call the ajax call then use GET or POST as you wish.
Related
I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser
I would like to call the mvc controller action method from jQuery, and when the action method gets invoked, the user should be transferred to another site. I have tried using jquery ajax to do this but after response.redirect, my page still stays on the same URL with out any change.
$.ajax({
url: '/Controller/Action',
success: function (Data) {
//don't want to use this callback as I require only calling the
action method
}
});
and in the controller
public void Action(){
// process the request and redirect
Response.Redirect("url", false);
}
Can anyone help me in understanding where the issue is in the above code.
Thanks in advance.
You can try something like this
return Redirect("http://www.google.com");
or try using javascript
public ActionResult Index()
{
return Content("<script>window.location = 'http://www.example.com';
</script>");
}
You can check this link to know about Redirect vs RedirectResult
return new RedirectResult() vs return Redirect()
I tried it and it is working. I hope this helps :-)
HTML
<button class="btn btn-primary" onclick="RedirectTosite()">Redirect To Google</button>
Jquery Call
function RedirectTosite() {
$.ajax({
url: '/Employee/RedirectTosite',
success: function (Data)
{
window.location = Data;
}
});
}
Controller
public JsonResult RedirectTosite()
{
return Json("http://www.google.com", JsonRequestBehavior.AllowGet);
}
I don't get a clue why are you calling server using ajax if you don't do any data manipulation on the database if you are aiming just to redirect to a page simply redirect using javascript code like
window.location.href = '/Controller/Action/'
Ok I am convinced you have done some work on the void method, If you redirect page on the void method ajax request fails and you are not redirected to another page. For it to work you simply remove the line of code
Response.Redirect("url", false);
from controller and write a line of code as follows inside success function of ajax .
window.location.href = '/Controller/Action/'
I am coding some basic crud application in Symfony2 where I want to implement some type of search function on a certain page.
The idea is that I want to launch a search query by entering something in an inputfield which is going to fire an ajaxcall (I could not think of anything better). The response of that ajaxcall has to be a kind of popup list with clickable items that is placed into another field on the initial page when clicking an item.
I have two questions:
Is there a better approach than ajax and how can I resolve the problem of the 'popup list' thing.
Second: I can make post ajaxcalls in Symfony2 with this kind of code:
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "post",
success: function(data) {
//some things here
}
But I thought it is a bit strange to use post and I wanted to use get.. Apparently this is not working as I can not retrieve my data in the controller..
EDIT: I forgot to post my controller where I am handling the ajax call, here is the code:
public function testGetAction(Request $request)
{
$data = $request->request->get('data');
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('EuropsimProductBundle:SimProfile')->find($data);
return new Response($entity); }
This is working fine with method: "post", but failing when I try to use "get".
I also read about typeahead and this is really close to what I meant, the thing is I want a custom little popup or something because the ajax is supposed to return an array of objects with multiple attributes that has to be shown and where mulitple items are selectable. You can see it as two steps where you first launch the searchquery which bring you to a kind of popup or something where you can select the desired rows for further use on the page.
Thanks in advance!
Hicy
You have to use method $request->query:
For GET method:
$data = $request->query->get('data');
For POST method:
$data = $request->request->get('data');
This really is not much a Symfony2 related question... but...
This code is javascript, if you want to use GET just change method to GET,
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "get",
success: function(data) {
//some things here
}
Then in Symfony create the route test_oostand do whatever you want on the controller to send "data" in the response.
Then on te success method process this data accordingly and create the needed view.
EDIT: Based on your new edit, you have an error accessing your data parameter, you should use query instead request
$data = $request->query->get('data');
I am trying to send and then get data from PHP on my server, but I don't think it sends the data.
My js code:
angular
.module('h2hApp', [])
.controller('mainCtrl', ['$scope', '$http', function(scope, http) {
scope.initGames = function() {
http({
method: 'POST',
url: 'apis.php',
data: {
url: someUrl
}
})
.success(function(data) {
console.log(data);
});
};
scope.initGames();
}]);
and my PHP file:
<?php
$url = $_POST['url'];
echo file_get_contents($url);
?>
The only thing I get in response is that error:
Notice: Undefined index: url in /my/path/apis.php on line 2
I made this working using jQuery but with AngularJS it doesn't seem to work. I'm new to Angular and I read some other problems like this. I tried things like adding headers and other things but nothing worked.
You can be forgiven for thinking that your PHP script should be expecting data in the $_POST variable as encoding your data as a query string has traditionally always been the default mechanism.
Angular however encodes the message body as a JSON object by default. As mentioned you could use the params instead however in the long run I'd argue that it's more flexible to conform on the server-side. For example you can read and decode the message body as follows:
<?php
$data = json_decode( file_get_contents('php://input') );
echo $data->url;
It should be 'params', not 'data'. See http://docs.angularjs.org/api/ng/service/$http#usage
Be sure to set the HTTP header, sort of like this:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
More info on using Post from AngularJS to PHP
You can use http.post() method -
Try this the code -
http.post('apis.php', {
url: someUrl
})
.success(function(data) {
console.log(data);
});
What is the bestHi everyone, a MVC3 newbie here! please take a look at these:
in my View page, i have there:
<div id = "AccounStatusDiv" class="display-field">
#Html.DisplayFor(m => m.AccountStatus)
<input id="btnBool" type="button" class="btnGrid ActStatBtn" value="#(Model.AccountStatus ? "Deactivate" : "Activate")" onclick="ChangeStatus()"/>
</div>
and a script:
<script type="text/javascript">
function ChangeStatus() {
$.post('#Url.Action("SetAccountStatus", "User")',
{ UserName: "#(Model.UserName)",
accountStatus: "#(Model.AccountStatus)" });
// change the display of the AccounStatusDiv elements, or maybe just reload the div element if possible. is it?
}
</script>
while in my Display Template, i have there:
<div id = "AccountStatusDiv" style="display:inline-block;">
<img src="#Html.Custom().ResolveImage((bool)Model ? imgPositive : imgNegative)" alt="#Model" />
<label> #ResourceManager.Localize(resource, display)</label>
</div>
in the controller:
public ActionResult SetAccountStatus(string userName, bool accountStatus)
{
SecurityManager.GetMembershipProvider().SetStatus(userName, !accountStatus);
return AjaxResult.JsonRedirect("/User/ViewUser?username=" + userName);
}
The results are shown only after I reload the page.
I want to display the updated img, label and btnBool elements right after clicking the btnBool without reloading the whole page. What is the best way in such case?
Please post your code suggestions, it would be a great help for me!
Thanks in advance!
You're only using $.post() to send data (request) to the server. AJAX can be two-fold: send a request, and receive the corresponding response. In your code, you're not receiving data back (or, at least, making the necessary arrangements so that you are).
If the SetAccountStatus action of your UserController is set to return some data back (maybe through return Json(), or similar), you can modify the $.post() call to receive it, and have your Javascript react accordingly using a callback function.
var data = {
UserName: "#Model.UserName",
accountStatus: "#Model.AccountStatus"
};
var call = $.post(
'#Url.Action("SetAccountStatus", "User")',
data
);
// set the success callback here
call.success(function (m) {
// the [m] variable contains the data returned by the server
// during the resolution of your call
// this will be called when your AJAX call succeeds,
// and you can use this opportunity to update the HTML DOM with new data
});
this is to event click in button and without refresh page
$("#btnBool").click(function(e){
e.preventDefault();
//to do your code, you can use `$.ajax` to request and get response from server
$.ajax({
url: '#Url.Action("SetAccountStatus", "User")',
type:"GET",
dataType: 'json',
data: { UserName: "#(Model.UserName)",accountStatus: "#(Model.AccountStatus)" },
async:'true',
success:function (data) {
alert(data);
//success to parsing json if you data type of your response is json
}
});
}
you can use web service to send request and get response from server , and to request,get response from server you can use $.ajax() in jquery http://api.jquery.com/jQuery.ajax/