I've searched everywhere but can't find an answer to this problem.
I'm writing a little ajax script but can't get the correct value of the POST request.
This is the code so far:
<textarea id="message" name="message" style="width:100%;"></textarea>
<input value="SEND" style="border-radius: 5px 5px 5px 5px;" type = 'button' onclick = 'ajaxFunction()'/>
<script type="text/javascript"> <!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('chbox');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var message = document.getElementById('message').value;
var queryString = message ;
ajaxRequest.open("POST", 'chatdata.php', true);
//ajaxRequest.send(null);
ajaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajaxRequest.send('queryString');
}
</script>
<?php
$message1 = $_REQUEST['message'];
echo $message;
?>
when i use print_r($message); to see the content of the POST value
this is what i get Array ( [queryString] => ). It has no values.
What could be wrong with my code?
(I would have used jQuery but i'm not well grounded in it yet.)
I fixed some bugs and code start works:
1.
<p id="chbox"></p> <!-- ajaxDisplay need this -->
2.
ajaxRequest.send("message="+queryString); //queryString is variable so without quotes
3.
var_dump($message1); //there was message without 1
Here's how you would do it in jQuery - much simpler:
$('#mybutt').click(function(){
var txt = $('#message').val();
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: 'ta=' + txt,
success: function(d){
if (d.length) alert(d);
}
});
}); //END mybutt.click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="message" name="message" style="width:100%;"></textarea>
<input id="mybutt" value="SEND" style="border-radius: 5px 5px 5px 5px;" type='button' />
my_ajax_processor_file.php
<?php
$txt = $_POST['ta'];
$out = 'You sent: ' .$txt;
echo $out;
Here are a bunch of free 5-min video tuts for jQuery
The trouble is with query string. You should put ajaxRequest.send(queryString) instead of ajaxRequest.send('queryString');. Don't use query string just use the name of the variable. It should work!
Related
The ajax jquery I am using in my form takes almost 4 seconds to complete and create the fields I want in my form. Because of that, some users submit the form before those fields are created. I want the form not submitted until those fields are created.
Here is my code.
echo"<form action='http://teachers.teicm.gr/dvarsam/index.php/exelixi_aitisis/' method='post' onsubmit='return recaptcha();'>
<label class='formLabel'>Όνομα*</label><br />
<input name='FirstName' required='' type='text'/><br />
...
...
echo"<select name='ThesisID' id='link_block' onchange='showCourses(this.value)'>
<option disabled='disabled' selected='selected' value=''></option>";
while ($row = mysqli_fetch_array($result))
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";
//displays the courses when thesis is selected
echo"<p id='courses'></p> ";
//placeholder which you’ll need to add to your form markup wherever you want the reCAPTCHA to appear
echo"<div class='g-recaptcha' data-sitekey='6LcIzA4TAAAAABo7Ean4z9EbNJddkkh04x9v6pLs'></div>
<input type='submit' name='action' value='Αποστολή' />
</form>";
On submit function. It checks if receptcha "I am not a robot" is clicked
function recaptcha ()
{
if(grecaptcha.getResponse() == ""){
alert('Παρακαλώ επιβεβαιώστε ότι δεν είστε ρομπότ κάνοντας κλικ στο κουτάκι.');
return false;
}
else
{
return true;
}
}
OnChange javascript. It shows textboxes on < p id='courses'>
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and will update div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // the div section where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://teachers.teicm.gr/dvarsam/index.php/get_courses" + queryString, true);
ajaxRequest.send(null);
}
I think that I need to add something in my on submit function that will return true only when the ajax jquery is completed. Am I thinking correctly? Can someone help me with that?
First, give an ID to your submit button and disable it by default:
<input type='submit' ID="SUBMITBUTTON" name='action' value='Αποστολή' disabled />
Then you can do something like this in your On Success return from Ajax to enable the submit button:
$('#SUBMITBUTTON').removeAttr('disabled');
OR
$('#SUBMITBUTTON').prop('disabled', false);
I have problem with the code further down.
In html file:
<form id='changeAccountForm' action='usermenu.php' method='post'>
Name:<input type="text" name="name"/>
Surname:<input type="text" name="surname"/>
Password:<input type="password" name="password"/>
Phone:<input type="text" name="phone"/>
Paid mail:<input type="text" name="paidMail"/>
Payment method:<input type="radio" name="paymentMethod" value="0"/>paypal
<input type="radio" name="paymentMethod" value="1"/>payza
<div id="changeAccountInformation" >change</div>
</form>
In Javascript file I use Javascript and jQuery. I use javascript with ajax and the function called:
function ajaxInit(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}//end function ajaxInit
function updateUserDataWithAjax(){
var ajaxRequest = ajaxInit();
// Create a function that will receive data
// sent from the server and will update
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
// find all form elements and add the responseText to placeholder attribute
var childNodes = $("#changeAccountForm").children(),i,j=0;
var inputAjaxRequest = ajaxRequest.responseText;
//inputAjaxRequest = inputAjaxRequest.plit(",");//ERROR:
for(i=0; i<childNodes.length; i++)
if(childNodes[i]!= "input"){
childNodes[i].setAttribute("placeholder",inputAjaxRequest[j++]);
}
}
}
var namesArray = "userId,password,name,phone,";
namesArray+= "surname,paidMail,payMethod,";
namesArray+= "score";
namesArray = namesArray.split(',');
//gets all the childnodes and find these with attribute
var childNodes = $("#changeAccountForm").children(),values,names,i;
var queryString = '';
var first = true;
for(i=0; i<childNodes.length; i++)
for(j=0;j<namesArray.length;j++)
if(childNodes[i].getAttribute("name")==namesArray[j]){
values = childNodes[i].value;
names = childNodes[i].getAttribute("name");
if (first){
queryString += names+"="+values;
first = false;
}else
queryString += "&"+names+"="+values;
}
ajaxRequest.open("POST", "usermenu.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString .length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(queryString);
}
//and i call this function
$(document).ready( function(){
$("#changeAccountInformation").click(function(){
var user = updateUserDataWithAjax();
});
});
In php file:
when i use the method post something going wrong and prints Undefined index: [key value name] in. The response text from ajax is an array with the name of html file.
include "userMenu.html";
isset($_POST['name']);
echo $_POST['name'];
Any information will be appreciated, thank you.
I have a form that executes an AJAX function to submit form values to a PHP page. The PHP page just responds by echoing out the variables in a DIV.
It works with GET method, but I can't get it working with POST.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Browser Not Supported");
return false;
}
}
}
// Get Response
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("response").innerHTML = ajaxRequest.responseText;
}
}
var name=document.getElementById("name").value
var email=document.getElementById("email").value
ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='Form1'>
Name: <input type='text' name='name' id="name"/> <br />
Email: <input type='text' name='email' id="email"/> <br />
<input type="button" value="Submit" onClick="ajaxFunction();">
</form>
<div id="response">
</div>
</body>
</html>
And the php page, process.php
<?php
echo date("H:i:s");
echo "<br/>";
// echo "Post Variables: ".$_POST['name']." ".$POST['email']; old code
echo "Post Variables: ".$_POST['name']." ".$_POST['email'];
echo "<br/>";
echo "Get Variables: ".$_GET['name']." ".$_GET['email'];
?>
The response I get is:
11:32:05
Post Variables:
Get Variables: name entered email entered
So i'm pretty sure it's to do with the variable being passed from PHP to Javascript.
Many thanks.
ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
ajaxRequest.send(null);
That's not posting the variables. Here you're sending them as GET parameters, with an empty body for your POST request. Instead, use
ajaxRequest.open("POST", "process.php", true);
ajaxRequest.send("name="+name+"&email="+email);
or even better
ajaxRequest.open("POST", "process.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email));
On my register page, I am trying to set it up so that when somebody enters a username into the username box, it will either show a green check mark if the username doesn't exist, or a red 'X' if the username already exists. When the page loads though (the body tag is <body on_load="process();">), it doesn't come up with a picture, it comes up with the word "undefined".
JavaScript code:
var xmlHttp = createXmlHttpRequestObject();
//Create object for function
function createXmlHttpRequestObject(){
var xmlHttp;
//Check if IE
if(window.ActiveXObject){
try{
//Setting variable equal to object for IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}else{
//Anything not IE
try{
//Want to use this object if not IE
xmlHttp = new XMLHttpRequest;
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}
//If couldn't set object
if(!xmlHttp){
//Tell people that JS couldn't create the object (new XMLHttpRequest or ActiveXObject)
alert("Couldn't create an object with JavaScript!");
}else{
//Return object
return xmlHttp;
}
}
//Use this attribute for body tag: <body onload="process()">
function process(){
/*readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
*/
try{
//Check if ready to communicate
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//<input type="text" id="userInput" /> relates to this
//Set variable to value they typed in
username = encodeURIComponent(document.getElementById("register_name").value);
//Creates request to send to server
//Need PHP file, GET would be in PHP file, also can be POST, etc.
xmlHttp.open("POST","functions/check_used.php",true);
//Doing something to make it pretend like it's a form, for POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Handle server response when server responds to the request
xmlHttp.onreadystatechange = handleServerResponse;
//Send request (this is used for POST, use null when using GET)
xmlHttp.send("username="+username);
}else{
//Not ready to communicate, wait for 1 second and try again
setTimeout('process()',1000);
}
}catch(e){
//Something doesn't work, tell them what happened
alert(e.toString());
}
}
//When response received, tells what to do with it
function handleServerResponse(){
//Response done communicating
if(xmlHttp.readyState==4){
//Communication went OK
if(xmlHttp.status==200){
//Put response into variable
xmlResponse = xmlHttp.responseXML;
//Get document element
xmlDocumentElement = xmlResponse.documentElement;
//Get data from XML file
message = xmlDocumentElement.firstChild.data;
//Access document, put it in element on page, innerHTML is stuff shown on webpage
document.getElementById("checkedUser").innerHTML = message;
//Pause 1 second before communicating with server again
setTimeout('process()',1000);
}else{
//There was an error with data
alert('Something went wrong!');
}
}
}
On the register page, I have an input box with the div next to it:
<input type="text" id="register_name" name="username" /><div id="checkedUser"></div>
Finally, I have the PHP file that it is posting to:
<?php
require_once('../includes/db.php');
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<username>';
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
echo '</username>';
?>
I have tried troubleshooting it, but I couldn't figure out what was wrong.
Listen for keystrokes in input, and check username when the input changes :
$(function() {
$('#register_name').keyup(function() {
$.ajax({
type: 'POST',
url : 'functions/check_used.php',
data: {username : this.value},
success: function(result) {
$('#checkedUser').html(result);
}
});
});
});
And there's no need to return XML:
<?php
require_once('../includes/db.php');
header('Content-Type: text/html');
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
?>
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
should be
if(xmlHttp.readyState== 4 && xmlHttp.status == 200){
I am try to have a forum submits more then once when a user clicks the submit button. Why? I am try to add more then one idem to a shopping cart, The shopping cart software I am using doesn't support adding more then one product at a time and I don't want to edit there core code. The hidden forum would have the product ids like '1,2,3' I'd then need the JavaScript to separate the values and post each one using AJAX to the cart. I am not great a JavaScript but I coded what I think should work but its just giving me a alert: 'There was a problem with the request.' twice. I can't see whats wrong with it, any and all help and suggestions are welcomed! Here the code:
JS
<script type="text/javascript">
function testResults (form) {
var product_id = form.product_id.value;
var quantity = form.quantity.value;
var brokenstring=product_id.split(",");
for ( var i in brokenstring )
{
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
var poststr = "product_id=" + encodeURI( brokenstring[i] ) +
"&quantity=" + encodeURI( quantity );
makePOSTRequest('post.php', poststr);
}
}
</script>
HTML
<form action="javascript:testResults(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="product_id" id="product_id" />
<input type="hidden" name="quantity" id="quantity" value="1" />
<br />
<input type="submit" name="button" value="Submit" />
</form>
<span name="myspan" id="myspan"></span>
post.php
<?php
print_r($_POST);
?>
If you want to add two items to the cart shouldnt you be doing two posts with the same item? I can just see one post per item there. You are not taking the quantity into account. But this is not the problem. In this case this is only a logic error.
For the javascript side I would recommend you to use jQuery to treat the ajax stuff because it will make your life WAY easier than regular javascript that might event not work with all browsers.
This is the link related to the POST method of jQuery: http://docs.jquery.com/Post
Hope it helps
It is against all the programming logics to post a form several times instead of having a more complex form. From what I can see or understand from your code you are trying to loop through your splitted (brokenstring) string. Your loop is not constructed where and how it should be. Anyway, if I were you, I would consider migraton to another free cart o the possibility to write one myself. From what I see you will be able to do so with a little bit of help from here.