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

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>

Related

AJAX Request Payload not showing up in console log

I am learning AJAX and I am trying to log all the data parameters in the console in case of success and in case of a failure to throw an alert. My code works and I can successfully dump the data I send, but nothing shows up in the console, even though I explicitly put console.log within the Javascript to register that.
this is my code.
Html page
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>Send JSON</h2>
<form action="postrequest.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="param1"/>
<input type="text" name="param2"/>
<input type="text" name="param3"/>
<button type="submit">Submit</button>
</form>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var param1 = $("#param1").val();
var param2 = $("#param2").val();
var param3 = $("#param3").val();
$.ajax({
url : 'postrequest.php',
contentType: "application/json",
dataType: "json",
type : 'POST',
data: JSON.stringify({
param1: param1,
param2: param2,
param3: param3
}),
success: function(data) {
console.log(data);
},
error: function (data) {
alert(data.param3);
}
});
});
});
</script>
</html>
postrequest.php
<?php
var_dump( $_POST);
What am I doing wrong?
Error 1: Remove the form tag. It will work because it contains action="postrequest.php". You are doing 2 things at the same time.
Submitting the form via PHP using the form tag.
You are performing ajax and submitting the form.
Error 2: You are writing var param1 = $("#param1").val(); Where is the param1, param2,param3 you defined?
Error 3: You are giving the jquery link, you don't have closed the script tag.
Error 4: You are sending the data in ajax and outputting the ajax response again with the same variable
Error 5: Ajax error block you have created is wrong.
<!DOCTYPE html>
<html>
<body>
<input type="text" name="param1" id="param1"/>
<input type="text" name="param2" id="param2"/>
<input type="text" name="param3" id="param3"/>
<input type="button" value='Submit' class="js-ajax-php-json" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".js-ajax-php-json").click(function() {
var param1 = $("#param1").val();
var param2 = $("#param2").val();
var param3 = $("#param3").val();
$.ajax({
url: 'postrequest.php',
dataType: "html",
type: 'post',
data: {
param1: param1,
param2: param2,
param3: param3
},
success: function(rsp) {
console.log(rsp);
},
error: function(jqXHR, status, err) {
console.log("Error");
},
});
});
});
</script>
</body>
</html>
postrequest.php page
<?php
print_r($_POST);
?>
I have just rewritten your code with a very simpler one. You can
change it as per your requirement.
I think the root cause is that the page is reloading once you hit submit. Hence you cannot see anything in the console. Try the following steps.
Remove the 'action' and 'method' attributes from the form tag. This is already handled in ajax request.
Add onsubmit="return false;" attribute to the form tag. This will prevent reloading of the page.

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

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>

Partially working AJAX that writes form input to text file

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>

passing values from javascript to php

HTML CODE
<form action="phpfile.php" method="post">
<input type="button" id="id1">
<input type="button" id="id2">
<input type="submit">
</form>
<div id="result"></div>
JAVASCRIPT CODE
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
Can you give me some tips on how I can send the qty1, qty2 and totalqty to my php file, after I click the submit button. Before I send it to the php file, I need to check first if the button is already clicked. If not, no qty will be send to the phpfile. I need to send the exact number of qty based on how many times you clicked the button.
The easiest solution would be to add qty as <input type="hidden" id="qty1" name="qty1" /> to your form. They will be invisible as your variables, and will be sent to the server as form fields. To access their values from Javascript, use $("#qty1").value()
You're looking for something called AJAX.
This is easy to implement using the jQuery library, but it's also available using regular JavaScript.
If you choose to use the jQuery implementation then your can look at the documentation.
Here's a basic example:
$.ajax({
type : 'post',
url : 'target.php',
dataType : 'json',
data : {
'foo' : 10
}
}).done(function()
{
$(this).addClass("done");
});
You then use the back-end to handle the response, let's for example assume that you send an object of parameters whera one key is named foo and the value is 10, then you could fetch it like this (if the code is PHP):
$foo = isset($_POST['foo']) ? $_POST['foo'] : "";
Using the ternary operator
try using jquery $.ajax or $.post function:
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
get_values(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
get_values(qty2);
});
function get_values(qty_val) {
$.post(
'get_values.php', // url of your php who will receive the values
{ post_variable_name: qty_val }, // your post variables here
function(data) {
// call back function
$("#result").html(data); // see what does your get_value.php echoes via html
console.log(data); // see it via console in inspect element
}
);
}
and in your php that will recieve the values, just retrieve using $_POST:
<?php
$qty_val = '';
if(isset($_POST['post_variable_name'])) {
$qty_val = $_POST['post_variable_name'];
echo $qty_val;
}
?>
HTML
<form>
<input name="id1" type="button" id="id1" />
<input name="id2" type="button" id="id2" />
<input type="submit" />
</form>
<div id="status"></div>
JS
qty1=0;
qty2=0;
totalqty=0;
$("#id1").click(function(){
qty1=qty1+1;
totalqty=totalqty+1;
$("#result").html(qty1);
});
$("#id2").click(function(){
qty2=qty2+1;
totalqty=totalqty+1;
$("#result").html(qty2);
});
$( "form" ).submit(function( event ) {
// prevent the default event
event.preventDefault();
// check first if the totalqty. You can add more checks here
if ( totalqty === 0 ) {
// usually show some kind of error message here
alert('No quantity selected!');
// this prevents the form from submitting
return false;
} else {
$.ajax({
type: 'post',
url: 'phpfile.php',
dataType: 'json',
data: {
quantity1: qty1,
quantity2: qty2,
totalQuantity: totalqty
}
}).done(function(data) {
console.log(data);
alert( "success" );
$('#status').html("Successfully saved!");
}).fail(function() {
console.log(data);
alert( "error" );
$('#status').html("Successfully saved!");
});
}
});
PHP
$qty1 = isset($_POST['quantity1']) ? $_POST['quantity1'] : "";
$qty2 = isset($_POST['quantity2']) ? $_POST['quantity2'] : "";
$total = isset($_POST['totalQuantity']) ? $_POST['totalQuantity'] : "";
Sorry, i can't test it, but it should work
For more detailed you could have a look to the jQuery Learning Center - Ajax where you can find useful examples to work with ajax and forms.

Categories

Resources