retrieve javascript array from servlet - javascript

If data1 and data2 are javascript arrays
e.g ["aa","bb"] and ["xx","yy"]
$.ajax({
url : 'testServlet',
type: 'post',
data :
[{"array1" : data1},
{"array2" : data2}]
,
success : function(responseText) {
//...
}
});
how can I retrieve it from the testServlet??
or does my data have to be in the form of json format?(not familiar with this part)
I have tried using
String[] data= request.getParameterValues("array1");
but it is null

You can print out the request parameters and their values with the following snippet:
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
This should print all the parameters and values. This will help you check/debug what's retrieved at server side.

var test = [{"array1" : data1},
{"array2" : data2}];
$.ajax({
type: 'post',
url: 'testServlet',
dataType: 'JSON',
data: {
test: JSON.stringify(test)
},
success : function(responseText) {
//...
}
});
And, on testServlet
String json = request.getParameter("test");

Related

Cannot rewrite some html content with ajax

I wanna rewrite my HTML content with ajax. A part can be rewritten, but not for others. This is my js :
$.ajax({
url: 'http://localhost/ThePrpuz/public/mahasiswa/getDetail',
data: {
nim: nim
},
method: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
if ((data.gender) == 'Wanita') {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cewek.jpg');
$('#foto').attr('alt', 'Cewek');
} else {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cowok.jpg');
$('#foto').attr('alt', 'Cowok');
}
$('#nama').html(data.nama);
$('#nim').html(data.nim);
$('#univ').html(data.univ);
$('#fakultas').html(data.fakultas);
$('#jurusan').html(data.jurusan);
$('#penjurusan').html(data.penjurusan);
$('#ttl').html(data.tempat.concat(', ', data.tanggal));
}
});
The problem is, content with ** ID: ttl** can be rewritten. But did not for others. The result like this :
Nama :
Nim :
TTl : Somewhere, sometime
Univ :
Fakultas :
Jurusan :
Penjurusan :
Ih this case, I use console.log(data) to see that my ajax works or not. and in console, these are shown :
{
"nama": "Muhammad Fachri Saragih",
"tanggal": "2001-09-11",
"tempat": "Sibolga",
"gender": "Pria",
"univ": "Sriwijaya",
"fakultas": "Ilmu Komputer",
"jurusan": "Sistem Komputer",
"penjurusan": "Jaringan",
"nim": "9011281924069"
}
The method concat() is used to join two or more arrays, not strings!
Replace
$('#ttl').html(data.tempat.concat(', ', data.tanggal));
with
$('#ttl').html(data.tempat + ', ' + data.tanggal);
First, try to check the data type of the "data". I think it can't be accessed because the data type is still string, not JSON.
try to parse data to JSON.
$.ajax({
url: 'http://localhost/ThePrpuz/public/mahasiswa/getDetail',
data: {
nim: nim
},
method: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
console.log(typeof data);
var obj = JSON.parse(data);
if ((obj.gender) == 'Wanita') {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cewek.jpg');
$('#foto').attr('alt', 'Cewek');
} else {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cowok.jpg');
$('#foto').attr('alt', 'Cowok');
}
$('#nama').html(obj.nama);
$('#nim').html(obj.nim);
$('#univ').html(obj.univ);
$('#fakultas').html(obj.fakultas);
$('#jurusan').html(obj.jurusan);
$('#penjurusan').html(obj.penjurusan);
$('#ttl').html(obj.tempat.concat(', ', obj.tanggal));
}
});

How to use element name when initializing object in javascript?

I'm trying to get data using ajax function, but my code returns :
Uncaught SyntaxError: unexpected string..
Javascript :
var myParams = {
$('#csrf').attr('name') : $('#csrf').val(),
'module' : 'culinary',
'id' : '12',
}
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
success: function(response) {
reponse = $.parseJSON(response);
console.log(response);
}
});
One of my friends suggested to use this:
var myParams = [];
myParams[$('#csrf').attr('name')] = $('#csrf').val();
myParams['module'] = 'culinary';
myParams['id'] = '12';
But if I use the second method, the PHP function can't recognize the parameters.
What's the correct way to send parameters to an ajax function?
The issue is in your creation of the myParams object. To create a key using a variable you need to use bracket notation. Try this:
var myParams = {
'module': 'culinary',
'id': '12',
}
myParams[$('#csrf').attr('name')] = $('#csrf').val();
The second example you have doesn't work because you create an array, ie. [], not an object, {}.
Also note that if you set the dataType property of the request then you don't need to manually parse the response as jQuery will do it for you:
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
dataType: 'json',
success: function(response) {
console.log(response);
}
});
You should define new object {} and not new array [] :
var myParams = [];
Should be :
var myParams = {};
Hope this helps.

