Sending JS array via AJAX to laravel not working - javascript

I have a javascript array which I want to send to a controller via an ajax get method.
My javascript looks like this:
var requestData = JSON.stringify(commentsArray);
console.log(requestData);
//logs correct json object
var request;
request = $.ajax({
url: "/api/comments",
method: "GET",
dataType: "json",
data: requestData
});
I can tell that my requestData is good because I am logging it and it looks right.
and the controller is being accessed correctly (i know this because I can log info there and I can return a response which I can log in my view after the response is returned).
when trying to access requestData I am getting an empty array.
My controller function that is called looks like:
public function index(Request $request)
{
Log::info($request);
//returns array (
//)
//i.e. an empty array
Log::info($request->input);
//returns ""
Log::info($_GET['data']);
//returns error with message 'Undefined index: data '
Log::info(Input::all());
//returns empty array
return Response::json(\App\Comment::get());
}
And I am getting back the response fine.
How can I access the requestData?

Dave's solution in the comments worked:
Changed ajax request to:
request = $.ajax({
url: "/api/comments",
method: "GET",
dataType: "json",
data: {data : requestData}
});

This is how push item in an array using jQuery:
function ApproveUnapproveVisitors(approveUnapprove){
var arrUserIds = [];
$(".visitors-table>tbody>tr").each(function(index, tr){
arrUserIds.push($(this).find('a').attr('data-user-id'));
});
$.ajax({
type:'POST',
url:'/dashboard/whitelistedusers/' + approveUnapprove,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {data : arrUserIds},
success:function(data){
alert(data.success);
},
error: function(e){
//alert(e.error);
}
});
}
And this is how I access them in my controller
//Approve all visitors
function ApproveAllWhitelistedUsers(Request $request){
$arrToSend = request('data');
foreach ($arrToSend as $visitor) {
$vsitor = User::findOrFail($visitor);
$vsitor->update(['is_approved'=> '1']);
}
return response()->json(['success'=>'Accounts approved successfully!']);
}

Related

How can I get post parameters on ajax request in Symfony 3

I have an ajax request working fine. My problem is I do not really know how to use correctly my controller to get the datas in the format I would like.
I would like to use this kind of method:
$request->request->get('pseudo'); // will return "bob"
Here is my controller code:
public function mainPlayAction(Request $request)
{
if ($request->isXmlHttpRequest())
{
$allContent = $request->getContent(); // will return a string with this format "selectedBalls=34&selectedStars=11"
$selectedBalls = $request->request->get('selectedBalls'); // will return null
$selectedstars= $request->request->get('selectedStars'); // will return null
$all = $request->request->all(); // will return Array[0]
$response = [
'allContent' => $allContent,
'selectedballs' => $selectedBalls,
'selectedStars' => $selectedStars,
'all' => $all,
'success' => true,
"status" => 100
];
return $this->json($response);
}
}
Here is my ajax code
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: {
'selectedballs': selectedBalls,
'selectedStars': selectedStars,
'countGames': countGames
},
success: function (response) {
window.console.log(response);
},
})
You simply need to call ->get() on Request object to get the data passwed along with AJAX Request.
Like this,
$selectedballs=$request->get('selectedballs');
$selectedStars=$request->get('selectedStars');
$countGames=$request->get('countGames');
I found a good answer.
I deleted this line of code from my ajax request
contentType: "application/json; charset=utf-8"
And now I can retrieve my datas using
$request->get('selectedBalls');

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

Access instance variable from View

I have this call in my View:
$.ajax({
type: "GET",
url: "/appointments",
data: "dog_id="+ dog_id
});
My route:
match '/appointments', to: 'appointments#index', via: 'get'
Controller action:
def index
#appointments = Appointment.where("dog_id = ?", params[:dog_id])
#appointments = Appointment.all
end
Both of these solution don't work. When I try to fetch events from appointment I receive a message:
undefined method `each' for nil:NilClass
I'm trying to get all appointments in View:
<% #appointments.each do |appointment| %>
Any ideas what is wrong with this code?
For this ajax call, json return a data, for this you not able to access directly in rails
so u can try the code like this,
$.ajax({
type: "GET",
url: "/appointments",
dataType: "json",
data: "dog_id="+ dog_id,
success:function(data){
alert(data);
}
});
that 'data' return like an [object Object] , You can loop it and get instance value
ex
success(data){
var x = new Array();
alert("created new array");
for (var i=0;i
{
x[i] ,x[data[i].toString()]=function(){};
} }
x returns a instance variable value now you can access it in your view.

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Categories

Resources