Jump to content


Photo

How do you make javascript POST


  • Please log in to reply
23 replies to this topic

#1 pentan

pentan
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 07 October 2006 - 04:10 PM

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
Michael Shaffer
www.pelentan.com
"You know you have it, but can you _show_ you have it?"

#2 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 07 October 2006 - 07:31 PM

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 ober

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);
        }
    }
}

Hope that helps,
Tom

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#3 pentan

pentan
  • Members
  • PipPip
  • Member
  • 19 posts

Posted 08 October 2006 - 01:57 PM

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!
Michael Shaffer
www.pelentan.com
"You know you have it, but can you _show_ you have it?"

#4 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 09 October 2006 - 06:25 AM

Can I just confirm that if i have a form as such:
<form action="javascript:GetPage()">
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

#5 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 09 October 2006 - 06:41 AM

I always do something like this..

<form action ="" onSubmit="return blockSubmit();">

Now in the block submit function do this..

function blockSubmit() {
     getPage();
     return false;
}

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..

//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;
   }
}

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

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#6 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 09 October 2006 - 11:04 AM

Thanks for the help. I will test later, and be back if I need any help..

Alex

#7 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 10 October 2006 - 12:30 AM

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:
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;
   }
}
so that it works (the example has var page, then sets the div to response), so that isnt the problem.


Thanks again,
Alex

#8 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 04:30 AM

Yea that is the source of part of your problem. Change

document.getElementById('main').innerHTML = response;

To

document.getElementById('main').innerHTML = page;

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.

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;
   }
}

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,

var page = http.responseText;

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

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#9 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 10 October 2006 - 04:43 AM

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

#10 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 04:51 AM

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

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#11 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 10 October 2006 - 05:50 AM

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.

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;
}

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

#12 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 06:25 AM

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...

<?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);
?>

hope that helps,
Tom

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#13 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 10 October 2006 - 10:58 AM

Thats basically what I have... but when that page loads, there is no $_POST['id']; The form is as such
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.

#14 sholla

sholla
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 13 October 2006 - 05:41 PM

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.

#15 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 13 October 2006 - 10:39 PM

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

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#16 sholla

sholla
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 14 October 2006 - 09:30 AM

Thanks, I'm making progress now. Will keep u updated with progress and questions.  :)

#17 sholla

sholla
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 14 October 2006 - 11:51 AM

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


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

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;
}

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

#18 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 14 October 2006 - 09:28 PM

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..

//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;
       }
   }
}

Does that answer you question?

Tom

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#19 sholla

sholla
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 16 October 2006 - 09:31 AM

Thanks. I'll keep your updated about my progress

#20 aleX_hill

aleX_hill
  • Members
  • PipPipPip
  • Advanced Member
  • 143 posts

Posted 17 October 2006 - 08:04 AM

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users