AJAX button not submitting and not going through - javascript

I'm having an issue where my Ajax code doesn't go through .. As if the functions is empty.
I clicked submit , nothing happens ..
My HTML code :
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<body>
<form method="POST" id="contactForm" >
<input type="text" name="email" id="email"></input>
<input type="submit" name="submit"></input>
</form>
<script type="text/javascript">
$('#contactForm').submit(function(e){
e.preventDefault();
var email = $('#email').val();
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'check.php',
data: {email: email},
success: function(data){
if(data.status == 'success') {
alert('The e-mail address entered is correct.');
} else {
alert('The e-mail address entered is Incorrect.');
}
}
});
});
</script>
</body>
</head>
My check.php:
<?php
if (isset($_POST['email'])) {
$status = 'success'
} else {
$status = 'failed';
}
echo json_encode(array('status' => $status));
?>
When i click submit , it just do nothing..
i want the error to pop up.
Is there anything i missed?

Make sure that all the options you're passing into the ajax call are properly cased. Example: datatype needs to become dataType, and beforesend needs to become beforeSend.
Here is the reference: http://api.jquery.com/jquery.ajax/

The brackets are misplaced and you are missing a : for "success" callback. See fixed code below,
And the case too as mentioned in the other answer here..
$('#contactForm').submit(function () {
var email = $('#email').val();
$.ajax({
type: 'GET',
dataType: 'json',
url: 'check.php',
beforeSend: function () {},
// v--- missing :
success: function (data) {
if (data.status == 'success') {
alert('The e-mail address entered is correct.');
} else if (data.status !== 'success') {
alert('The e-mail address entered is wrong.');
}
} // this was misplaced in the line below in your code
}); // this was misplaced in the line above in your code
});

Try to debug using the dev tools of Firefox or Chrome.
On Chrome's DevTools for example:
Debug Javascript with the source option. Or you cold add some console.log() inside your .submit() function to make sure that the event handler is triggering.
Use the network tab to make sure the ajax call is being made and check which response you get from server.
Last but not less important, check the console tab for Javascript errors to see if another script throws an error before the excecution of your script.
With these techniques, you can identify what could be wrong and see how could could solve it.

Related

Page is getting Submit Without Refresh Via Otp?

I got this website when I fill the information and try to send the OTP page reload
Here's the website:
https://tunisia.blsspainvisa.com/english/book_appointment.php
After you fill the information and click on (Request verification code) and you will know what I mean
What I tried is:
$(function () {
$('#tunisiaThird').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://tunisia.blsspainvisa.com/book_appointment.php',
data: $('#tunisiaThird').serialize(),
success: function () {
}
});
});
});
I'm only a client, so I'm using Tampermonkey to inject.
You need to read more about jquery ajax post or get method here:
https://api.jquery.com/jQuery.post/
And there are tons of questions here if you search you will find tons of examples
Here is a complete example, which is getting error messages from php part and displaying on html form.
Like this: in php : $error .= 'an error happend'; and ajax $('#result').html(data.error);
to display in html.
<div id="result"></div>
$(document).ready(function(){
$('#tunisiaThird').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"book_appointment.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html('Successfuly');
$('#tunisiaThird')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
}
}
});
});
});

validating ajax data values

Is it possible to validate if there empty input?
I want to check if data has gotten values from html. If true then should disable button. If not then don't disable button.
This the sample html
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<label>email
<input type="text" name="email" />
</label>
</form>
</body>
</html>
thats the sample html
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
success: function(res) {
if (data) {
$("#Submit").attr("disabled", true);
$('#success').text(res.response);
} if (!data) {
$("#Submit").attr("disabled", false);
$('#error').text(res.error_msg);
} else { // do nothing }
},
error: function(resp) {
alert("failed");
}
});
};
});
</script>
U can validate the values before triggering an ajax request. As u can serialize your form data and then validate your required values for the request and if they validate then trigger the ajax call with required data
function Execute(){
// Contains all the inputs that are present in your form
var formData = $('form').serializeArray();
// Validate your values
// If values does not matches your requirements, return false with error like
alert('All required values not filled');return false;
// If code reaches here, means you have all your required values.
// So, making ajax request makes more sense now as it can be executed successfully as values are first validated then ajax is triggered
$.ajax({
// Your code for ajax request
})
}
Try this one. I just modified your code. Hope it helps you out. Basically ajax call is not called untill you validate youe values and once you validated your values you can proceed with ajax and handling your button state using ajax lifecycle functions ( I don't know the exact term for these (beforeSend, complete, success etc) ) :)
LOL it was more easy like this
i got fixed D:)
only Before send was the solution
<script>
$(document).ready(function () {
$("#Submit").click(function(event) {
Execute();
});
function Execute(){
$.ajax({
type: 'POST',
url: 'test.php',
data: { 'email': $("input[name='email']").val() },
beforeSend: function(){
if ($("form input[name='email']").val() == "") {
alert("Text-field is empty.");
return false;
}
},
success: function(response) {
$("#Submit").attr("disabled", true);
$('#resp').text(response.feedback);
},
error: function() {
alert("failed");
}
});
};
});
</script>

