AJax variable not getting send to php variable - javascript

Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post.
I have managed to create the following which is a form that displays a message on submit. If form was successfully submitted a message is displayed without page refreshing as you can see in image below:
FORM
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
What I want to do
Retrieve the value from text field message and assign it to php variable
My problem
When I try to retrieve the value of message with the following code, nothing happens:
PHP code below form
<?php
if(isset($_POST['contact'])){
$message = $_POST['msg'];
echo $message;
}
?>
Im very new to Ajax so I guess I am doing something wrong here, unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.
Thanks in advance

Hanoncs suggestion will work, but keeping things only browser side (by displaying the message only from form to div), will always give the user the impression that message is send (processed) server-side, while it is not always the case, one would make php return it before displaying it with javascript. So here is another approach I suggest:
First, Make a Separation of concerns: Sending a POST HTTP Request to the same current page contardicts somehow the purpose of AJAX. The HTTP Response will contain all the page ( the HTML rendred by PHP, the embeded HTML used for templating, and maybe the script if it is not joined in a script tag). Instead, I suggest you create a small separate php file that is responsible for rendereing only the needed markup. And so, instead of using $.post(document.location.url.., one would use $.post('pathToSmallPHPFile'..
Second, let jQuery AJAX functions accept callbacks or use promises. I suggest you carefully read the following link.

The issue is that you are using ajax, which does not cause a page refresh, and then trying to echo out the posted variable, since there is no page refresh, php will not process the page again to echo the posted variable.
My solution is to use javascript to display the text entered and then database it using php.
Here is an example,
$(document).ready(function () {
$(".button").click(function () {
$('p').text($('#msg').val());
});
});
http://jsfiddle.net/r4nanmof/ you dont need ajax if all you want to do is display it on the page. If you plan on saving in the database then ajax is required.

Jquery Code for posting the message value to the php file is given below:
$('#contact_btn').click(function(event){
event.preventDefault();
var url = "url/of/the/php/page/where/to/process/data";
var data = $("#msg_box").val();
var wrapper = $('#wrapper');
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
wrapper.html("The reponse from the page is " + response);
},
error: function(xhr,status,msg){
//Handle error here
}
});
});
<code>
<div id="wrapper">
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" id="msg_box" value="" /><br />
<input type="submit" id="contact_btn" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
</div>
</code>
Message
Thank You We will Get Back to you
Ooops....Something Went Wrong

