Solved

JQuery post - how to use a variable to contain my post parameters

Posted on 2009-03-30
3
1,737 Views
Last Modified: 2012-05-06
I'd like to use a function to "build" the parameters I want to send along a $.post

Something like this :

function makePostParm()
{
var t = '';
var parms = array("id","name");
var vals = array(100,"mark");
for(t=0;t<parms.length;t++){
   t = t + "," + parms[t] + ":" + vals[t];
}
}

function mypost(params)
{
   $.post("ajax.php", {params} );
}

var parameter = makePostParm();
mypost( parameter );

Is this at all possible or ??

Thx,
Mark
0
Comment
Question by:trg_dk
  • 2
3 Comments
 
LVL 12

Accepted Solution

by:
alien109 earned 500 total points
ID: 24019441
You should build an actual object, and not a string representation of it. You can do this through a function, or by explicitly setting them using json notation:

var params = {
    id:100,
    name:"mark"
}

$.post("ajax.php", params);

------
OR
------

function addParam(obj, key, value) {
    obj[key] = value;
}

var params = {};
addParam(params, "id", 100);
addParam(params, "name", "mark");

}

$.post("ajax.php", params);
0
 
LVL 12

Expert Comment

by:alien109
ID: 24019455
oops. left an extra "}" there at the end, right before the $.post call. That shouldn't be there!
0
 
LVL 2

Author Closing Comment

by:trg_dk
ID: 31564331
I made some minor changes - the function should return obj and the obj should be updated like this :

function addParams(obj,key,value)
{
obj[key] = value;
return obj;
}
var params = {};
params = addParams(params,"id",100);
etc.

At least that was what worked for me
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now