insert key=>value pair in PHP from a submitted Javascript object - javascript

im trying to figure out how to properly insert key=>value pair to an array using array_unshift
this is my code.
Javascript/AJAX
var array= {};
array['name'] = name;
array['lname'] = lname;
$.ajax ({
type:"POST",
url:"some.php",
data: {array:array},
success: function(html) {}
});
PHP will then receive the array via POST
$array = $_post['array'];
//add additional key=>value pair in the array
array_unshift($array, "['middle']=>test");
return $array;
Im not getting any errors from it, i just dont see the value being printed from the function.
Printed Result:
Object {name: "John", lname: "Smith"}
edit:typo

I don't think you're doing it right...
You can't alter a JavaScript array (it's an object actually) via PHP. However, you can fetch new data and replace the JavaScript object.
Because I'm expecting an object, I might as well use the JSON format - thus use $.getJSON() instead. Note that this is a GET request on default.
var url = 'file.php';
var obj = {
name: name,
lname: lname
};
$.getJSON(url, { data:obj }, function(data) {
// replace object with new content
obj = data;
console.log(obj);
});
As for your PHP code:
// get data (remember we're using a GET request)
$data = $_GET['data'];
// add an index
$data['middle'] = 'test';
// echo data in JSON format
echo json_encode($data);

// not var array= {};
var person = {}
person['name'] = name;
person['lname'] = lname;

Rename the person to array like
var array= {};
array['name'] = name;
array['lname'] = lname;
$.ajax ({
type:"POST",
url:"some.php",
data: {array:array},
success: function(html) {}
});
Or send the person array as array
data: {array:person},
EDIT :.Simple try like
$array['middle'] = 'test';

Related

CodeIgniter - Form Validation on AJAX data(of multidimensional associative array) sent after stringification

This is a quick demo of javascript portion:
var student = {};
student['name'] = 'ABC';
student['dob'] = '1-1-2015';
student['address'] = {};
student['address']['home'] = 'somewhere on earth';
student['address']['office'] = 'near mars';
student['contactnum'] = {};
student['contactnum']['home'] = {};
student['contactnum']['home']['mob'] = '12345';
student['contactnum']['home']['phone'] = '987';
student['contactnum']['office'] = {};
student['contactnum']['office']['mob'] = '12345';
student['contactnum']['office']['phone'] = '987';
$.ajax({
type: "POST",
url: "<?php echo base_url('admin/ajax/addStudent');?>",
data: {'d': JSON.stringify( student ) },
contentType: 'application/json'
})
As you can see am sending this associative array object to the CodeIgniter page via AJAX. But the question is, how to use the FormValidation helper at the server side! To my belief, the validation helper only checks for single field names. Since all the validations needed for me is in that helper, I don't want to reinvent the wheel, but want to know how to write validation config for this data at CodeIgniter page!

Convert javascript object or array to json for ajax data

So I'm creating an array with element information. I loop through all elements and save the index. For some reason I cannot convert this array to a json object!
This is my array loop:
var display = Array();
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
I try to turn it into a JSON object by:
data = JSON.stringify(display);
It doesn't seem to send the proper JSON format!
If I hand code it like this, it works and sends information:
data = {"0":"none","1":"block","2":"none","3":"block","4":"block","5":"block","6":"block","7":"block","8":"block","9":"block","10":"block","11":"block","12":"block","13":"block","14":"block","15":"block","16":"block","17":"block","18":"block","19":"block"};
When I do an alert on the JSON.stringify object it looks the same as the hand coded one. But it doesn't work.
I'm going crazy trying to solve this! What am I missing here? What's the best way to send this information to get the hand coded format?
I am using this ajax method to send data:
$.ajax({
dataType: "json",
data:data,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
Using GET method because I'm displaying information (not updating or inserting). Only sending display info to my php file.
END SOLUTION
var display = {};
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
$.ajax({
dataType: "json",
data: display,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
}
To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:
// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
return oldJSONStringify(convArrToObj(input));
};
})();
And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)
Edit:
Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
jsFiddle with example here
js Performance test here, via jsPerf

Posting multiple objects in an ajax call

I have a list of data which is within multiple objects.
Each object has an ID and a status and then the main object has a type and a form id.
The problem I am having is posting result via ajax as it doesn't like the multiple objects.
This is the code I have:
var permissionsData = [];
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData.push(obj);
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: permissionsData
});
How can I wrap/send permission data?
How about changing your array to an object and using jQuery's param function.
var permissionsData = {};
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData[index] = obj;
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: $.param(permissionsData)
});
maybe you can use json2.js
it can parse the object to json string and parse the json string to object
you can use JSON.stringify method for parse object to json string

Passing string array from ASP.NET to JavaScript

I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?
I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);
This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];

How tp parse Json result which is returned with an arraylist in a webmethod?

This is a simplified code. I have a webservice (.asmx) as following:
I store some values in Test class and then store the class in an arraylist.
I do this two times in two different arraylists.
and then store these two array lists in a third arraylist.
and then pass this arraylist as output of webmethod.
private class Test
{
public string Id;
public string Name;
}
[webmethod]
public ArrayList RuleReport(long RuleId)
{
Test t = new Test();
t.Id = "1";
t.Name = "a";
ArrayList ar = new ArrayList();
ArrayList ar2 = new ArrayList();
ArrayList ar3 = new ArrayList();
ar.Add(t);
t = new Test();
t.Id = "2";
t.Name = "b";
ar2.Add(t);
ar3.Add(ar);
ar3.Add(ar2);
return ar3;
}
and in js file I want to parse he json result to read each Id and Name values of two arraylists.
id=1,name=a
id=2,name=b
this is my jquery code:
$.ajax(
{ url: " Ajaxes/Rules.asmx/RuleReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: "{'RuleId':'79'}",
async: false,
success: function(data) {
$.each(data.d, function(index, obj) {
alert(obj.d[0].Id);// something like this. How to do it???
})
}, error: function() { }
});
this is the json response in fire bug:
{"d":[[{"Id":"1","Name":"a"}],[{"Id":"2","Name":"b"}]]}
how to get every Id and Name values???
With your current setup inside $.each loop you are getting
[{"Id":"1","Name":"a"}]
as obj. As you can see it's a array of object with only one object as it's content. You can access that object with obj[0] and then their properties can be accessed with obj[0].Id and obj[0].Name
You can do this with the following code
$.each(data.d,function(index,obj){
var id = obj[0].Id;
var name = obj[0].Name;
// do what ever you want with them
})​
Working fiddle

Categories

Resources