Its not necessary in your case but change method"post"> to method="post">
And change your Form
<form name="message-form" action="" id="contact-form" method="""post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none"> </div>
And use the following jQuery code to post your data
$(function () {
$("#contact-form").submit(function (e) {
e.preventDefault();
$form = $(this);
$.post(
document.location.url,
$(this).serialize(),
function (data) {
$(".form-feedback").html("Your msge " + data + " is recieved and we will get back soon");
$(".form-feedback").show();
})
});
});

Related

Jquery If condition display message based on submission or failure

Im learning Jquery and AJAX on my own through online tutorials and by posting on SO when I gets stuck, so please keep in mind I am a novice should you be so kind to answer my question.
I have a form inside a modalbox. Ajax prevents it from closing/reloading and a message gets displayed after submission as you can see in image below:
My problem
Both the success and failure messages gets displayed. I would like to change this so that 1) Success message gets displayed on successfull submission or 2) failure message gets displayed on failed submission:
My Form
<div id="inline3" style="width:400px;display: none;">
<h3>Contact Us</h3>
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
If anyone can give me a bit of help or advise here it will be greatyly appreciated.
Thanks for reading
First thing I would do is change the backend so that instead of returning html it return json containing only the information you need (like whether the submission was a success or failure and any other messages, etc.).
Then the easiest fix that comes to my mind is to give each of your two feedback message divs unique id's:
<div id="form-feedback-success" class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div id="form-feedback-error" class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
Keep the class names so that you can use css to style the two in a similar manner.
Then in your javascript check for a success or failure flag. Based on the flag display one or the other div based on the id:
$.post(document.location.url, $(this).serialize(), function(data){
if(data.success) {
$('#form-feedback-success').fadeIn(1500);
}
else {
$('#form-feedback-error').fadeIn(1500);
}
});
You may need to make some tweeks(like deserialize the response from json to an object), but that is the gist of it.

How to access form data from javascript

I am a javascript newb so any help on this matter would be appreciated!
I am trying to get the user submitted data back after submission.
I have a javascript function that replaces one form with another. A kind stackoverflow user helped me create this function.
function Vanish(event) {
event.preventDefault();
// Specify the id of the form.
var IDofForm = "quest";
// Specify the id of the div containing the form.
var IDofDivWithForm = "question";
// Specify the id of the div with the content to replace the form with.
var IDforReplacement = "entryform";
if(document.getElementById(IDofDivWithForm).innerHTML = document.getElementById(IDforReplacement).innerHTML){
return true;
}
else{
return false;
}
}
Then I have my forms :
<div id="question">
<form action="" method="POST" name="quest" id="quest" onsubmit="Vanish(event)">
<textarea name="question" class="question-field" placeholder="Ask your question..."></textarea><br><br>
<input type="submit" name="qsubmit" onclick=" Change();">
<!-- Change() only swaps images on the screen-->
</form>
</div>
<!-- Vanishing Form -->
<div id="entryform" style="display:none;">
<form action="" method="POST" id="email">
<input type="text" name="fName" placeholder="First Name" class="forms" value="<?echo $_POST['question'];?>">
</br>
<input type="text" name="sName" placeholder="Second Name" class="forms">
</br>
<input type="text" name="email" placeholder="Email" class="forms">
</br>
<input type="image" src="images/submit.png" name="esubmit" onclick="submitForm()">
</br>
</div>
As you can see from above I have two forms. the entry form replaces the question form after it has been submitted.
My question today is how do I get the entered data?
I prefer php as I understand it more so if there was a php method to this that would be great however all solutions will be helpful!.
For PHP I have tried using the $_REQUEST and $_POST methods to try and get back the data but it does not work.
My forms all submit to the page they are on.
First of all JavaScript is client side programming language so to get data to server you need to make a http/https request to server and send/receive data
Good read What is the difference between client-side and server-side programming?
and to do that you can either use html Form or ajax
Form
In form you simply send data to url in action ( if no url specified it will make request to current page else specified action url)
Ajax
you can send data using ajax for that you just need to make ajax request like below (i highly recommended to use JavaScript ( but if you are good at JavaScript that you can use Jquery framework too )
var yourFormId = document.getElementById("email");
email.onsumbit = function(e){
e.preventDefault();
var formData = new FormData(yourFormId );
var request = new XMLHttpRequest();
request.open("POST", "your-url");
request.send(formData);
}
// here by formData object you can get all data in single code of line
and to do with jquery see this post it has very simple example jQuery Ajax POST example with PHP
Now couple of good Reads
FormData Objects
Ajax : MDN its really good source

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

How to display notification before form submit with jquery?

Is it possible to hold form submission to display notification for a couple of seconds?
Before a page reloads after the callback form is submitted I would like to display something along those lines: "Thank you for your callback request. We will be in touch shortly."
You can use preventDefault() to stop the form from submitting, show the information you want and submit() the form in a setTimout() after the desired delay.
if you're submitting with AJAX there is no need to refresh.
Take this as an example:
<form>
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="email"/>
<input type="text" name="address"/>
<input type="password" name="password"/>
<!--
Here you have two options. Use <a></a> or an input with type="submit"
since you're using AJAX, I reccomend using Submit
-->
Submit
</form>
Thank you for your callback request. We will be in touch shortly.
On javascript then:
<script>
$(document).ready(function(){
$("#submit_form").bind("click",function(){
//do a $.post();
$.post("submit/this.php",something : "content_of_something",
function(response){
if(response==1)//or whatever you want
$('#some_id').fadeIn(function() {
setTimeout(function(){
window.location.reload();
},3000);
});
else
alert("Error ocurred");
}
);
});
});
</script>
On PHP, check if the variable got to the server through $_POST(for debug purpose do var_export($_POST) on the server and on the client put a alert(response) right after function(response)). If everything went how it was supposed, echo 1(so response will match 1== response == 1), else, you can echo something else you want.

Create a Form element using javascript and submit it without redirecting/refreshing

I am using a Form in a LightBox which contains some input element.
<form name="imageUploadForm" action="uploadImage.do" method="post" enctype="multipart/form-data">
<input type="text" id="id" name="id" style="display: none;" value="">
<div id="fileUploaderDiv">
<input type='file' name="file0" id ="file0" />
</div>
<button onclick="javascript:ImageUploader.attachImage();">Upload</button>
</form>
can anybody tell me how to copy this form in new one and submit it without redirecting user or knowing him about form submission using javascript or jquery?
http://api.jquery.com/serialize/
$('#yourbutton_notintheexample_you_provided').click(function(){
var myForm = $('form[name=imageUploadForm]')
var data = myForm.serialize();
$.ajax({
url: myForm.attr('action'),
type: myForm.attr('method'),
data: data,
success: function(){
window.alert("write your form handling code here")
}
});
});
or something along the lines.
In prototype, there was a single convenience method, called Form.request, read about it here.
In order to send data to a server (through submitting a form or otherwise) one can use AJAX. The user does not need to be informed (but I'd recommend letting the user know somehow).
JavaScript tutorial
jQuery docs

Categories

Resources