Use array as jQuery POST Variables? - javascript

When sending data via POST or GET with jQuery you use for format { name:"value" } so I thought, is there a way to do it with this kind of code:
var postdata = array();
postdata['name'] = "data";
$.post("page.php", postdata, function(data)
{
alert(data);
}
I tried this, and it doesn't seem to work. Is there a proper way to do this?

What you are trying to initialize is an object, not an array. You can initialize objects in two ways:
var postdata = {};
Or:
var postdata = new Object();
Then you can assign keys and values just like you intended:
postdata['name'] = "data";
Or:
postdata.name = "data";
You can also build your object in the initialization phase:
postdata = {
name: "data"
}

Related

How to get value from Encode json data on php pages

I try to take object from my controller, when I console.log(response) it show the value correctly which is in
[
{
"itemValue":100,
"itemUnit":"2"
}
]
unfortunately I try to use the object like response.itemValue when I console it show undefined. I try var object = response. during the console it show the same value. Please I want to use the response data.
if(itemID){
$.ajax({
type:'POST',
url:'?syspath=ajax&controller=ajax&action=getActItemDose',
data: { 'itemId': itemID, 'itemType': itemType },
success:function(response){
// var obj = jQuery.parseJSON(data);
console.log(response);
var object = response;
var value = object.itemValue;
var unit = object.itemUnit;
console.log(object);
console.log(value);
}
});
}
This is controller where I encode the object into Json
$row = $getProcess->fetch();
$object[] = array(
'itemValue' => $row['each_dose'],
'itemUnit' => $row['unit_dose']
);
echo json_encode($object);
I recommend using the jQuery library. For parsing JSON, simply do
var obj = JSON.parse(data);
// Accessing individual value from JS object
alert(obj.itemValue);
alert(obj.itemUnit);
It worked, by changing this few item
$object[] = array();
into
$object = array();
and JSON.parse(data)
var object = JSON.parse(data);
value = object.itemValue;
unit = object.itemUnit;
Your response is an array. So you need to access it like
response[0].itemValue
or you can loop through the array
response.forEach(element => {
console.log(element.itemValue);
});
Below is the example
const response = JSON.parse(`[
{
"itemValue":100,
"itemUnit":"2"
}
]
`);
response.forEach(element => {
console.log(element.itemValue);
});

Put XMLHttprequest results into one string

I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery .ajax() POST Only checkboxes :checked

I am getting an error in my .ajax() function when attempting to pass in the checkboxes
Here is the code:
if(typeof($post) !== 'undefined'){
var $fname = $($post).attr('name').toString();
var data = {$fname : []};
alert($post);
alert($fname);
$($post + ":checked").each(function() {
data[$fname].push($(this).val());
});
}else{
var data = null;
}
The error I am getting in firebug is: data[$fname].push($(this).val()); is undefined
$post is just a class name passed into the function.. in this case it's .del-checked
The alerts sucessfully alert me the class name, and the checkbox name... in this case it's del[]
How can I get this to work in order to pass it to the data option of $.ajax?
Because you can not use a variable as a key when creating a new object
var data = {$fname : []};
is the same thing as doing
var data = {"$fname" : []};
You need to create the object and add the key with brackets
var data = {};
data[$fname] = [];
You can't use variables as keys unless you use bracket notation
if (typeof($post) !== 'undefined'){
var $fname = $($post).attr('name');
var data = {};
data[$fname] = [];
$($post).filter(":checked").each(function() {
data[$fname].push( this.value );
});
}else{
var data = null;
}
What about:
var data = $($fname).serialize();

Merge objects received from Ajax calls

I'm trying to merge two objects I receive as JSON via Ajax, but I can not access the variable and declaring it global. What am I doing wrong?
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
post.done(function( data ) {
postdata = jQuery.parseJSON(data);
});
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
postwatch.done(function( data ) {
postwatchdata = jQuery.parseJSON(data);
});
var postmerge = $.extend(postdata,postwatchdata);
console.log(postmerge);
The answer of postdata = jQuery.parseJSON(data) should be:
{"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be:
{"respwatch":"needlogin"}.
But to access the console, instead of getting postdata and postwatchdata merged, I get an empty object.
Object {} product.js:61
Edit:
I want when post and postwatch done, use data in product function.
The answer of postdata = jQuery.parseJSON(data) should be: {"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be: {"respwatch":"needlogin"}.
function product(data){
var obj = jQuery.parseJSON(data);
if (obj.resplike=='like'){
var respuesta = 'No te gusta';
}
else if(obj.resplike=='dislike'){
var respuesta = 'Te gusta';....blabla
I want to get in obj: {"resplike":"needlogin", "respwatch":"needlogin"}
You cannot handle the result of an asynchronous call like that. All operations done on a async function call must be done within the callbacks of that async method. read more about this in answer
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
$.when(post, postwatch).then(function(arg1, arg2){
var postmerge = $.extend(arg1[0], arg2[0]);
console.log(postmerge);
})
Also since you need to wait for the responses from two different requests you can use $.when() which will back the success handlers once all the passed promises are resolved.

How to display data from JsonRestStore

The following is the code sample I have written. I would like to get the data from REST services and print it on the screen. I could get the response from REST in the JSON format. But, I could not find the way to use store it in the JSONStore and use it. Please help me to resolve this issue.
dojo.provide("index.IndexService");
dojo.require("dojo.parser");
dojo.require("dijit.Editor");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.data.JsonRestStore");
var xhrArgs = {
url: "http://localhost:8080/RestApp/service/customers",
handleAs: "json",
contentType : "application/json",
load: function(data){
alert(data);
},
error: function(error){
alert(error);
}
}
dojo.ready(function(){
// Create a button programmatically:
var button = new dijit.form.Button({
label: "View Transactions...",
onClick: function(){
// Do something:
dojo.byId("result1").innerHTML += "Functionality yet to be implemented! ";
}
}, "progButtonNode");
alert('hi');
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
alert(store);
store.get(1).when(function(object){
alert(object);
// use the object with the identity of 3
});
//var deferred = dojo.xhrGet(xhrArgs);
//compliantStore = new dojox.data.JsonRestStore({deferred});
alert(deferred);
});
Returned JSON value is
{"employees":{"customers":[{"city":null,"accountNo":null,"name":"Name
1","id":1},{"city":null,"accountNo":null,"name":"Name
2","id":2}],"count":2}}
How would I retrive the values?
JsonRestStore items are actually simple JavaScript objects, therefore you can always directly read properties from items. Like
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
myValue = recipeStore.getValue(item,"foo"); //stored in myValue
get = store.getValue;
set = store.setValue;
save = store.save;
// then fetch an item
var myGetValue = get(item,"foo");
var setMyValue = set(item,"foo","bar");
In synchronous mode, one can fetch without providing a callback, by directly accessing the results property from the request object that is returned from the fetch operation:
var queryResults = store.fetch({query:"?tastes='good'"}).results;
var firstItem = queryResults[0];
Did you meant something like that.. Hope it helps

Categories