jquery POST data append not happening - javascript

I want to append some string before data output. Please help me figure out in how to do it. I have tried both HTML and append function, but I am not getting desired output.
Like if data = abc, it should show data = xyzabc and append xyz automatically to JSON data
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "a.php",
data: data,
success: function(data) {
$(".the-return").html(
data
);

just add the string "xyz" to the output data as "xyz" +data
try
$(".the-return").html( "xyz" + data );

Related

Post data $(form).serialize() and an array together

I'm having trouble sending the form via ajax. In addition to the fields populated by the user, I need to send an array of objects together.
AJAX POST:
submitHandler: function (form) {
$.ajax({
url: urlPost,
type: "POST",
dataType: "json",
data: $(form).serialize() + JSON.stringify(myArray),
success: function (resposta) {
alert('success');
}
});
}
If I send only $(form).serialize() I can, but with the array not.
ARRAY:
myArray = [{name: 'a', node: 1}, {name: 'b', node: 12}, ...];
Change your data: $(form).serialize() + JSON.stringify(myArray) to data: $(form).serialize() + "&arr=" + JSON.stringify(myArray). For Further help refer to https://stackoverflow.com/a/10398820/4518930
.serialize() + Some JSON String doesn't make sense.
According to the docs:
https://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded
notation.
So you're really taking a string like foo=bar&goat=baz and then adding a JSON string to like. Which makes no sense.
I think you'd be better off serializing the form yourself into a JSON object. Adding another key for your array and then dumping that object to JSON via JSON.stringify and that string is your request data.
After the tip of Cody Caughlan, I created an object that adds all the properties of the form and the array itself. The code looks like this:
var dataForm = {};
$($(form).serializeArray()).each(function(index, obj){
dataForm[obj.name] = obj.value;
});
dataForm["MyArray"] = myArray;
And ajax: post: dataForm.

Adding JSON results within quotation marks in a dataset

I am trying to the JSON values from a JQuery Ajax request into a dataset. The problem is that the dataset is in quotation marks and will not accept my parsed JSON values.
This is the original dataset:
{"value":"B", "number":"1492"},
{"value":"C", "number":"2782"},
{"value":"D", "number":"4253"},
{"value":"E", "number":"2702"}
I need for it to be accept the parsed JSON from the JQuery call.
$(document).ready(function(){
$("#ButtonClick").click(function(){
$.ajax({
url: "https://myUrl.com",
type: "get",
dataType: "json",
success: function(data) {
{"value":data.name, "number": data.currency},
{"value":data.nameA, "number":data.currencyA},
{"value":data.nameB, "number":data.currencyB},
{"value":data.nameC, "number":data.CurrencyC}
How can I go about doing this?

how to retrieve array in hidden field

I am storing my array in hidden field
var myarray = [];
if ($(this).prop('checked')) {
myarray.push(val);
$('#myhidden').val(JSON.stringify(myarray));
}
how can I retrieve that array ? because I want that array to past it to other page using jquery.ajax
I tried this
var retarray = $('#myhidden').val();
["110","118"]
when I send that using jquery.ajax
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: 'param1=' + param1 + '&param_array=' + retarray,
success: function(data) {
}
});
it gives me error because it is not an array.
Thank you in advance.
You're converting your array to a string here:
$('#myhidden').val(JSON.stringify(myarray));
If you need it to be an array, then you need to parse this array back from the string
var retarray = JSON.parse($('#myhidden').val());
for example:
var array = [1,2,3,4]; // create an array
var stringarray = JSON.stringify(array); // convert array to string
var array2 = JSON.parse(stringarray); // convert string to array
Try this
var retarray = encodeURIComponent($('#myhidden').val());
Your ajax request is is using the method POST and you have specified a data type of json which means your http request is sending json in the body.
So you can send your whole request message as json, like this:
// get json from input
var retarray = $('#myhidden').val();
// parse json into js
var arr = JSON.parse(retarray);
// create your request data
var data = { param1: param1, param_array: arr };
// stringify
var json = JSON.stringify(data);
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: json, // the json we created above
success: function(data) {
}
});
Then in your php script you can deserialize the json message to a php object like so:
$json = file_get_contents('php://input'); $obj = json_decode($json)
You can do this :
$('#myhidden').val(myarray.split("|")); //set "0|1".split("|") - creates array like [0,1]
myarray = $('#myhidden').val().join("|"); //get [0,1].join("|") - creates string like "0|1"
"|" is a symbol that is not present in array, it is important.

Handle json response in 2D array

I am into some weird situation where JSON response is-
{"Id":1,"service_name":"asdf","service_charge":11.32,"service_type":null,"service_comission":14.65,"service_desc":"","after_service_charge":23.55,"service_duration":60,"after_service_comission":11.22,"service_frequency":58,"tax_rate":15}
Condition-
In my form- #form-service-values I have input field of same name as it comes in response. Now I wanted to fetch value from JSON where data name matches.
For ex-
data.service_name logs me with value asdf
But Now here It is coming to me when name is dynamic of input fields as-
[object Object].service_name
Here Is how I am handling it in ajax-
function getDescService(Idservice) {
$.ajax({
url: '/Service/GetServiceDescriptions/',
type: 'post',
data: { Id: Idservice },
success: function (data) {
$('#form-service-values input[type="text"]').each(function () {
var name = $(this).attr('name');
$(this).val(data + "." + name);
})
}
});
}
I am trying to get this JSON response in a form where name of inputs are same as it comes in JSON response.
I just want to access JSON data fields.
How do I try on it?
In javascript, an object can be access like that data.name, where name is the key, or like that data["name"]
So you should do this
$(this).val(data[name]);
Instead of this
$(this).val(data + "." + name);
The first one is retrieving the value stored at the key name in the object data, while the second one is only writing text.

Create array of arrays from JSON

I am receiving after an ajax call the following as response using in php json_encode:
"['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]", "['2013-02-27', 6]", "['2013-02-28', 6]", "['2013-03-01', 3]", ...
How can I make in JavaScript from this an array of arrays? Is this even possible? I mean, I've tried with jQuery makeArray or with parseJSON with no success. What is the most preferred method?
Edit:
function submitForm(t) {
$.ajax({type:'GET', url: 'charts.php', data:$(page_id).serialize(), success:
function(response) {
var myFanRemovesData = new Array(response);
var myChart = new JSChart(chart_id, 'line');
myChart.setDataArray(myFanRemovesData);
I have to use the array of arrays to set myFanRemovesData with it
1) strip out the double-quotes ("):
var json = json.replace(/"/g, '');
2) wrap the whole thing in square brackets:
json = "[" + json + "]";
3) replace the single-quotes with double-quotes (because the singles won't parse):
json = json.replace(/'/g, '"');
4) parse the json string:
var arrays = JSON.parse(json);
Here is a working example. It will alert the first date in the first array. (note: the data is pulled from the DIV to simulate the AJAX call and to avoid me having to mess around with escaping quote characters)
Try:
var response = ["['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]"];
for (var i = 0; i < response.length; i++) {
var cleaned = response[i].replace(/'/g, "\"");
response[i] = $.parseJSON(cleaned);
}
DEMO: http://jsfiddle.net/hu3Eu/
After this code, the response array will contain arrays, made out of the original strings.
Just example.. because you haven't provide us with any code...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
dataType: 'json',
}).done(function( responde ) {
$.each(responde, function(i, v){
alert(v.0 + ' --- ' + v.1);
});
});
If you receive and expecting json you directly can use it as array/object :)
If its array you have to make a each loop so you can access each value..

Categories