Sending JS array via AJAX to laravel not working

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!']);
}

Getting Record has been added successfully.[obect Object] instead of actual values [duplicate]

This question already has answers here:
What does [object Object] mean?
(12 answers)
Closed 8 years ago.
The script below normally returns values formatted in into JSON object as shown below:
{"Value":null,"Status":2,"Message":"Greetings."}
For the past couple of days, we have been getting:
Record has been added successfully.**[obect Object]**
Any ideas what could have gone wrong?
This is the code below.
<script type="text/javascript">
function CallService() {
//Creating an object to hold token form field
myToken = new Object();
myToken.Token = $("#token").val();
//Creating an object to hold form fields
myData = new Object();
// Creating variables to hold data from textboxes. First building associated details
myData.Address = $("#Address").val();
myData.CallerAcctNum = $("#CallerAcctNum").val();
myData.CallerAddress = $("#CallerAddress").val();
myData.CallerCellPhone = $("#CallerCellPhone").val();
myData.CallerCity = $("#CallerCity").val();
myData.CallerComments = $("#secondarysitecontact").val();
myData.CallerDistrict = $("#CallerDistrict").val();
myData.CallerEmail = $("#CallerEmail").val();
myData.CallerFax = $("#CallerFax").val();
myData.CallerFirstName = $("#CallerFirstName").val();
myData.CallerHomePhone = $("#CallerHomePhone").val();
myData.CallerLastName = $("#CallerLastName").val();
myData.CallerMiddleInitial = $("#CallerMiddleInitial").val();
myData.CallerState = $("#CallerState").val();
myData.CallerWorkPhone = $("#CallerWorkPhone").val();
myData.CallerZip = $("#CallerZip").val();
myData.City = $("#City").val();
myData.Details = $("#comments").val();
myData.District = $("#District").val();
myData.Location = $("#Location").val();
myData.ProblemSid = $("#RequestID").val();
myData.State = $("#State").val();
myData.StreetName = $("#StreetName").val();
myData.X = $("#X").val();
myData.Y = $("#Y").val();
myData.SiteContactDisplay = $("#sitecontact").val();
myData.Comments = $("#comments").val();
myData.Text1 = $("#deptId").val();
$.ajax({
type: "POST",
url: "proxyCreate.php",
data: {
data: JSON.stringify(myData),
token: myToken.Token
},
dataType: "json",
async: false,
success: function (response) {
alert("Record has been added successfully." + response );
window.location.reload();
}
});
return false;
}
</script>
alert() cannot print an {} object [object Object] unless you JSON.stringify it.
If you usually returned from your success this object:
{"Value":null,"Status":2,"Message":"Greetings."}
from your response argument, than you need to access a desired Object property like:
alert( response.Message );
otherwise, if you want to read fully the object do something like:
alert( JSON.stringify( response, null, "\t") );
Furthermore, to simplify your code I made some changes:
function v(id){ return $("#"+id).val(); } // Get value
function CallService() {
var myToken = v("token");
var myData = {
Token : v("token"),
Address : v("Address"),
CallerAcctNum : v("CallerAcctNum"),
CallerAddress : v("CallerAddress"),
CallerCellPhone : v("CallerCellPhone"),
CallerCity : v("CallerCity"),
CallerComments : v("secondarysitecontact"),
CallerDistrict : v("CallerDistrict"),
CallerEmail : v("CallerEmail"),
CallerFax : v("CallerFax"),
CallerFirstName : v("CallerFirstName"),
CallerHomePhone : v("CallerHomePhone"),
CallerLastName : v("CallerLastName"),
CallerMiddleInitial : v("CallerMiddleInitial"),
CallerState : v("CallerState"),
CallerWorkPhone : v("CallerWorkPhone"),
CallerZip : v("CallerZip"),
City : v("City"),
Details : v("comments"),
District : v("District"),
Location : v("Location"),
ProblemSid : v("RequestID"),
State : v("State"),
StreetName : v("StreetName"),
X : v("X"),
Y : v("Y"),
SiteContactDisplay : v("sitecontact"),
Comments : v("comments"),
Text1 : v("deptId")
};
$.ajax({
type: "POST",
url: "proxyCreate.php",
data: {
data: JSON.stringify(myData),
token: myToken
},
dataType: "json",
async: false,
success: function (response) {
console.log( response ); // open console and take a look.
alert("Record has been added successfully." + response ); // Nest with "." like response.something to print property you need
// window.location.reload(); // Do this later after you fix the bug
}
});
return false;
}
You have to specify which part of the object you want to print, for instance if you wanted the message:
$.ajax({
type: "POST",
url: "proxyCreate.php",
data: {
data: JSON.stringify(myData),
token: myToken.Token
},
dataType: "json",
async: false,
success: function (response) {
alert("Record has been added successfully." + response.Message );
window.location.reload();
}
});
You're trying to use alert, which takes an string and prints it on a dialog, and giving it an object, which... well, it's not an string. Your object CONTAINS strings, so you can access them and print them instead of trying to print the entire object, like show in the code above, where I whent to the message attribute of the response object.
Even simpler example: http://jsfiddle.net/9c0xLwcq/

