How do I convert data attributes to valid post (or get) data?
$('#nav').find('a').click(function(){
var params = $(this).data();
$.get({
type: "get",
url: "/view/",
data: params
});
})
I get this error:
POST http://127.0.0.1/Site1/%5Bobject%20Object%5D/ 404 (NOT FOUND)
You can use jQuery.param(),
$('#nav').find('a').click(function(){
var params = $(this).data();
params = $.param(params);
$.ajax({
type: "GET"
url: "/view/",
data: params
});
})
EDIT:
Actually the problem is you're using $.get() method like $.ajax().
$.get() doesn't accepts ajax settings object. Change it to $.ajax() than you don't need to use params.
jsFiddle DEMO
I think this should work:
$('#nav').find('a').click(function(){
var params = $(this).data();
$.get("/view/",params,function(){
//success callback
});
})
Without seeing the html it makes answering this more difficult but try something like this. $.post('YourUrl', { paramName : $("elementID").val(), paramName2 : $("#elementId").attr("data")}, function(data){ DoSuccessHere });
The jQuery get function takes an object for its data parameter, i.e.
$('#nav').find('a').click(function(){
var params = {
param1: 'foo',
param2: 'bar';
}
$.get({
type: 'get',
url: '/view/',
data: params
});
});
You can assign multiple values from multiple data sources in this way, e.g.
var params = {
id: $(this).id(),
name: $(this).attr('name');
}
Related
I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.
Try it once
url: '{{ route('addNewRoute') }}',
The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.
If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.
You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.
if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});
Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.
As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.
This is what I wrote in my factories.js:
app.factory('CustomerCompany', function($resource){
return $resource('/customer_companies/:id.json', {id: "#_id"}, {
'query':{method: 'GET', isArray:false},
'getByCustomerAccount':{
method: 'GET',
params: {customer_account_id: customer_account_id},
isArray:true,
url:'/customer_companies/get_by_account/:customer_account_id.json'
}
});
});
Because I want to fetch a list of customer_companies that belong to a particular customer_account so I need to supply a customer_account_id.
In my controllers.js,
app.controller('customerAccountEditController', function($scope, CustomerCompany) {
$scope.data = {};
var path = $location.path();
var pathSplit = path.split('/');
$scope.id = pathSplit[pathSplit.length-1];
var customer_account_id = $scope.id;
$scope.list_of_companies = [];
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
});
I get a customer_account_id not defined.
Where did I go wrong?
I think you don't need to define params inside your $resource & then URL will becomes url:'/customer_companies/get_by_account/customer_account_id.json' & while calling a method you need to pass the customer_account_id, from {customer_account_id: customer_account_id} so that it would create an URL with customer_account_id=2 somtehing like that.
Service
'getByCustomerAccount':{
method: 'GET',
//params: {customer_account_id: customer_account_id}, //removed it
isArray:true,
url:'/customer_companies/get_by_account/:customer_account_id'
}
Controller
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id + '.json'}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
This worked for me.
controllers.js
CustomerCompany.getByCustomerAccount({customer_account_id: customer_account_id}, function(data){
console.log(data);
//$scope.list_of_delegates.push(data);
});
services.js
app.factory('CustomerCompany', function($resource){
return $resource('/customer_companies/:id.json', {id: "#_id"}, {
'query':{method: 'GET', isArray:false},
'getByCustomerAccount':{
method: 'GET',
isArray:false,
url:'/customer_accounts/:customer_account_id/customer_companies.json'
}
});
});
What I changed:
on the server side, I decided to use /customer_accounts/:customer_account_id/customer_companies to render the results.
I realized that the data returned is always in object form, so I changed isArray in the $resource to false.
I pass the params like the way the Pankaj Parkar suggested in the controller when I call getByCustomerAccount
params: {customer_account_id: customer_account_id},
The customer_account_id you try to assign here is not defined.
Try params: {customer_account_id: '#customer_account_id'},
I want to sent some JSON data with ajax this is my script
$(document).ready(function () {
jsonObj = [];
$('.img-bg').map(function () {
var self = this;
var next = $(this).nextAll('.rectangle');
if (next.length > 0) {
next.map(function () {
item = {};
item.src = self.src;
item.left = $(this).css('left');
item.height = $(this).css('height');
jsonObj.push(item);
});
}
});
var data={ "firstName" : "Ray" };
jsonString = JSON.stringify(jsonObj);
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: jsonString,
success: function(response) {
console.log(response);
}
});
});
</script>
And jsonObj gives
[Object, Object, Object]
0: Object
height: "341px"
left: "10px"
src: "http://localhost/docAuto/test.jpg"
__proto__: Object
1: Object
height: "321px"
left: "54px"
src: "http://localhost/docAuto/image.jpg"
Output of jsonString
[{"src":"http://localhost/docAuto/test.jpg","left":"10px","height":"341px"},
{"src":"http://localhost/docAuto/image.jpg","left":"54px","height":"321px"},
{"src":"http://localhost/docAuto/image.jpg","left":"43px","height":"295px"}]
Both var is not send, but if I send data it's working. My Json file is wrong?
You need to pass the options to data as an object. Here's a fixed $.ajax call:
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonString },
success: function(response) {
console.log(response);
}
});
Your testajax.php should now see the jsonString in URL variable json.
edit: fixed my response. I misread your code due to the problems with indentation.
You don't need to use JSON.stringify to send a json object via the jQuery $.ajax() method... jQuery will take care of that conversion behind the scenes. Just use jsonObj as your data parameter.
You need to use POST in upper case.
I think your JSON is missing the key part. When I added the key: 'first', it worked. You got one mighty Json Array there:
JSON.stringify({ first: [{"src":"http://localhost/docAuto/test.jpg","left":"10px","height":"341px"},
{"src":"http://localhost/docAuto/image.jpg","left":"54px","height":"321px"},
{"src":"http://localhost/docAuto/image.jpg","left":"43px","height":"295px"}] })
JSFiddle link http://jsfiddle.net/jyrkim/suvG7/1/
Json Arrays, syntax etc link
I'm trying to make my page more efficient by using a separated ".js" file and trying to declare multilple used functions only one time. So I have to declare them in a way, that they caa be used for different situations. For Example passing different data.
Here is my Ajax Function in the "functions.js" file:
function CallAjax(type, url, data, div){
$.ajax({
type: type,
url: url,
data: data,
success: function (data) {
console.log(data);
$(div).html(data);
}
});
}
Here is my Code in my PHP File where I use this function and pass Parameters:
CallAjax('POST', 'about.php', '{ aufid : id }', '#con2');
My Problem is the "data" section. How can I declare it? The way I'm doing it doesn't work.
I don't want to use a new Ajax Function everytime when I need different data... I'm trying to trigger less functions as possible.
If you have any tips to make the page more efficient by trying to use less code, then it would be awesome if you mention them, too! Thank you!
you can do it like this:
var obj = {
aufid: 1
};
CallAjax('POST', 'about.php', obj, '#con2');
I propose js callback:
function CallAjax(type, url, data, div){
$.ajax({
type: type,
url: url,
data: data,
success: function (data) {
callback(data);
}
});
}
var obj = {
id:1
};
CallAjax('POST', 'about.php', obj, function(response){
$(div).html(response); //or other
});
or a more elegant way in promise:
function CallAjax(type, url, data){
return $.ajax({
type: type,
url: url,
data: data,
});
}
var obj = { id: 1 };
var jxhr = CallAjax('POST', 'about.php', obj);
jxhr.done(function(response){
//successful callback goes here...
}).fail(function(response){
//failure callback goes here...
}).always(function(response){
//always callback goes here...
});
: )
I'm stumped on this. I'm trying to send an AJAX call by iterating over all the inputs and collecting their val() which is a string.
So that my params would hopefully look like this:
"action"=>"create",
"type"=>"zip",
"value"=> ["12", "13", "14", "14", "15", "16"],
"controller"=>"admin/distributions",
"email_id"=>"3"}
This is what I have, but its giving me an [Object object] as a value :
$(".all_of_morris").live("click", function(){
id = window.location.href.split("/")[5]
$.ajax({
type: "POST",
url: "/admin/emails/" + id + "/distributions",
dataType: "script",
data: { $.each($(".morris input"), function(){
value: $(this).val();
}),
type: "zip" }
});
});
If you need an array for the value property, you can use the jquery map function:
$(".all_of_morris").live("click", function(){
var data = {};
data.value = $(".morris input").map(function(){
return $(this).val();
}).get();
data.type = 'zip';
//..etc
id = window.location.href.split("/")[5]
$.ajax({
type: "POST",
url: "/admin/emails/" + id + "/distributions",
dataType: "script",
data: data
});
});
How about using serialize()?
$('.morris input').serialize();
And you don't want to an .each within the json object. If pre-processing is required, build the payload in a variable first using whatever means you deem necessary, then pass that variable to the .ajax call.
e.g.
var value = /*get value array */; ...
var dataToPass = {
'action' : 'create',
'value': value,
'type' : 'zip',
...
};
$.ajax({
...
data: dataToPass,
...
});
It returns an object because the each of JQuery merely executes its contents, not return it. The data key also accepts strings as value so you could iterate through the contents, generate something like "action=create&type=zip&..." and then give that array as value for the data key.
data: { value: $('.morris input').map( function() {
return $(this).val();
}).get(),
type: 'zip'
},