I have a form and i wanted specific elements of the form which I got and stored the values in an array.
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var item_name = miniform.elements['itemId'].value;
var quantity = miniform.elements['quantityId'].value;
var amount = miniform.elements['amountId'].value;
var total = amount * quantity;
var cart = ["Item: ",item_name,"Quantity: ",quantity,"Amount: ",amount,"Total: ",total];
I would then like to convert this array into a JSON object and send it to a php file through ajax but its not working. Here is my ajax code:
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.stringify(cart),
success: function(){
console.log('Message Sent');
}
});
What could be the problem??
look the comma, it should be {"key":value, "key":value..} not {"key":,value, "key":,value..}
var cart = {"Item" : item_name, "Quantity" : quantity, "Amount" : amount, "Total" : total};
you are doing wrong .
please use this way
var cart = {"Item ":item_name,"Quantity ":quantity,"Amount ":amount,"Total ":total};
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.parse(cart),
success: function(){
console.log('Message Sent');
}
});
If you want to post the array Then you can use this way.
cart = [];
cart[0] = item_name;
cart[1] = quantity;
cart[2] = amount;
cart[3] = total;
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data:{cart:cart},
success: function(){
console.log('Message Sent');
}
});
Don't build it manually
Instead of building your Object or Array manually, which is prone to errors, do it like this:
Object
// Define your empty Object
var cart = {};
// Assign its properties
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = amount * quantity;
Array
Or if you prefer to have an array:
// Define your empty array
var cart = [];
// Assign its properties
cart['item_name'] = miniform.elements['itemId'].value;
cart['quantity'] = miniform.elements['quantityId'].value;
cart['amount'] = miniform.elements['amountId'].value;
cart['total'] = amount * quantity;
Now you have your cart Object or Array ready and you can call JSON.stringify on it:
JSON.stringify(cart);
You could just send the entire form using formdata(). Is there a reason you don't?
Anyway, it doesn't work because you are not creating a json object, but a normal array. There's a difference. You can actually just put the json directly into the ajax call and you don't have to stringify it.
var cart = {};
cart['Item'] = item_name;
cart['Quantity'] = quantity;
cart['Amount'] = amount;
cart['Total'] = total;
$.ajax({
url: 'https://www.google.com',
type: "POST",
//Datatype causes it to automatically become json and will expect json back
//return json back from php through json_encode($myArray);
dataType: "json",
data: cart,
success: function() {
alert('Message Sent');
}
});
in short: You used the wrong braces :)
I just changed it to an easier way of managing objects. The problem with your previous object was that it was built wrong. Should be something like:
var cart = {"Item":item_name,"Quantity": quantity,"Amount":amount,"Total":total};
I found a solution to my problem and I combined some your responses to find the answer.
$('#miniform').on('submit',function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var cart = {};
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = cart.amount * cart.quantity;
var jsonString = JSON.stringify(cart);
$.ajax({
url: url,
type: type,
data:{data:jsonString},
success: function(){
console.log('Email Sent');
},
error: function(error){
throw new Error('Did not work');
}
});
return false;
});
Related
I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example
I'm trying to send an array from Javascript to PHP.
function wishlist_save(arr){
$.ajax({
type: "POST",
url: "from.php?type=customers",
data: {info: JSON.stringify(arr) },
success: function(){
}
});
}
The array is set this way:
function getAll(){
var info = [];
var i = 0;
$(".desc").each(function(){
var value = $(this).text();
var qtt = $(this).attr('alt');
info[i] = [];
info[i]['desc'] = value;
info[i]['qtt'] = qtt;
i++;
});
return info;
}
If I output (with console.log(getAll())) the array in javascript I get the right values in Chrome Console:
[Array[0], Array[0], Array[0]]
->0: Array[0]
desc: 'John'
alt: 'Good'
->1: Array[0]
desc: 'Obama'
alt: 'Great'
But in PHP (from.php?type=customers) I can't figure out how to get those values..
$arr = json_decode($_POST['info']);
ChromePhp::log($arr[0]['desc']); // returns null
What am I doing wrong?
Solved.
The problem was on JSON.stringify(arr), which in some way didn't send properly the array to PHP.
So, all I needed was to adapt the function that retrieves the array:
var info = [];
info.push({desc: value, qtt: qtt });
Besides that, the AJAX only now need:
data: {info: arr },
And PHP:
I am having an issue where my collection property (in this case Parameters Collection) in my model is not being included in the JSON string created by the JSON.stringify function. Is there any reason why this might be happening? It basically just excludes it and adds the rest of the variables to the JSON string.
Here is the event:
EventAggregator.on('toggleFacet', function (facets) {
var facets = SearchOptionsUtil.getCheckedFacets(facets);
var sortOptions = SearchOptionsUtil.getSortOptions();
var searchOptions = new SearchOptionsModel();
for(var facet in facets){
var id = facet;
var value = facets[facet];
searchOptions.parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
var criteria = $.extend(facets, sortOptions);
location.hash = UriUtil.getUriHash(criteria);
RequestUtil.requestSearchResults(searchOptions);
});
Here is the fetch:
requestSearchResults: function (searchOptions) {
//fetch the results
var performSearchModel = new PerformSearchModel();
var searchOptionsJson = JSON.stringify(searchOptions);
performSearchModel.fetch({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({searchOptionsJson: searchOptionsJson}),
success: function (response) {
console.log("Inside success");
console.log(response);
},
error: function (errorResponse) {
console.log("Inside Failure")
console.log(errorResponse.responseText)
}
}) //have to wait for the fetch to complete
.complete(function () {
//show our regions
App.facetsRegion.show(new FacetListView({collection: performSearchModel.facets}));
App.resultsRegion.show(new ResultListView({collection: performSearchModel.results}));
//perform search fetch complete
});
}
and here is the model:
var SearchOptionsModel = Backbone.Model.extend({
defaults: {
parameters: ParameterCollection,
currentItemId: '{EE8AA76E-0A3E-437B-84D8-AD7FCBAF2928}',
sortBy: 0,
sortDirection: 'asc',
resultsPerPage: 10
},
initialize: function () {
this.parameters = new ParameterCollection();
//fetch calls an on change event.
this.on("change", this.fetchCollections);
},
url: function () {
return '/Services/Search/SearchService.asmx/SearchOptions';
},
parse: function (response) {
var data = JSON.parse(response.d);
return data;
},
fetchCollections: function () {
//when we call fetch for the model we want to fill its collections
this.parameters.set(
_(this.get("parameters")).map(function (parameter) {
return new ParameterModel(parameter);
})
);
}
});
UPDATE**
So I changed the way I create and add the parameters collection in the SearchOptionsModel and the JSON object is being formed correctly. I changed it from this:
var searchOptions = new SearchOptionsModel();
for(var facet in facets){
var id = facet;
var value = facets[facet];
searchOptions.parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
To this:
var parameters = new ParameterCollection();
//loop through all of the variables in this object
for(var facet in facets){
var id = facet;
var value = facets[facet];
parameters.add(new ParameterModel({id: id, values: value.split(',')}));
}
var searchOptions = new SearchOptionsModel({parameters: parameters});
Now the parameters are filled under the attributes in the model and I see an empty parameters variable on the searchOptions object (which was being filled before instead). Why is there a parameters variable set in the SearchOptionsModel if I am not explicitly creating it? Is it because the parameters default is set to a collection?
To convert a Backbone model to JSON, you must use the toJSON method:
model.toJSON();
Check doc here: http://backbonejs.org/#Model-toJSON
I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request
I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.
jQuery 1.4 and JSON library are loaded
var send_data = [];
$('.contact_check').each(function(i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts[' + this_id + '][message]');
var content = addslashes(msgbox.getContent());
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});
var encoded = JSON.stringify(send_data);
$.ajax({
type: 'POST',
url: 'http://localhost/test.php',
data: encoded,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
alert('jay');
}
});
Firstly,
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
does not seem to work. It says send_data[i] undefined. I've also tried:
send_data[this_id] = escape(content);
That does not seem to work either. The JSON string returns as []. What am I doing wrong?
You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.
send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);
or, better:
send_data[i] = {
id: this_id,
content: escape(content)
};
You have to make each send_data[i] an object first:
$('.contact_check').each(function (i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
var content = addslashes(msgbox.getContent());
send_data[i] = {};
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});