Trying to send a value from JS to PHP - JQuery's $.ajax() method is not working

I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.
This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.
Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);.
Why isn't this working properly? How can I fix this?
From index.php:
<form id="form">
Name:
<input id="name" type="text" />
<input type="Submit" value="Go" />
</form>
From scripts.js:
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
alert(name);
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
}
});
});
});
echo.php:
<?php
if ( isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"]) ) {
echo $_POST["nameEntered"];
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
EDIT:
Console:
Network:
EDIT 2:
Added the following to $.ajax():
,
success: function(){
alert("success");
},
error : function(){
alert("error");
}
I get an alert saying success but the browser NEVER directs to echo.php =s
EDIT 3:
After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.
This way should show response.
JAVASCRIPT
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
//alert(name);
$.ajax({
type:'POST',
url:'http://localhost/Test12/echo.php',
data: {
nameEntered : name
},
success : function(data){
console.log(JSON.parse(data));
},
error : function(error){
console.log('erro', error);
}
});
});
PHP
<?php
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
$name = array("nome" => $_POST["nameEntered"]);
echo json_encode($name);
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
As a test, replace your echo.php with:
<?php
echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
echo 'Here 01';
} else {
echo 'Here 02';
}
?>
Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'
I think you need to add "event" as parameter in your submit function, in addition to the success call to show results
What does this give you:
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
},
success: function(recd){ // <-------
alert(recd); // <-------
},
error : function(){
alert("error");
}
});
You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.
Try:
function(e){
e.preventDefault();
};

Alert message in browser using Ajax based on Node JS response

I developed a simple form where a user can enter an author name. The name will be queried using Node JS in the database to check if there are tweets written by this author or not. If there is no data, I want to response to the client using Ajax by showing an alert.
This is the client side:
<html>
<head>
<script>
$(document).ready(function() {
$.ajax({
error: function(error){
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
}
}
});
});
</script>
</head>
<body>
<form action="/process_post" method="POST">
<select name="SearchTypes">
<option value="Author" selected>Author</option>
<option value="Mention">Mention</option>
<option value="Tag">Tag</option>
</select>
<input type="text" name="term">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is the part of the Node JS that includes the response:
var query = connection.query(queryString, [term,term], function(err, rows) {
console.log(rows);
var tweet = JSON.parse(JSON.stringify(rows));
if (tweet.length == 0){
res.status(500).send('showAlert');
}else{
for(var i in tweet){
res.write("Author: ");
......
As you see, I used res.status(500).send('showAlert'); to send the response to the client side but what really happens is that when I provide an input that does not have any data in the database (tweet length is zero), it just prints showAlert in the HTML page.
That's because the above JavaScript runs the control only if there is an error, but your message is sent as a correct response. You should change your client code to check in case of success, like this:
$(document).ready(function() {
$.ajax({
error: function(error){
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
success: function(result){
if (result.responseText == 'showAlert'){
alert("There was an error")
}else{
//Do things...
}
}
}
}
});
});
You want to wrap the ajax call in a form submit handler. Right now, when you submit the form, it is doing a full synchronous request and coming back with the text "showAlert".
$(document).ready(function() {
$('form').on('submit', function (e) {
// keep the form from submitting synchronously
e.preventDefault();
var $form = $(e.currentTarget);
// submit via ajax
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
data: $form.serialize()
})
.done(function (response) {
console.log('done: ', arguments);
})
.fail(function(error){
console.log('failed: ', arguments);
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
}
})
});
});
Remove those calls to console.log once you have it working as you need. See $.ajax for options in that call.
You will probably also want to give your form an id and then refer to it that way, e.g. $('#myForm'), so that you can add more forms to the page without causing any problems.

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories