Partially working AJAX that writes form input to text file - javascript

This script is supposed to take the users input in an HTML form and use AJAX to write that input to a text file via PHP. When I run this code, however, I get two alerts, first 'error' then 'complete' (form the .fail and .always functions in AJAX) which leads me to believe that the problem is in the information being sent back by PHP.
<?php
$fileHandle = fopen('emailList.txt', 'a') OR die ("Can't open file\n");
$email=$_POST['email'];
var_dump($email);
$result = fwrite ($fileHandle, "$email; \n");
fclose($fileHandle);
echo (!$result)? "error" : $result;
die;
?>
Where 'email' is the name of the text input of the form.
But in case the PHP is correct, I'll put the HTML and javascript here as well:
<form>
<input type="text" name="email" value="" class="emailSubmitSidebar" placeholder=" Your Email">
<input type="submit" value="Add" class="submitButton" id="subscribeButton">
</form>
<script>
$(document).ready(function() {
var input = $('.emailSubmitSidebar').val();
var subscribeButton = $('#subscribeButton');
subscribeButton.click(function() {
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: {email: $("input[name=email]").val()},
})
.done(function(data) {
alert("success!")
})
.fail(function() {
alert("error");
})
.always(function() {
alert("complete");
})
});
});
</script>

Related

Is it possible to store an HTML input class into a PHP variable?

I have an html form and some php and a little bit of javascript. The form has two input tags. Both input tags have class attributes. I would like to 'store' the class value inside a PHP variable so I can echo after clicking submit.
I've tried integrating javascript with the first php variable ($firstclass) and failed to get it working even as an alert(). I really don't want to alert the class value but figured this would help find the solution.
<form action="" method="post">
<input type="text" name="input1" class="hidden_class_1">
<input type="text" name="input2" class="hidden_class_2">
<input type="submit" name="submit">
</form>
<?php
$firstclass = ""; //hidden_class_1
$secondclass = ""; //hidden_class_2
$firstclass = "<script type=\"application/javascript\">alert(('this.className').attr('class'))</script>";
$secondclass = ""; //ideally hidden_class_2
if(isset($_POST['submit'])){
echo "<h2>First Input Class Value: ".$firstclass."</h2>";
echo "<h2>Second Input Class Value: ".$secondclass."</h2>";
}
I expect the output to be as follows;
First Input Class Value: hidden_class_1
Second Input Class Value: hidden_class_2
The "easiest" way would be to use AJAX/XHR and send the classes to the PHP script.
<form id="ajaxform" action="path/to/script.php" method="post">
<input type="text" name="input1" class="hidden_class_1">
<input type="text" name="input2" class="hidden_class_2">
<input type="submit" name="submit">
</form>
For example, using jQuery:
const $form = $('#ajaxform');
function onSuccess (response) {
console.log('Successfully submitted the form');
console.log('Server responded with', response);
}
function onFailure (jqXhr, status) {
console.log('Ooops, something went wrong!');
console.log('Server sent status code', status);
}
$form.on('submit', event => {
event.preventDefault(); // suppress the reload
const $input1 = $form.find('[name=input1]');
const $input2 = $form.find('[name=input2]');
$.ajax({
method: $form.prop('method').toUpperCase(),
url: $form.prop('action'),
data: {
input1Value: $input1.val(),
input2Value: $input2.val(),
input1Class: $input1.prop('className'),
input2Class: $input2.prop('className')
}
}).
done(onSuccess).
fail(onFailure);
});
Inside you PHP, you'd use $_POST (or $_REQUEST) to grab the values which have been sent:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want with the variables
Note that you have to handle the server's response inside the onSuccess function. Usually, people use JSON to model a response from the server. You can use PHP's build-in json_encode and json_decode functions for it. For example, your PHP script could answer with:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want to do with the variables, then
$response = array(
'ok' => true,
'message' => 'PHP says "Thanks" for the information'
);
header('Content-Type: application/json');
echo json_encode($response);
die;
Inside the onSuccess function, you'd then for example:
function onSuccess (response) {
if (response.ok) {
console.log('Submitted, and all values where OK');
console.log(response.message);
return; // opt-out early, no need for "else" keyword
}
console.log('Submitted, but something went wrong');
console.log(response.message);
}

Passing variable from PHP to Javascript, using Ajax returns 'undefined'

I have got a PHP file that received data that has been posted from a form. It then sends it to a database. However I needed to get those variables and put them in JavaScript. I have done the following, but when logging the variables supposed to store the php data (in the script file) it return undefined.
What am I doing wrong? I am new to all the languages. The files are all separate - with the PHP and Script files being external.
SCRIPT:
$(function(){
var data1 = $("#username").val();
console.log(data1);
$.ajax({
type: "POST",
url: 'signUp.php',
data: ({data1}),
success: function(data) {
console.log("success");
}
});
});
PHP
if (isset($_POST['signup'])){
//The connection to the database
include_once 'databaseHandler.php';
//Gets the infomation submitted from the form
//Protects the database by converting everything to text...
//The database therefore cannot read the inputs as code
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
echo (".$user.");
HTML
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
You never set the post parameter 'signup'. Which in turn does not let you enter your if construct and therefor php gives you nothing.
Try:
data:{
"username":$('usernameSignUp').val(),
"password":$('passwordSignUp').val(),
"signup":1,
}
I think, you don't send the variable correctly.
var data1 = $("#usernameSignUp").val();
var data2 = $("#passwordSignUp").val();
$.ajax({
type: "POST",
url: 'signUp.php',
data: {signup:'1',username:data1,password:data2 },//Supose data1= username data, data2 = password data
success: function(data) {
console.log("success");
}
});
There is so much wrong here, it is hard to know where to begin.
You make the Ajax request when the page loads. This is before the user has typed anything into the form.
When the form is submitted, you don't use Ajax at all
You pass a field called data1 to the server (which it is not looking for)
You give that field the value of the input with id="username" (which doesn't exist)
You don't pass fields called username or password to the PHP (which it is looking for)
You don't pass a field called signup to the PHP (which it tests for with isset before doing anything)
Your PHP echos a variable called $user which you haven't defined
Your JavaScript doesn't look at the response, it just logs the string "success"
You'd need something more like:
$(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'http://example.com/signUp.php',
data: ({
signup: 1,
username: $("#usernameSignUp").val(),
password: $("#passwordSignUp").val()
}),
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log("This is a cross origin request to a dummy URL, what did you expect");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
Then there are the things which are bad practises but which don't directly affect the ability of the code to work.
You use mysqli_real_escape_string instead of placeholders.
You don't hash your passwords. "Not hashing at all" is an unsuitable hashing algorithm; you need to take better care of your users' passwords.
The HTML5 placeholder attribute is not a substitute for the label element

Ajax Request not working. Doesn't get connected to server

I've created a simple contact us form that captures data from textfields and then the data is converted to a JSON object and is being sent to the Server using Ajax. But I always gets the error. The success function isn't working. Which i believe that it doesn't get connected to the server.
Please tell me where I've gone wrong.
HTML
body>
<h1> Contact Us </h1>
We value your feedback. Send in your questions, suggestions, ideas to help us improve our service.
<h2 align="Center"> Search us on Google Maps</h2>
<br>
<br>
<form action="contact.php" name="form" method="post">
<br>Name :<br>
<input type="text" name="fName" id="fName" required >
<input type="text" name="lName" id="lName" required >
<br> <br>
Email: <br>
<input type="email" name="email" id="email" required >
<br> <br>
Comment: <br>
<textarea name= "comment" id = "comment" rows="8" cols="50" ></textarea>
<br> <br>
Rate our Website <select name="select" id="select" >
<option value = "1" name= "rate"> 1 </option>
<option value = "2" name= "rate"> 2 </option>
<option value = "3" name= "rate"> 3 </option>
<option value = "4" name= "rate"> 4 </option>
<option value = "5" name= "rate"> 5 </option>
</select>
<br> <br>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
Javascript
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
var jsonArr = {
firstName :document.getElementById("fName").value,
lastName :document.getElementById("lName").value,
email :document.getElementById("email").value,
comment :document.getElementById("comment").value,
rate :document.getElementById("select").value
};
$.ajax({
url : "contact.php",
type : "POST",
data : JSON.stringify(jsonArr),
dataType : "json",
success : function(data){
console.log("This is working", data);
},
error : function (error){
alert("Error. not working"+ error);
console.log("Error. not working" , error);
}
});
});
});
</script>
PHP
<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
?>
</body>
</html>
First, try adding a slash to your url to make it relative to your host:
$.ajax({
url : "/contact.php",
type : "POST",
data : JSON.stringify(jsonArr),
dataType : "json",
success : function(data){
console.log("This is working", data);
},
error : function (error){
alert("Error: " + error);
console.log("Error. not working" , error);
}
});
And second, close your PHP tag in the contact.php file:
<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
</body>
</html>
should be:
<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
?>
</body>
</html>
There are a few issues here:
Cancel default submit
You are not cancelling the default submit event so the form will get submitted the non-ajax way, effectively reloading the page (assuming that everything is done on contact.php).
You need something like:
$('form').on('submit', function(event) {
event.preventDefault();
...
});
Send the type of data that is expected on the server
You are not sending data to the server in a format that will allow you to access it through $_POST. You are sending a string so to get to that, you would need to read the input. If you want to access it through $_POST you need to send a query string or (better as they are encoded automatically...) an object. The easiest way to get your encoded data is using:
...
data: $('form').serialize(),
...
or, if you want to use your set keys:
...
data: jsonArr, // sending an object is fine, jQuery will encode it correctly for you
...
PHP syntax error
Your php has syntax errors as mentioned before. However, that is irrelevant here because of the next problem.
Return only json from your php script
The biggest problem with your php is that it returns html and not json. As you have set:
dataType : "json",
your php script needs to return valid json. So no tags, or any echoes except for a single json_encode().
So for your example, it should contain only:
<?php
$decode = $_POST['firstName'];
// do some more stuff?
echo json_encode($decode);
exit;
Try changing your JS (see below). Trigger onclick event, and prevent default from possible duplicate submisssions and restructure your json. See if this works.
<script>
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
url: "contact.php",
type: "POST",
data: {
'firstName': document.getElementById("fName").value,
'lastName ': document.getElementById("lName").value,
'email': document.getElementById("email").value,
'comment': document.getElementById("comment").value,
'rate': document.getElementById("select").value
},
dataType: "json",
success: function(data) {
console.log("This is working", data);
},
error: function(error) {
alert("Error. not working") + error;
console.log("Error. not working", error);
}
});
});
});
</script>
add an id attribute to form and try this code
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
$.ajax({
url : "contact.php",
type : "POST",
data : $("{formid}").serialize,
success : function(data){
console.log("This is working", data);
},
error : function (error){
alert("Error. not working")+ error;
console.log("Error. not working" , error);
}
});
});
});
</script>

php ajax form submit ..nothing happens

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.
Here is my HTML form:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="box_form">
<form id="zFormer" method="POST" action="contact.php" name="former">
<p>
Your Name:<input type="text" value="James Duh" name="z_name">
</p>
<p>
Your Email Address: <input type="text" value="duh#domain.com" name="z_requester">
</p>
<p>
Subject: <input type="text" value="My Subject Here" name="z_subject">
</p>
<p>
Description: <textarea name="z_description">My Description Here</textarea>
</p>
<p>
<input type="submit" value="submit" id="submitter" name="submit">
</p>
</form>
</div>
<div class="success-message-subscribe"></div>
<div class="error-message-subscribe"></div>
<script>
jQuery(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('.box_form form').submit(function() {
var postdata = $('.box_form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>
</body>
</html>
And the PHP Part:
You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.
<?php
( REMOVED API CALL CODE FROM ABOVE HERE )
if (isset($_POST['submit'])) {
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array(
'subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']),
'requester' => array('name' => $arr['z_name'],
'email' => $arr['z_requester'])
)));
$return = curlWrap("/tickets.json", $create, "POST");
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thank you!';
echo json_encode($array);
?>
Any ideas why this isn't working?
I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine
Replace jQuery(document).ready(function() { by
$(document).ready(function() {
Secondly from Jquery documentation:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Therefore submit button won't serialize through jQuery.serialize() function.
A solution below:
<script>
$(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('#submitter').click(function(e) {
e.preventDefault();
$myform = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
var postdata = $myform.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped

Categories

Resources