ajax to pass array value , how to fetch array on called page

I have array containg image path ,
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
I am trying to pass this array with following code,
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: "sample value"
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
sample value is passed successfully , but how can i pass array to ajax and use it on another page?? i tried passing array and using with below code but it is not working
$data1 = $_REQUEST['genRep'];
echo "tested".$data1[0];
Try like
genRep = [];
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: GenerateReport
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
It will send your array as genRep
try to use json object. in object you can store your images path
var data=[]; // array
var data[0] = 'something';
var data[1] = 'something1';
var data = { 'name': name, 'email' : email, 'contact' : contact, 'type' : type, 'msg' : msg }; // object
$.ajax({
url : 'contact.php',
type : 'POST',
data : {contact:JSON.stringify(data)}, // for json object
data : {contact: data}, // for array
success : function (msg)
{
alert(msg);
}
})
contact.php
$info = $_POST['contact'];
$info = json_decode($info,true); // for json object
echo $info.name; // for json object
echo $info[0]; // will print something...
$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";
echo json_encode ($arr);
use this on the php page
and use the following to get the output
success:function(msg){
id_numbers = JSON.parse(msg);
alert(id_numbers)
}
Try:
$.ajax({
url: "generatePdf.php",
type: 'POST',
data: form_data,
dataType:"json",
success: function(data) {
alert(data[0]);
}
On the PHP side, you'll be wanting to print:
print json_encode($photos);
Made Some Change
print json_encode(array("photolist"=>$photos));
Then on the server, you'd access these with:
data.photolist[0]; //First photo
I have tested it, this will definitely work !
JS:
var GenerateReport = [];
GenerateReport[0] ="../images/Desert1.jpg";
GenerateReport[1] ="../images/Desert2.jpg";
GenerateReport[2] ="../images/Desert3.jpg";
GenerateReport[3] ="../images/Desert4.jpg";
GenerateReport[4] ="../images/Desert5.jpg";
$.ajax({
type: 'POST',
url: 'generatePdf.php',
data: 'image_array='+GenerateReport,
success: function(msg) {
alert(msg);
}
});
generatePdf.php :
<?php
$image_string = $_POST['image_array'];
$image_array = explode(",", $image_string);
print_r($image_array);
?>
Then you can loop over the $image_array to get the values.
try this
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
corrected code:
var imagedata = '';
$.each(GenerateReport,function(index,value))
{
if(imagedata=='')
{
imagedata = imagedata +'image'+index+'='+value;
}
else
{
imagedata = imagedata +'&image'+index+'='+value;
}
});
$.ajax({
type: "POST",
url: "generatePdf.php",
data: imagedata //pass string imagedata
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
imagedata should have sting like this:
image1=../images/Desert1.jpg&image2=../images/Desert2.jpg and so on
if(isset($_REQUEST['genRep']))
{
$data = $_REQUEST['genRep'];
print_r($data1);
echo "tested".$data1[0];
createPdf($data);
}
My code was correct , there was no value on index 0 , thats why it was not printing anything .My Mistake !!!

Categories

Resources