Jump to content

Archived

This topic is now archived and is closed to further replies.

pentan

How do you make javascript POST

Recommended Posts

I've got a textarea in the middle of a form.  I want javascript to POST the contents that someone types in to another PHP program when they click a button.  I can get the info _to_ the other window, but that's just javascript to javascript.  I need to have PHP do some stuff to the data before it displays it though.  Is there some simple command I'm missing or do I have to use AJAX to do this?

Thanks!
Michael

Share this post


Link to post
Share on other sites
Yea you need Ajax to do this. I will give you a couple examples.

First you will need to set a request object. You can accomplish this several different ways. This is the best that I have found. Thanks to [url=http://www.phpfreaks.com/forums/index.php?action=profile;u=12972]ober[/url]

[code=php:0]
function createRequestObject()
{
    if (window.XMLHttpRequest) { // Mozilla, Safari, Opera...
        var xmlhttp = new XMLHttpRequest();
        if (xmlhttp.overrideMimeType)
xmlhttp.overrideMimeType('text/xml');
    }
else if (window.ActiveXObject)
{ // IE
        try {
            var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!xmlhttp) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
return xmlhttp;
}

// now we delcare a couple variables

var http = createRequestObject();

//now we send the information to the php file

function sendRequest() {
    var field = document.getElementById('yourfield').value
    if (field == '') {
        alert('The field was empty');
    }
    //now this will open the php file for posting
    http.open('POST', 'yourfile.php');
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //now we send the results to the php file
    http.send('field=' + field);
    http.onreadystatechange = handleRequest;
}

//now we handle any thing that might come back from the php file

function handleRequest() {
    if (http.readyState == 4) {
        var response = http.responseText;
        //now we can do something with the results
        //say you return the word ok we will redirect to another page
        //other wise we will alert the error
        if (response == 'ok') {
            window.location = 'someotherpage.php';
        } else {
            alert(response);
        }
    }
}
[/code]

Hope that helps,
Tom

Share this post


Link to post
Share on other sites
Yeah... that was what I was thinking.  Thanks for confirming it.  One would have thought that javascript would have a simple command but no worries.  Thanks!

Share this post


Link to post
Share on other sites
Can I just confirm that if i have a form as such:
[code]<form action="javascript:GetPage()">[/code]
where GetPage is a javascript function I am using for AJAX, I will need the code as shown before to actually submit the variables to the new page?

Is there an easier way with the get method?

Basically I have a main div, which holds all my content. I want to delete an entry in a db, so i am trying to post the id to the delete function page (which is loaded into the main div to show to error/confirm message).


Thanks,
Alex

Share this post


Link to post
Share on other sites
I always do something like this..

[code]<form action ="" onSubmit="return blockSubmit();">[/code]

Now in the block submit function do this..

[code=php:0]
function blockSubmit() {
     getPage();
     return false;
}
[/code]

And as far as the get method goes. It is a little more simple but you will still have to create a request object. Here is a simplefied version for the get method..

[code=php:0]
//I am going to assume that your function for createing the request function is called the following:
var http = createRequestObject();

function getPage() {
    http.open('GET', 'yourpage.php?someting=something');
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    http.send(null);
    http.onreadystatechange = somethingelse;
}

function somethingelse() {
   if (http.readyState == 4) {
      var page = http.responseText;
      //now we replace the your main div. I am going to assume that it is called main
      document.getElementById('main').innerHTML = response;
   }
}
[/code]

Now the reason that I like to use the blockSubmit function is that if the user hits enter you would see the results in your browser. So say you are submiting a form with a field called text. On your current page you would see something like this in the address bar. yourpage.html?text=thesubmitted text.

Good Luck,
Tom

Share this post


Link to post
Share on other sites
I tried what was suggested, but it didnt seem to work. I made an error in my first bit of code, it is actually a GetPage('action') function, where it loads page.php?act=action. I cant see why this would create an error though.

The new page loads fine when I use the code, but none of the $_POST variables are available. I tried changing the form to method="get" and using $_GET, but still no luck.

If you know where I may have gone wrong, please let me know.

On a side note, I have changed the following function:
[code]
function somethingelse() {
  if (http.readyState == 4) {
      var page = http.responseText;
      //now we replace the your main div. I am going to assume that it is called main
      document.getElementById('main').innerHTML = response;
  }
}
[/code]
so that it works (the example has var page, then sets the div to response), so that isnt the problem.


Thanks again,
Alex

Share this post


Link to post
Share on other sites
Yea that is the source of part of your problem. Change

[code=php:0]
document.getElementById('main').innerHTML = response;
[/code]

To

[code=php:0]
document.getElementById('main').innerHTML = page;
[/code]

Also which browser are you testing this in? Some people say that Opera is the best but I think that FireFox is. IE is the worst browser for debugging javascript.

Another thing.. Try placing a alert throughout the script to find when it stops.. Like this.

[code=php:0]
function somethingelse() {
  if (http.readyState == 4) {
      alert('The readyState is 4');
      var page = http.responseText;
      //now we replace the your main div. I am going to assume that it is called main
      document.getElementById('main').innerHTML = page;
  }
}[/code]

If that works then move it down to the next line. Continue this until the alert stops poping up. You will then find where the error starts.

Also,

[code=php:0]
var page = http.responseText;
[/code]

Means that you have placed the response from your script to the variable called page. Then the
document.getElementById('main').innerHTML means that you are going to write the  result from your script to the div with the id of main.

Hope that helps,
Tom

Share this post


Link to post
Share on other sites
I ma using IE (the majority of the people using the system will use IE, so It has to work).

I had fixed the page/response error, and everything goes well with the debugging. It will load the new page fine, just not pass through the variable.

For example, I want to load page.pg?act=delete_message with the id of the message as post.

It loads the page, and shows it (says "entry deleted"), but when i try to echo $_POST['id']; I get nothing. It seems like nothing wrong with the js as far as loading the page, just the passing of the variables.

Alex

Share this post


Link to post
Share on other sites
Ok let me see if I am understanding you correctly.

Well first.. I didn't mean that you should write the script for FF but rather that you should down load FF and use it to debug your javascript. Almost everything that works in FF will work perfectly in IE but not the other way around. Also, FF's javascript console is very descriptive as far as errors go. But do what you want..


Now back to your question.. Are you saying that you want to pass something like this to this script.. youpage.html?something=something. If so, this is not impossible but I have not tried this yet. I have seen it done somewhere but I have yet to find a need to do it yet.

I will figure it out and post a solution. This is what you meant.. Correct?

Tom

Share this post


Link to post
Share on other sites
That is pretty much correct.

I want to pass ACTION to the script (ie. GetPage('ACTION')) and then have it go to page.php?act=ACTION . That bit is fine, works perfectly. The problem is that page.php looks similar to below.

[code]
switch($_GET['act'])
{
case 'ACTION':
    mysql query to complete action (in this case delete message $_POST['id'])
    tell the user that action is complete
break;
}
[/code]

I get "tell user action is complete", but it doesnt delete the message. $_POST['id'] is NULL. and I am sure that "id" is the correct name etc because it worked before I started using AJAX to make it quicker.

Thanks for the help, I look forward to seeing a solution, its doing my head in...

Cheers,
Alex

Share this post


Link to post
Share on other sites
ah ok... I see what you mean now.. That is a php question and here is a nice little function that I like to use for that...

[code]
<?php
session_start();//just incase you want to do something with sessions
include("db.php");//your database connect file
//now this is something that I like to through in there for added security.
$valid_actions = array('deleteMessage', 'something', 'somethingelse');

//now we declare the action
$action = strip_tags($_GET['action']);

//now we check to make sure that the action is in or valid actions array

if (!in_array($action, $valid_actions)) {
    //if it is not then we die with the message invalid action
    die("invalid action");
}

//now we create a function to hold the actions

function getaction($action) {
    switch($action) {
        //now each case will be a different action
        case "deleteMessage":
            //place you php for the action here
        break;
        case "something":
              //dido
        break;
        case "something else":
              //dido 2
        break;
    }
}

//you need the line below for the script to function

getaction($action);
?>[/code]

hope that helps,
Tom

Share this post


Link to post
Share on other sites
Thats basically what I have... but when that page loads, there is no $_POST['id']; The form is as such
[code]
For each entry in db:
<form action="" onsubmit="blockSubmit()">
<input type="hidden" id="id" name="hidden" value="<?php echo $id; ?>">
<input type="submit" ...>
</form>
[/code]

I know my PHP code works fine (pretty much exactly as you said in the previous post) because when I loaded to page through <form action="page.php?action=delete_message"> it worked fine. Thats why I have posted here, because it is something to do with the AJAX that it doesnt work...

Thanks again for the help Tom.

Share this post


Link to post
Share on other sites
I've been keenly followingg this discussion and I've been practising the steps but it didn't work for me. I'm a newbie at this. What I wish to do is simply to display an "echo" command from a php file into a div in my main html page. If I can get this to work, I will be very happy and will be able to progress to database issues. My goal is to design a web-based database application using mySQL, PHO and AJAX/javascript.

Please, I really need help and any useful tutorials I can get.

Share this post


Link to post
Share on other sites
Like ober told me when i first started with Ajax well really javascript in general. You have to be absolutely precise. Did you try putting alerts at different points in the javascript? As I said if you use ether FireFox for Opera it would make your life alot easier. First make sure that you have no errors in your php script. Then start debuging your javascript with the alerts like I said.

Good Luck,
Tom

Share this post


Link to post
Share on other sites
Thanks, I'm making progress now. Will keep u updated with progress and questions.  :)

Share this post


Link to post
Share on other sites
[quote]Thats basically what I have... but when that page loads, there is no $_POST['id']; The form is as such
Code:

For each entry in db:
<form action="" onsubmit="blockSubmit()">
<input type="hidden" id="id" name="hidden" value="<?php echo $id; ?>">
<input type="submit" ...>
</form>


I know my PHP code works fine (pretty much exactly as you said in the previous post) because when I loaded to page through <form action="page.php?action=delete_message"> it worked fine. Thats why I have posted here, because it is something to do with the AJAX that it doesnt work...

Thanks again for the help Tom[/quote]

[b]I got it to work! [/b] The problem is not with the form. I changed getPage() as follows:

[code]
function getPage() {
var d1 = document.datain.txt_name.value;
var d2 = document.datain.txt_phone.value;
var d3 = document.datain.txt_email.value;
var para = "f_name="+d1+"&f_phone="+d2+"&f_email="+d3;

    http.open('POST', 'post_data.php');
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    http.send(para);
    http.onreadystatechange = somethingelse;
}
[/code]

The data was successfully transfered to my PHP file which properly executed and the result as display.
What I'm trying now is how to use two request objects and get them to work one after the other. For example, once data has been successfully posted, to select all data in the database table and display as an HTML table

Share this post


Link to post
Share on other sites
ok I think that I am understanding you correctly. You are wanting to use another function after returning the results from your first request... If so you can do something like this..

[code=php:0]
//I am assuming that the Request object function is called createRequestObject()
var first = createRequestObject();
var second = createRequestObject();

function something() {
    var somefield = document.getElementById('fieldName').value;
    first.open('POST', 'youscript.php');
    first.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    first.send('somefield=' + somefield);
    first.onreadystatechange = somethingElse;
}

//now we can do something with the response. I am going to assume that you are updating
//something in the db and will be returning ether the word updated or a error string

function somethingElse() {
    if (first.readyState = 4) {
        var response = http.responseText;
        if (response == 'update') {
            doSomethingElse();
        } else {
            alert(response);
        }
    }
}

//now in the do someting else function you could display something or what ever.

function doSomethingElse() {
    second.open('GET', 'somescript.php?page=somepage');
    second.send(null);
    second.onreadystatechange = handleSomething;
}

function handleSomething() {
   if (second.readyState = 4) {
       var page = second.resonseText;
       if (page == 'error') {
          alert('there was an error');
       } else {
          document.getElementById('yourContentDiv').innerHTML = page;
       }
   }
}[/code]

Does that answer you question?

Tom

Share this post


Link to post
Share on other sites
That would be a way to do it. The biggest problem I have is that I am converting an old system, and would prefer not to have to change $_POST['var']

Also, I use the same function for many forms, but the javascript would have to be different for each form if I used that method.

Thanks for the help, if you know of a way to do it without having a different function for each form, please let me know.

Thanks,
Alex

Share this post


Link to post
Share on other sites
Your post got me thinking..

I do something like this for the get and post method for my php scripts so I thought why couldn't it be done with javascript..

I have only tested this is IE6 I am not sure about FF or Opera.

[code=php:0]
function something(form) {
    var fld = document.forms[form].elements;
    //this will get the total number of fields in the form
    var fmax = fld.length;
    var vals;
    var error = new Array();
    //now we loop thorough the fields.
    for (var i = 0; i < fmax; i++) {
          //this is going to assume that you have a name for the submit button
         if (fld[i].name !== 'submit') {
             if (fld[i].value == '') {
                  error[] = fld[i].name;
             }
             if (i == 0) {
                 vals += fld[i].name + '=' + fld[i].value;
             } else {
                 vals += '&' + fld[i].name + '=' + fld[i].name;
             }
         }
     }
     if (error.length !== 0) {
         var errors;
         for (var i = 0; i < error.length; i++;) {
                errors += error[i] + ', ';
         }
         var val = errors.split('undefinded');
         alert('You did not enter the following fields ' + val);
     } else {
         var param = vals.split('undefined');
         //now we return the second part of the split
         return param[1];
     }
}               
[/code]

now you can do this in the function that sends the results to the php file.

[code=php:0]
function yourfunction(form) {
    var params = something(form);
    first.open('POST', 'youscript.php');
    first.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    first.send(params);
    first.onreadystatechange = somethingElse;
}
[/code]


now you call this function like this onclick="yourfunction(this.form.name);" You could also add the name of the script that you want to send it to by doing this onclick="yourfunction(this.form.name, script);" and adding that to that to the yourfunction  function like this.

[code=php:0]
function yourfunction(form, script) {
    var params = something(form);
    first.open('POST', script + '.php');
    first.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    first.send(params);
    first.onreadystatechange = somethingElse;
}
[/code]


You will also have to have a name for the form and a name for the fields.

hope that helps,
Tom

Share this post


Link to post
Share on other sites
Tom, your a legend...

I havent tested it yet, but it looks like that will do exactly what I'm looking for.

Thanks for all your help, and be assure, if it doeant work, I will be back :)

Alex

Share this post


Link to post
Share on other sites
I had a couple of problems with the error reporting, especially the error[] = ... line.

After omitting this it worked, with the exception of the use of document.forms[form].

The forms.[form] expects an integer, but seeing as my page has theoretically infinate forms, with a loop to create them, i simply added another argument for the form number, which is the same as the loop variable in my PHP script.

Alex

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.