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);
});
Related
Below is my code for getting a data from api for 2 different URLs. The result is positive when I use $('#resultDiv1').html instead of opts[j].html. On using opts[j].html, I am getting error as opts[j].html is not a function'. Where is the mistake? Please help me.
var domain = "https://example.com/api#token=";
var detail = "/some_data"
$(document).ready(function() {
var token = ['260105', '49409' ];
var resultElement1 = $('#resultDiv1');
var resultElement2 = $('#resultDiv2');
var opts = ["resultElement1", "resultElement2"];
for (j=0; j<1; j++){
$.ajax({
url: domain + token[j] + detail,
method: 'get',
dataType: 'json',
success: function(response) {
opts[j].html(response.data.candles[response.data.candles.length - 1][4]);
}
})
}
});
That won't work because "resultElement1" and "resultElement2" are two different strings in the opts array. To use the selected elements, you need to create array using the variables resultElement1 and resultElement2, like this:
var opts = [resultElement1, resultElement2];
Also, your for loop will only work for resultElement1, because you end the iteration as soon as j becomes 1.
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;
});
I have this ajax json function where I use to send request and pull json response data (refer below)
//global array
var coaum_creation_date = [];
var coaum_arrears = [];
var coaum_wupdate= [];
var coaum_completed = [];
var coaum_pending = [];
var coaum_overdue = [];
//chart rendering
function get_coaum_chart(){
$.ajax({
url: $("body").attr("data-link") + "/get-coaum-chart",
type: 'post',
dataType: 'json',
data: { request : 'get coaum chart'},
beforeSend: function(){
},
success: function(response){
if(response.success){
console.log(response);
//clear the array objects
coaum_creation_date = [];
coaum_arrears = [];
coaum_wupdate= [];
$.each(response.chart_data, function(index, value){
coaum_creation_date.push(value.creation_date);
coaum_arrears.push(parseInt(value.arrears));
coaum_wupdate.push(parseInt(value.with_updates));
});
}
}
});
}
get_coaum_chart();
and there is the json response along the error (refer to the image below)
any ideas, clues, recommendations, suggestions, help?
Just guessing here, but it can be because you can use $.each on Objects, but your response.chart_data seems to be a JSON string.
Try using $.parseJSON() (doc):
$.each($.parseJSON(response.chart_data), ...
Hope it helps.
I have a nested loop. in the inner most loop I am creating the array and when the control comes out of the inner loop, then I am coppying the entire array formed in the inner loop to the new array.
The problem is that the values are getting over written in the end.
The data I have will go for 2 outer loop and each loop will have 5 and 24 inner loops respectively.
But in the end the total data I get is the data from the last loop.
Here is the js code:
$(document).ready(function(){
$.ajax({
url: "Sample.xsd",
dataType: "html",
success: function(data){
var xmlObj = $.parseXML(data);
var buff = $(xmlObj).find("xs\\:complexType");
var xmlObj1 = []; var buff1 = [];
var j = 0;
$(buff).each(function(i){
buff1.splice(0, buff1.length);
$this = $(this);
$this.find("xs\\:element").each(function(index){
buff1[index] = $(this).attr('name');
});
xmlObj1[j] = buff1;
console.log(xmlObj1);
j++;
});
console.log(xmlObj1);
},
error: function(err){
}
});
});
If you want I can attach the xsd file as well. But I dnt think its important.
Thank you.
Honestly I think you are overdoing it. The following should give you the expected result:
$(function() {
$.ajax({
url: "Sample.xsd",
dataType: "html",
success: function(data) {
var xmlObj = $.parseXML(data), xmlObj1 = new Array(),
buff = $(xmlObj).find("xs\\:complexType");
$(buff).each(function(i) {
var buff1 = new Array();
$(this).find("xs\\:element").each(function(ii) {
buff1[ii] = $(this).attr('name');
});
xmlObj1[i] = buff1;
});
console.log(xmlObj1);
},
error: function(err) {
console.log(err);
}
});
})
jsFiddle based on similar idea.
Try to reassign it as empty to the array value after it is assigned before it starts a new loop.
You can make buff1 as a local variable to the $(buff).each loop.
$(document).ready(function(){
$.ajax({
url: "Sample.xsd",
dataType: "html",
success: function(data){
var xmlObj = $.parseXML(data), xmlObj1 = [];
var buff = $(xmlObj).find("xs\\:complexType");
$(buff).each(function(i){
var buff1 = [], $this = $(this);
$this.find("xs\\:element").each(function(index){
buff1.push($(this).attr('name'));
});
xmlObj1.push(buff1)
});
console.log(xmlObj1);
},
error: function(err){
}
});
});
Can someone help me to convert these lines into one for loop?
var optie1 = "";
if($('#form #optie1_check').is(':checked')) {
optie1 = $('#form #optie1_naam').val();
}
var optie2 = "";
if($('#form #optie2_check').is(':checked')) {
optie2 = $('#form #optie2_naam').val();
}
I can't seem to find my answer on Google, don't really know how to search for it.
I want something like this:
for loop (i) {
var str = "optie" + (i+1) + "_check";
var str2 = "optie" + (i+1) + "_naam";
if($('#form #str').is(':checked')) {
opties = $('#form #str2').val();
}
}
And opties is an array I will be putting all the values in, so I can pass it later on with:
$.ajax({
type: "POST",
url: "voegOptiesToe.php",
data: "opties="+opties,
...
}
you can simply use .serialize() which encode a set of form elements as a string for submission
http://api.jquery.com/serialize/
For example,
$.ajax({
type: "POST",
url: "voegOptiesToe.php",
data: $('form').serialize(),
...
}
var opties = new Array();
for (i=1; i<=2; i++) {
var str = "optie" + i + "_check";
var str2 = "optie" + i + "_naam";
if($('#form #'+str).is(':checked')) {
opties.push($('#form #'+str2).val());
}
}
JSFiddle Example
var optie,i=1;
$('#form #optie'+i+'_check').is(':checked').each(function(){
optie+= $('#form #optie'+i+'_naam').val();
i++;
});
If you keep the same name for both the checkboxes, by default you can retrieve the value as an array in server side.
Or try this:
values = []
$("#form input[type='checkbox']")
.filter(function(i,el){
return $(el).is(':checked');
})
.each(function(i, el){
arr.push($(el).val());
})
And you can send the values array to ajax post data.