Reputation: 3864
I have created a messaging system which allows users to send messages to eachother. This works fine but when they reply I dont want them being taken to another page, I want a alert to say "sent" or "not sent". Below is my code which doesnt work.
in php:
echo"<form id=\"form\" name=\"form\" method=\"post\" onsubmit=\"send(reply)\">";
javascript:
function send(reply)
{
var httpRequest;
make_request()
function stateck()
{
if(httpxml.readyState==4)
{
alert (httpxml.responseText);
}
httpxml.onreadystatechange=stateck;
reply_url="compose.php?reply=" + reply.value + "&msgid="<?php echo $msgid; ?> + "&to="<?php echo $to; ?> + "&subject="<?php echo $subject; ?>";
httpxml.open("GET",reply_url,true);
httpxml.send(null);
}
}
I am using php php variables as this data needs to be accessed from the database.
Thanks
Upvotes: 0
Views: 629
Reputation: 3043
I agree with Natrium. A javascript library is the way to go. I prefer prototype/scriptaculous for a quick intro into ajax using prototype refer to the following
http://www.prototypejs.org/learn/introduction-to-ajax
Upvotes: 0
Reputation: 9926
You need to tell the browser that you handled the event yourself by returning false in your on submit handler:
echo"<form id=\"form\" name=\"form\" method=\"post\" onsubmit=\"send(reply); return false;\">";
Also your send function looks like it is going to generate an error, which will cause the browser to submit. You are not assigning to httpxml anywhere. I assume you really want:
function send(reply) {
var httpxml;
httpxml = make_request();
stateck = function () {
if(httpxml.readyState==4){
alert (httpxml.status);// you will want to check the server response code too
alert (httpxml.responseText);
}
};
httpxml.onreadystatechange=stateck;
reply_url="compose.php?reply=" + reply.value + "&msgid="<?php echo $msgid; ?> + "&to="<?php echo $to; ?> + "&subject="<?php echo $subject; ?>";
httpxml.open("GET",reply_url,true);
httpxml.send(null);
}
Upvotes: 2
Reputation: 442
Usually if you want to return something via Ajax you want to avoid a page submission. However, if you want the user to feel like they are submitting a form, place a normal button (i.e. NOT a submit button) on the page that will act as your Ajax submit button. Tie your Ajax update function to the onclick and have the PHP page to which you direct the request to send whatever result you want in the response. Everything else (popping the result text into fields, etc) should just be standard Ajax and JavaScript.
Upvotes: 0
Reputation: 151264
It took you to a different page because the form submit occurred. If you don't want the form submit to take place, use
onsubmit="send(reply); return false;"
By the way, you can use single quote: echo ' ... ' so that you don't need to escape all the double quotes in the string.
Upvotes: 2