Help with 2D Graphics - How do I send Variable data to paint method?

I am working on a program that figures mortgage payments and an amortization schedule when a user inputs the principle, APR, and term length in years. After it figures all of those, I want to be able to display a chart that shows the principle and interest amounts for each year. My problem is, how do I get my loan information into my paint method so that I can draw a chart using that data? Any help would be greatly appreciated. The graph class in the code below is called after pressing a "Display Graph" button from my GUI.
I'm pasting my code below. This does not include my main method or my GUI method. I can post those if necessary. Here is my code so far:
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.io.*;
import java.lang.Math;
public class Graph extends JFrame
     public Graph(double dCurrentBalance, double dMonthlyPmt, double dRate, int iTime)
          final double balance = dCurrentBalance;
          JFrame graphFrame;
          int iCounter = 0;
          int iPmtNumber = 0;
          double dCurrentInt = 0.0;
          double dCurrentPrinciple = 0.0;
          double dMPR = 0.0;
          int yCoordInt = 0;               //integer for Y coordinate for Interest
          int yCoordPrinciple = 0;     //integer for Y coordinate for Principle
          iTime *= 12;               //determine number of months for this loan
          iCounter = iTime;          //set loop counter to number of months for this loan
          dMPR = dRate/12;          //determine monthly periodic rate
          graphFrame = new JFrame ("mCalc Graph");
          graphFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          graphFrame.setSize(800,600);
          graphFrame.setResizable(false);
          // center graphFrame on the screen
     Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize();
     Dimension FrameSize = graphFrame.getSize();
     if (FrameSize.height > ScreenSize.height)
     FrameSize.height = ScreenSize.height;
     if (FrameSize.width > ScreenSize.width)
     FrameSize.width = ScreenSize.width;
     graphFrame.setLocation((ScreenSize.width - FrameSize.width) / 2,
               (ScreenSize.height - FrameSize.height) / 2);
          //Displays graphFrame
          Graphic graphicPane = new Graphic();
          graphFrame.add(graphicPane);
          graphFrame.setVisible(true);
          //This loops until all payments have been figured
          for (; iCounter > 0; )
     iPmtNumber++;
     dCurrentInt = dCurrentBalance * dMPR;
     dCurrentPrinciple = dMonthlyPmt - dCurrentInt;
     dCurrentBalance = dCurrentBalance - dCurrentPrinciple;
               if (iPmtNumber%12 == 0)
//           System.out.println("dCurrentBalance = " + dCurrentBalance);
//                    System.out.println("Payment # = " + iPmtNumber);
//                    System.out.println("dCurrentInt = " + dCurrentInt);
//                    System.out.println("dCurrentPrinciple = " + dCurrentPrinciple);
     iCounter = iCounter-1;
          } //end for loop
     } //end Graph constructor
