I need to pass through $.ajax() method some form elements and an array too. How can i send serialize and array by ajax?
my code bellow:
function loadgraficosajax(){
var arr = ['331234','142323','327767'];
var data = $('#p-form').serialize;
$.ajax({
type: "POST",
url: "/page/show",
data: data,
dataType : 'html',
success: function (msg) {
$(document).ajaxComplete(function (event, request, settings) {
$('.has-error').removeClass('has-error');
$(document).off('ajaxComplete').off('ajaxSend');
$('#addajax').html(msg);
});
}
});
}
serialize is a method in jQuery, not a property, so you should call it in this way:
var data = $('#p-form').serialize();
and to pass your array you need to use param method and modify your array to be inside Object, where array name is object property:
var arr = { arr: ['331234','142323','327767'] };
var data = $('#p-form').serialize();
data += '&' + $.param( arr );
param will transform your object to serialised string:
console.log($.param( arr )); // "arr[]=331234&arr[]=142323&arr[]=327767"
var formData = new FormData($('#p-form')[0]);
var arr = ['331234','142323','327767'];
// append array to formData
formData.append('arr',JSON.stringify(arr));
$.ajax({
type: "POST",
url: "/page/show",
data: formData,
success:.....
You could bundle the two items together in a stringified object which you can send:
function loadgraficosajax(){
var arr = ['331234','142323','327767'];
var data = $('#p-form').serialize();
var request = {
array: arr,
elements: data
}
var data = JSON.stringify(request);
$.ajax({
type: "POST",
url: "/page/show",
data: data,
dataType : 'json',
success: function (msg) {
$(document).ajaxComplete(function (event, request, settings) {
$('.has-error').removeClass('has-error');
$(document).off('ajaxComplete').off('ajaxSend');
$('#addajax').html(msg);
});
}
});
}
Related
I cannot send JSON Data from HTML to PHP with jquery and always show fail status at console.log. Please check my code.
jsonObjects.domain = client_domain;
jsonObjects.pkg = client_package;
jsonObjects.company_name = client_company;
jsonObjects.company_email = client_email;
jsonObjects.personal_name = psn_name;
jsonObjects.personal_phone = psn_phone;
jsonObjects.personal_email = psn_email;
var JsonPush = new Array();
JsonPush.push(jsonObjects);
var JsonArray = JSON.stringify(JsonPush);
$.ajax({
type: "POST",
url: 'order.php',
data: JsonArray,
dataType: 'json',
})
.done(function (data) {
console.log('done');
console.log(data);
}).
fail(function (data) {
console.log('fail');
console.log(data);
});
Order.php file
<?php
$decoded = json_decode($_POST['data']);
var_dump($decoded);
?>
You don't need to stringify first, just post it in a keyed object and access via the key like this
let postData = { object: jsonObjects };
$.ajax({
type: "POST",
url: 'order.php',
data: postData,
dataType: 'json',
})
Then in php:
$jsonObjects = $_POST['object'];
note: you don't access the posted variable by the name of the object itself but rather the keys inside the posted object
You have no data parameter in your AJAX call. It should be:
data: { data: JsonArray },
But there really isn't any need to use JSON at all. You can just given an object as the data: option, and its properties will become POST parameters.
data: jsonObjects,
Then in PHP you can access $_POST['domain'], $_POST['pkg'], etc.
I'm currently working on a project with javascript and jquery.
I'm using a $.ajax call to ask the server for some data. This call is being made within an object I created.
On success, I want to update the data members of such object with the data recieved. It looks something like so:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
success: function ( data ) {
// update data
}
});
};
};
For passing the original object (Caller) to the succes function, I've tried the following:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
var _this = this;
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
success: function ( data ) {
// update data
_this.data1 = data.data1;
_this.data2 = data.data2;
}
});
};
};
Then I tried:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
_this: this,
success: function ( data ) {
// update data
var _this = this._this
_this.data1 = data.data1;
_this.data2 = data.data2;
}
});
};
};
And then:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
context: this,
success: function ( data ) {
// update data
this.data1 = data.data1;
this.data2 = data.data2;
}
});
};
};
In all the cases above, it seems that a copy of the object, rather than the original one, is being pass to the function, so the original values are not
changed.
Is there a way to change the originals values of the object or pass the original one? I hope you can help me, i've stuck with this for a while.
If you send a request to another site, you must do
crossDomain: true
or
If you want to do data return, you must do
async: true
Example:
var data_1 = 0;
ajax success function data_1 = data.data_1
return data_1;
I need to pass array of ids with $.ajax data variable. The array is a result of a function. If i declare this function outside $.ajax it sends array correctly. But if i put same function code inside $.ajax (which is preffered for me), i get it as a string.
function mySort(){ // Do not pass hidden clones
var items = [];
$('#fp_parameters_list').children().each(function(){
if ($(this).is(':visible')) {
items.push($(this).attr('data-parameter-id'));
}
});
return items;
}
// This gives correct ordering
$.ajax({
url: '/echo/json/',
type: 'post',
dataType: 'json',
data: {
ordering: mySort()
}
});
// This gives ordering as a string
$.ajax({
url: '/echo/json/',
type: 'post',
dataType: 'json',
data: {
ordering: function(){ // Do not pass hidden clones
var items = [];
$('#fp_parameters_list').children().each(function(){
if ($(this).is(':visible')) {
items.push($(this).attr('data-parameter-id'));
}
});
return items;
}
}
});
Here's fiddle: http://jsfiddle.net/vxLrN/7/
You can see that first request is sent with ordering as an array, while second pass ordering as string, although, functions are absolutely equal.
How can i put function inline and still get array result?
Thanks
Well make sure that you invoke this anonymous function in order to assign the proper result (array of strings) to the ordering parameter:
data: {
ordering: (function () { // Do not pass hidden clones
var items = [];
$('#fp_parameters_list').children().each(function() {
if ($(this).is(':visible')) {
items.push($(this).attr('data-parameter-id'));
}
});
return items;
})(); // <!-- Here call the anonymous function to get its result
}
Just use $.map to build the array directly instead
$.ajax({
url: '/echo/json/',
type: 'post',
dataType: 'json',
data: {
ordering: $.map($('#fp_parameters_list').children(':visible'), function(el) {
return $(el).data('parameter-id');
})
}
});
I have a array in jquery.Now as per my need i have to add each array values into single quotes as ..
var toc='INCOMING','INETCALL','ISD','LOCAL','STD'
But at present i have values like this ..
var toc=INCOMING,INETCALL,ISD,LOCAL,STD
And here is my codes ..
$.ajax({
type: 'GET',
url: 'getdata',
async:false,
dataType: "text",
success: function(data) {
var values = [];
values = data;
values=values.replace('[','');
values=values.replace(']','');
var array = values.split(",");
for(var i=0,len=array.length;i<len;i++)
{
if($.isNumeric(array[i]))
{
callcost.push(array[i]);
}
else
{
toc.push(array[i]);
}
}
alert(toc);
alert(callcost);
}
});
not sure if i got your question right but i guess you are messing up with all this replace/split/... logic. If the data object is an array just try this
$.ajax({
type: 'GET',
url: 'getdata',
async:false,
dataType: "text",
success: function(data) {
var array = JSON.parse(data);
$.each(array, function(i, val){
if($.isNumeric(val)) {
callcost.push(val);
}else{
toc.push(val);
}
});
}
});
I am trying to get all jqgrid data in one array and sending to servelet,so far I am try with this-
var rows= jQuery("#list").jqGrid('getRowData');
var paras=new Array();
for(var i=0;i<rows.length;i++)
{
var row=rows[i];
paras.push($.param(row));
//alert(paras[i]);
}
alert(paras);
$.ajax({
type: "POST",
url: "JQGridServlet?action=arraydata¶s="+paras,
data: paras.join('and'),
success: function(msg)
{
alert(msg);
}
});
but it send only first 'srno'.not whole array.
please any body suggest me to how to send array to servlet and how to access it on servlet.
Try this:
var griddata= $( "#list" ).getRowData();
var model = {
grid: griddata
};
var paras= JSON.stringify( model );
alert(paras);
$.ajax({
type: "POST",
url: "JQGridServlet?action=arraydata¶s="+paras,
data: paras.join('and'),
success: function(msg)
{
alert(msg);
}
});