/* This class needs to be personalized to include my own variable names,
*     etc. I also need to find a way to bring in data from the Graph class.
     class Graphic extends JPanel
          public void paintComponent(Graphics comp)
                         int i; // Declare the variables used to generate the chart
float xLoc = 50; // Location of the X Axis along Y
float yLoc = 50; // Location of the Y Axis along X
Line2D.Float LnA; //
super.paintComponent(comp);
               // Establish a tie between this subroutine and the Graphic
Graphics2D comp2D = (Graphics2D) comp;
// Cast the Graphics named comp to a Graphics2D as comp2D
comp2D.setColor(Color.white);
// Set the background color
comp2D.fillRect(0,0,800,600);
// Draw the X and Y axis
comp2D.setColor(Color.black); // Set the pen color to black
Line2D.Float YAxis = new Line2D.Float(50,50,50,getSize().height - 50); // Define the Y-Axis
Line2D.Float XAxis = new Line2D.Float(50F,getSize().height - 50F, getSize().width -50F, getSize().height -50F); //Define the X-Axis
comp2D.draw(YAxis); // Draw the Y-Axis
comp2D.draw(XAxis); // Draw the X-Axis
Font font = new Font("Dialog", Font.BOLD, 12); // Set the font for the Axis labels
comp2D.setFont(font);
float increment = 15;
// Draw the line
xLoc += increment;
comp2D.setColor(Color.red);
/* Need to find a way to bring in my own data to use for the
* yLoc variables.
for (i=1; i<=45; i++)
{ // Begin making the graph
if (i < 30)
     yLoc += increment;
} else {
     yLoc -= increment;
// Scale the location to the graph height
LnA = new Line2D.Float( xLoc, getSize().height - 50F , xLoc, yLoc); // Create the line
comp2D.draw(LnA); // Draw the line
xLoc += increment;
                         }//end for
               }//end paintComponent
          } //end class Graphic
} //end class Graph
Any help would be GREATLY appreciated! Thanks.
Message was edited by:
russedl
My email address iss [email protected] if you wish to reply privately. I can send my entire program code if that will help. Thanks!

Hi Deca,
You can use the CmdExecuteSync method of the DIAdem.TOCommand interface to set the value of a text channel. For example passing the string "CHT(1,1) := 'test'" as a parameter to the CmdExecuteSync method will set the 1st row of the 1st channel to "test". Please refer to the DIAdem help for more documentation on the CHT function.
I hope this helps! Please post back if I wasn't clear enough in explaining how to do this or if you have any problems getting it to work.
Regards,
Sarah Miracle
National Instruments

Similar Messages

  • I purchased Adobe Acrobat x Pro recently and installed it, I have compatibility issues vision 2013. The adobe pdf converter  plug in stays inactive despite all my efforts to activate it, I need help with this? How can i get the plug in

    I purchased Adobe Acrobat x Pro recently and installed it, I have compatibility issues vision 2013. The adobe pdf converter  plug in stays inactive despite all my efforts to activate it, I need help with this? How can i get the plug in to work with Visio 2013?

    For MS Visio (any version) only the appropriate version of Acrobat *PRO* provides PDFMaker for Visio.
    For Visio 2013 specifically you must have Acrobat XI Pro (updated to at least 11.0.1).
    See: 
    http://helpx.adobe.com/acrobat/kb/compatible-web-browsers-pdfmaker-applications.html  
    Be well...

  • I purchased Adobe Acrobat x Pro recently and installed it, I have compatibility issues vision 2013. The adobe pdf converter  plug in stays inactive despite all my efforts to activate it, I need help with this? How can i get the plug in to work with Visio

    I purchased Adobe Acrobat x Pro recently and installed it, I have compatibility issues vision 2013. The adobe pdf converter  plug in stays inactive despite all my efforts to activate it, I need help with this? How can i get the plug in to work with Visio 2013?

    For MS Visio (any version) only the appropriate version of Acrobat *PRO* provides PDFMaker for Visio.
    For Visio 2013 specifically you must have Acrobat XI Pro (updated to at least 11.0.1).
    See: 
    http://helpx.adobe.com/acrobat/kb/compatible-web-browsers-pdfmaker-applications.html  
    Be well...

  • How can i send the data from WD to SMARTFROMS to fill it?

    Hi All,
    how can i send the data from WD to SMARTFROMS to fill it?
    Best Regards

    Hello
    After conferring with a colleague, the following response may help:
    The Smart Form doesn't have any special integration in WebDynpro.
    Therefore the application should implement it especially.
    Steps:
    1) Call of Smart Forms in mode GET_OTF
    2) Convert OTF to PDF
         3) Show the PDF in WD Context Node
    Similar topic was discussed here:
    Re: Displaying Smartforms in Webdynpro ABAP
    Thanks
    Kind Regards
    Toros Aledjian
    Edited by: Toros Aledjian on Nov 29, 2010 8:43 AM

  • Can someone help with a previous post labeled "Writing to a data file with time stamp - Help! "

    Can someone possibly help with a previous post labeled "Writing to a data file with time stamp - Help! "
    Thanks

    whats the problem?
    Aquaphire
    ---USING LABVIEW 6.1---

  • Need help with using graphics in swing components

    Hi. I'm new to Java and trying to learn it while also developing an application for class this semester. I've been following online tutorials for about 2 months now, though, and so I'm not sure my question counts as a "new to Java" question any more as the code is quite long.
    Here is the basic problem. I started coding the application as a basic awt Applet (starting at "Hello World") and about a month in realized that Swing components offer better buttons, panels, layouts, etc. So I converted the application, called BsfAp, to a new JApplet and started adding JPanels and JComponents with layout managers. My problem is, none of the buffered graphics run in any kind of JPanel, only the buttons do. I assume the buffered graphics are written straight to the JApplet top level container instead but I'm not entirely sure.
    So as to not inundate the forum with code, the JApplet runs online at:
    http://mason.gmu.edu/~dho2/files/sensor.html
    The source code is also online at:
    http://mason.gmu.edu/~dho2/files/BsfAp.java
    What I would like to do is this - take everything in the GUI left of the tabbed button pane and put it into a JScrollPane so that I can use a larger grid size with map display I can scroll around. The grid size I would like to use is more like 700x1000 pixels, but I only want to display about 400x400 pixels of it at a time in the JScrollPane. Then I could also move this JScrollPane around with layout manager. I think this is possible, but I don't know how to do it.
    I'm sure the code is not organized or optimized appropriately to those of you who use Java every day, but again I'm trying to learn it. ;-)
    Thanks for any help or insight you could provide in this.
    Matt

    Couple of recs:
    * Don't override paint and paint directly on the JApplet. Paint on a JPanel and override paintComponent.
    * The simplest way to display a graphic is to put an image into an ImageIcon and show this in a JLabel. This can then easily go inside of the JScrollPane.
    * You can also create a graphics JPanel that overrides the paintComponent, draw the image in that and show that inside of the JScrollPane.
    * don't call paint() directly. Call repaint if you want the graphic to repaint.
    Here's a trivial example quickly put together:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.awt.RenderingHints;
    import java.awt.geom.Ellipse2D;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class BsfCrap extends JApplet
        private JPanel mainPanel = new JPanel();
        private JScrollPane scrollPane;
        private JPanel graphicsPanel = new JPanel()
            @Override
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g;
                RenderingHints rh = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHints(rh);
                Paint gPaint = new GradientPaint(0, 0, Color.blue,
                    40, 40, Color.magenta, true);
                g2d.setPaint(gPaint);
                g2d.fill(new Ellipse2D.Double(0, 0, 800, 800));
        public BsfCrap()
            mainPanel.setPreferredSize(new Dimension(400, 400));
            mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            graphicsPanel.setPreferredSize(new Dimension(800, 800));
            graphicsPanel.setBackground(Color.white);
            scrollPane = new JScrollPane(graphicsPanel);
            scrollPane.setPreferredSize(new Dimension(300, 300));
            mainPanel.add(scrollPane);
        public JPanel getMainPanel()
            return mainPanel;
        @Override
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        setSize(new Dimension(400, 400));
                        getContentPane().add(new BsfCrap().getMainPanel());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }

  • Help with BufferedImage - Graphics updating

    Hello All-
    I will try to explain the best I can, still new to Java2D so little confused
    Hopefully the explanation makes a little bit of sense....
    I have a tabbedPane, one tab with no graphics and the other tab full of graphics
    The tab with the graphics on it is basically a bunch of rectangles that will change color depending on real time data I am pulling from a Mysql DB
    For sake of performance I only want to have to repaint those rectangles when the data from the DB changes (i.e. repaint the rectangles when the bit changes from 1=good to 0=bad)
    Any help on how to start implementing this would be absolutely wonderful
    or if I could explain something any better please ask.
    Thank you in advance
    Janduzerbots

    If you're thinking of just grabbing the graphics image of some component on the fly for rendering, that
    wouldn't work well. Here is a link to some tips on doing your own drawing.
    Again, yes, you may have to define your own component class. The only other alternative I can think of is to have a JLabel
    that has an ImageIcon that holds your BufferedImage, and you update this by calling repaint after updating
    the BufferedImage.

  • Not exactly iweb - need help with a graphic for my site

    This doesn't fit anywhere so dumping it here. I drew by hand a graphic I want to use with iweb to put on my site as my site's logo. Main problem is that getting the background transparent isn't working well as when it was scanned the scanner didn't back the background "pure" white. I have tried adjusting the whitepoint and setting the color depth down, but still no good. I don't know a ton about graphic program use. I have an older copy of graphic converter that came on this powerbook when i got it. I would be fine having the graphic loose the marker look and have solid fill colors - just I am not good enough with computer drawing tools to do it on the computer! So I either need to get a volunteer to help me out, or some help with some detailed instructions to get this to work out... (also I am broke so no cost/shareware is only option here)
    many thanks!!!!
    I can get you a scanned jpg of the pic if needed.

    THANK YOU/___sbsstatic___/migration-images/migration-img-not-avail.png so the tolerance makes it not care so much about the gradations in color? what else is tolerence good for?
    I have a cleaner copy now after someone suggested GIMP, so played with it last night - though couldn't figure out transparency - that was clear on converter- just not cooperative till these wonderful directions.
    So now I know how to do it without messing with the pic, and with messing with it - both good lessons and got a bit brighter color out of the deal.
    many thanks for the straightforward and clear directions, they worked perfectly/___sbsstatic___/migration-images/migration-img-not-avail.png extra strars for you/___sbsstatic___/migration-images/migration-img-not-avail.png

  • Color printing help with large graphics Reader 11.0.3

    Good morning!  We recently upgraded to 11.0.3.  Windows 7 64-bit.  We've had issues printing large color graphics from Reader 11.
    For example, the PDF will have an intricate purple graphic with matching purple text blocks underneath.  Print preview shows correctly, but when printed the graphic prints brown instead of purple.  The purple text blocks print correctly.  This seems to happen sporadically, but seems to be with complex graphics.
    Documents from all other apps print OK and if we open this .pdf from Acrobat X Standard and export it to a .png file the colors print correctly. 
    The graphic files come from a myriad of sources and customers and we don't have control over the way the documents are originally saved or what apps are used to create the artwork. 
    Any idea why the graphics colors aren't printing and if there are settings we can adjust in Reader 11 so they will print correctly?
    We've tried:
    - Printing to several printers with different drivers and all yield the same results.  (Toshiba eStudio 3530c with PCL6 and PS drivers, Epson Artisan 835, HP OfficeJet 8600, Samsung CLX-6200x)
    - Adjusting the Overprint Preview settings under File -> Preferences and setting "Simulate Overprinting" under the Advanced button in the print preview window.
    - Selecting "Print As Image" under the Advanced button in the print preview window.
    - Adjusting the Document Color Options under File -> Preferences -> Accessibility.
    Thanks in advance for any help!

    Fastest thing you can try: use Windows Explorer to navigate to C:\Program Files (x86)\Adobe\Reader 11.0\Reader, then double-click on Eula.exe and accept the license agreement.
    If that doesn't work, you can try using this tool to first remove all traces of Reader from your computer:
    http://labs.adobe.com/downloads/acrobatcleaner.html
    Then, you can download the full offline Reader installer from
    http://get.adobe.com/reader/enterprise/
    After downloading, restart your computer and run the installer before doing anything else.

  • Need help with buying graphics card and ram for MSI 865PE NEO 2-V

    Hi,
    I want to buy 1GB of ram for motherboard MSI 865PE NEO 2-V I need help with finding correct parts.
    I also want to buy 512Mb or 1GB graphics card.
    as i said before i need help with finding correct ones so they match motherboard, I would appreciate if any one would post link to cheap and fitting parts.
    I found graphics card allready, i just need to know if it will fit.
    the card is
    NVIDIA GeForce 7600 GS (512 MB) AGP Graphics Card
    Thanks for help.

    here you can see test reports for your mobo:
    http://www.msi.com/product/mb/865PE-Neo2-V.html#?div=TestReport

  • Help with new Storm 2 can't send email

    Can someone advise, I can type an email but whenI try to send I click on the gray area (send) but it does not send.  I can reply to an email, but not create a new email  Any suggestions.

    On your BlackBerry device, go to:
    1. Options > Advanced > Host Routing Table > Menu > Register.
    2. Resend your service books from your carrier BIS site:
    From your handheld device:   http://www.blackberry.com/btsc/KB15402
    Go to the Personal Email Set Up icon and log in. Then under Help!, select Service Books, then select Send service Books.
    From your desktop PC:  http://www.blackberry.com/btsc/KB02830
    North American Carriers - scroll down to select your carrier
    WorldWide Carriers - Find your carrier on the list
    3. With the BlackBerry device powered ON, remove the battery a few seconds and then reinsert the battery to reboot. This reboot, even if you have already done this, is often needed to install the service books.
    Finally, after all that, go to Options > Advanced > Default Services, and set your default email service.
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • I need help with Sunbird Calendar, how can I transfer it from one computer to the other and to my iphone?

    I installed Sunbird in one computer and my calendar has all my infos, events, and task that i would like to see on another computer that i just downloaded Sunbird into. Also, is it possible I can access Sunbird on my iphone?
    Thank you in advance,

    Try the forum here - http://forums.mozillazine.org/viewforum.php?f=46 - for help with Sunbird, this forum is for Firefox support.

  • Need help with my graphic calculator!!!

    Hello everybody!! I need help with my little program I made.... The problem is that I am unable to use to calculate but it is possible to compile the code!! What should I do?? Thanks in advance.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Aritmetik extends JFrame implements ActionListener{
         private JLabel l1 = new JLabel("Tal1: ", JLabel.LEFT);
         private JLabel l2 = new JLabel("Tal2: ", JLabel.LEFT);
         private JLabel l3 = new JLabel("Resultat",JLabel.LEFT);
         private JLabel l4 = new JLabel(" ", JLabel.RIGHT);
         private JTextField t1 = new JTextField(" ",10);
         private JTextField t2 = new JTextField(" ",10);
         private JButton b1 = new JButton("+");
         private JButton b2 = new JButton("-");
         private JButton b3 = new JButton("*");
         private JButton b4 = new JButton("/");
         public Aritmetik(){
              Container v = getContentPane();
              v.setLayout(new GridLayout(5,2));
              v.add(l1);
              v.add(t1);
              v.add(l2);
              v.add(t2);
              v.add(b1);
              v.add(b2);
              v.add(b3);
              v.add(b4);
              v.add(l3);
              v.add(l4);
              b1.addActionListener(this);
              b2.addActionListener(this);
              b3.addActionListener(this);
              b4.addActionListener(this);
              pack();
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent e){
              int tal1 = Integer.parseInt(t1.getText());
              int tal2 = Integer.parseInt(t2.getText());
                   if(e.getSource() == b1){
              if(t1.getText().equals("") || t2.getText().equals(""))
                                       JOptionPane.showMessageDialog(null, "Mata in tal!");
                   else{
                        l3.setText("Resultat ");
                   l4.setText(" " + (tal1+tal2));
                   else if(e.getSource() == b2){
                        int sub = tal1-tal2;
                        l4.setText(" " + (sub));
                   else if(e.getSource() == b3){
                        int multi = tal1*tal2;
                        l4.setText(" " + (multi));
                   else if(e.getSource() == b4){
                        int div = tal1/tal2;
                        l4.setText(" " + (div));
                   public static void main(String[] arg){
                   Aritmetik A =new Aritmetik();

    Here is your problem:
    public void actionPerformed(ActionEvent e){
      int tal1 = Integer.parseInt(t1.getText().trim());  // add the trim()
      int tal2 = Integer.parseInt(t2.getText().trim());  // add the trim()
      if(e.getSource() == b1){
        if(t1.getText().equals("") || t2.getText().equals(""))
          JOptionPane.showMessageDialog(null, "Mata in tal!");
        else{
          l3.setText("Resultat ");
          l4.setText(" " + (tal1+tal2));
      }... Better ...
    public void actionPerformed(ActionEvent e)  throws NumberFormatException {
      String tala = t1.getText().trim();
      String talb = t2.getText().trim();
      if ( tala == null  ||  "".equals(tala)  ||  talb == null  ||  "".equals(talb) ) {
        JOptionPane.showMessageDialog(null, "Mata in tal!");
        return();
      int tal1 = Integer.parseInt(tala);
      int tal2 = Integer.parseInt(talb);
      if(e.getSource() == b1){
        l3.setText("Resultat ");
        l4.setText(" " + (tal1+tal2));
      else if(e.getSource() == b2){
        int sub = tal1-tal2;
        l4.setText(" " + (sub));
      else if(e.getSource() == b3){
        int multi = tal1*tal2;
        l4.setText(" " + (multi));
      else if(e.getSource() == b4){
        int div = tal1/tal2;
        l4.setText(" " + (div));
    }Message was edited by:
    abillconsl

  • How to just send I data (No Q) using ni2920 USRP? (ASK modulation)

    Hi.  
     I am trying to send three level sequences as amplitude shift keying (ASK) modulation. my sequence has three state of (-1, 0 , 1). I am using ni2920 usrp to send carrier with amplitudes of -5v, zero, and +5v for each of the mentioned levels respectively (ASK) (Sample rate=25 or 50MS/s). to do that,  I saved a .txt file with voltages amplitudes in the PC and I am reading this .txt file and send them with USRP (I expect USRP to multiply these values with cos(carrier freq) and send it to its RF out port. However there some problems:
    1. I am not sure about the order of data USRP expects to have when reading .txt file in terms of "I" and "Q".  Assume I am sending  0,0,-1,1,1,-1,0,... I have a txt file with 0,0,-5,5,5,-5,0 saved .. BUT every time my code reads this txt file , it assign a vector of <"I","Q"> pair at output of LAN cable instead of considering all numbers as "I" data. my problem is: How can I force USRP to just send I data (no "Q") ? (This is required since I am using ASK modulation)
    2. when I read zero from txt file and send it, I expect to see zero level RF spectrum at output BUT according to my observation there is spectrum content of output RF when sending all zero sequences. How can I force USRP to send nothing (zero) when the bit=0? 
    Any help is appreciated. Thanks.

    1) You can send data to the device as complex double-precision data or binary I16 data.  If using the complex double type, just make the imaginary component of each complex sample 0 (Q is the imaginary componnent).  If using the binary I16 data, the samples are interleaved I, Q, I, Q, ... so just make every other sample 0.
    2) Even when sending 0s for I and Q, if the device is tuned to a frequency and the output path is enabled, you may see some power at the carrier frequency that is basically leakage from the local oscillator.

  • How can I send post data through nsurlrequest?

    Hi.
    I'm working on an application which needs to make requests to a php gateway. I tried many examples I found on google, but none of them worked for me.
    First I was working with GET, and it worked just fine, but now, as I need to send more complex data, GET isn't a solution anymore. I have three params to send: module which is a string containing a php class name, method: the function in the class, and params for the function which is usually an indexed array.
    The following method makes the request to the server, but for some reason, doesn't send the POST data. If I var_dump($_REQUEST) or var_dump($_POST), it turns out, the array is empty. Can somebody tell me, what am I doing wrong? Is there some kind of a sandbox, which prevents data from being sent to the? I also tried to send some random strings, which aren't json encoded, no luck. The sdk version is 5.1, and I'm using the iPhone simulator from xcode.
    If it is possible I would like to solve this problem without any additional libraries (like asihttp).
    And here is the code:
    +(NSObject *)createRequest:(NSString *)module: (NSString *)method: (NSArray *)params
        NSString *url       = @"http://url/gateway.php";
        NSData *requestData = nil;
        NSDictionary *data  = [NSDictionary dictionaryWithObjectsAndKeys:
                module, @"module",
                method, @"method",
                params, @"params",
                nil];
        NSString *jsonMessage = [data JSONRepresentation];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
        NSString *msgLength = [NSString stringWithFormat:@"%d", [jsonMessage length]];
        [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody: [jsonMessage dataUsingEncoding:NSUTF8StringEncoding]];
        requestData     = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *get   = [[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding];
        NSLog(@">>>>>>%@<<<<<<",get);
    Thank you.

    raczzoli wrote:
    I'm working on an application which needs to make requests to a php gateway. I tried many examples I found on google, but none of them worked for me.
    Why not?
    Unfortunately, you are dealing with a number of different technologies that have been cobbled together over the years. You could write a PHP server that would respond correctly to this request, but not using basic methods like the $_POST variable. PHP was designed for HTML and true forms. What you are trying to do is make it work as a general purpose web service over the HTTP protocol. You can do that, but not with the form-centric convenience variables.
    The following is a basic program that will populate the $_POST variable.
    #import <Foundation/Foundation.h>
    int main(int argc, const char * argv[])
      @autoreleasepool
        // insert code here...
        NSLog(@"Hello, World!");
        NSString  * module = @"coolmodule";
        NSString * method = @"slickmethod";
        //NSArray * params = @[@"The", @"Quick", @"Brown", @"Fox"];
        NSString * params = @"TheQuickBrownFox";
        NSString * url = @"http://localhost/~jdaniel/test.php";
        NSDictionary * data  =
          [NSDictionary
            dictionaryWithObjectsAndKeys:
              module, @"module",
              method, @"method",
              params, @"params",
              nil];
        //NSString *jsonMessage = [data JSONRepresentation];
        //NSData * jsonMessage =
        //  [NSJSONSerialization
        //    dataWithJSONObject: data options: 0 error: nil];
        NSMutableArray * content = [NSMutableArray array];
        for(NSString * key in data)
          [content
            addObject: [NSString stringWithFormat: @"%@=%@", key, data[key]]];
        NSString * body = [content componentsJoinedByString: @"&"];
        NSData * bodyData = [body dataUsingEncoding: NSUTF8StringEncoding];
        NSMutableURLRequest * request =
          [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:url]];
        //NSString * msgLength =
        //  [NSString stringWithFormat: @"%ld", [jsonMessage length]];
        NSString * msgLength =
          [NSString stringWithFormat: @"%ld", [bodyData length]];
        [request
          addValue: @"application/x-www-form-urlencoded; charset=utf-8"
          forHTTPHeaderField: @"Content-Type"];
        [request addValue: msgLength forHTTPHeaderField: @"Content-Length"];
        [request setHTTPMethod: @"POST"];
        //[request setHTTPBody: jsonMessage];
        [request setHTTPBody: bodyData];
        NSData * requestData =
          [NSURLConnection
            sendSynchronousRequest: request returningResponse: nil error: nil];
        NSString * get =
          [[NSString alloc]
            initWithData: requestData encoding: NSUTF8StringEncoding];
        NSLog(@">%@<",get);
      return 0;
    I have written this type of low-level server in PHP using the Zend framework. I don't know how to do it in basic PHP and wouldn't bother to learn.
    Also, you should review how you are sending data. I changed your example to send the appropriate data and content-type for the $_POST variable. If you had a server that could support something else, you could use either JSON or XML, but your data and content-type would have to match.

Maybe you are looking for