Ajax POST keep firing error function event though php script success - javascript

I am using jquery, jquery mobile and html to build a mobile app using phonegap.
Using ajax to call php scripts in server, works fine; updating, inserting data and sending email. However ajax error function is what always called,
Using firebug, 200 ok status is what returned, no idea what triggers error.
I have searched for this issues and found many suggestions here such as using complete () or done() functions instead of success() and error(), echoing json response... but no luck with all these solutions.
one solution is to add this header to php script,
header("Access-Control-Allow-Origin: *");
header solution has solved my problem with all ajax post scripts, however I am concerning about possible security risks because it is should run in mobile application.
In addition, adding such header can be logic when we need to access database but if we have a contact form that call php mail function and no database changes will occur , why we need to add that header too?
contact form
<div data-role="header" data-position="fixed" >
<input type="button" value="Send" name="sendbutton" id="sendbtn" />
<h1>contact us</h1>
<a data-rel="back" data-icon="arrow-r" data-iconpos="notext"></a>
</div>
<div data-role="content" >
<form id="contact-us" >
<input type="text" id="contactName" placeholder="Name" />
<input type="email" id="email" placeholder="Your Email" />
<input type="text" id="subject" placeholder="Message Subject" />
<textarea rows="20" cols="30" id="message" placeholder="Message.." ></textarea>
</form>
</div>
Jquery script
$("#sendbtn").click(function(event){
$("#sendbtn").disabled =true;
var postData ="";
if($("#contactName").val().length == 0 ||$("#email").val().length == 0 ||$("#subject").val().length == 0||$("#message").val().length == 0)
alert("Sorry but some required fields are empty !");
else {
if (!regex.test($("#email").val()))
alert("Please check that you write email correctly!");
else {
postData='contactName=' + $("#contactName").val() + '&email=' + $("#email").val() + '&subject=' + $("#subject").val() + '&message=' + $("#message").val();
$.ajax({
type: 'POST',
data: postData,
url: 'mydomainname.net/services/contact.php',
success: function(){
$('input').not('[type="button"]').val('');
$('textarea').val('');
alert('Message was Sent, Thank you!');
},
error: function () {
alert('Sorry, Error occurred ');
$('.error').fadeIn(1000);
}
});
}
}
});
php code
<?php
if ( isset($_POST['email']) && isset($_POST['contactName']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
mail( "myemail#mydomainname.net", "Contact Form: ".$_POST['contactName']." Title ".$_POST['subject'], $_POST['message'], "From:" . $_POST['email']);
}
?>
The code send email but always called ajax error function
Any other solution rather than header solution? thank you.

there some unclose breaks, try this :
$("#sendbtn").click(function(event){
$("#sendbtn").disabled =true;
var postData ="";
if($("#contactName").val().length == 0 ||$("#email").val().length == 0 ||$("#subject").val().length == 0||$("#message").val().length == 0) {
alert("Sorry but some required fields are empty !");
} else {
if (!regex.test($("#email").val())) {
alert("Please check that you write email correctly!");
} else {
postData='contactName=' + $("#contactName").val() + '&email=' + $("#email").val() + '&subject=' + $("#subject").val() + '&message=' + $("#message").val();
}
}
$.ajax({
type: 'POST',
data: postData,
url: 'contact.php',
success: function(){
$('input').not('[type="button"]').val('');
$('textarea').val('');
alert('Message was Sent, Thank you!');
},
error: function ()
{
alert('Sorry, Error occurred ');
$('.error').fadeIn(1000);
}
});
});

First, i think, collecting postData you should do like $('#my-form').serialize();
url: 'mydomainname.net/services/contact.php'
url should be set with scheme prefix, if you want post to another server.
however I am concerning about possible security risks.
At server side you can check domain and than decide - send allowed header or not.

Related

How to fix ajax request/response for mobile browsers in my code

code shown in picture This code perfectly works in desktop browsers,but for mobile browser directly redirect to url location,not works in my below code...To click on submit button form input data sent to process-data.php via submit-data.js and response shown to span
**form.php**
<script src="https://code.jquery.com/jquery-1.6.4.js"></script>
<script src="js/form/submit-data.js"></script>
<form id="feed_<?php echo$type_id;?>" action="include/process_data.php" method="post">
<input type="hidden" name="cmd_<?php echo$type_id;?>" value="<?php echo$type_id; ?>">
<input type="hidden" name="item_<?php echo$type_id;?>" value="<?php echo $type_name;?>">
<input type="hidden" name="amount_<?php echo$type_id;?>" value="<?php echo $ac_p;?>">
<input type="submit" class="fa fa-chevron-down" value="Submit">
</form>
<span id="dFcn_<?php echo$type_id;?>"></span>
submit-data.js
//submit-data.js
$(document).ready(function() {
$('form').submit(function(event) {
var charid = this.id;
var idsplit = charid.split('_');
var getid = idsplit[1];
var cmsd=$('input[name=cmd_'+getid+']').val();
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
var formData = {
'cmd' : $('input[name=cmd_'+getid+']').val(),
'item' : $('input[name=item_'+getid+']').val(),
'amount' : $('input[name=amount_'+getid+']').val()
};
$.ajax({
type : 'POST',
url : 'include/process_data.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//console.log(data);
if ( ! data.success) {
// errors message
$('#dFcn_'+cmsd+'').append('<div class="alert alert-success">' + data.message + '</div>');
} else {
//success message!
$('#dFcn_'+cmsd+'').append('<div class="alert alert-success">' + data.message + '</div>');
}
})
//stop refreshing the page
event.preventDefault();
});
});
process_data.php
<?php
//array
$data= array();
if (empty($_POST['cmd']) && empty($_POST['item']) && empty($_POST['amount']))
$POST_DATA_FALIURE = 'POST DATA FALIURE';
if ( ! empty($POST_DATA_FALIURE)) {
$data['success'] = false;
$data['errors'] = $POST_DATA_FALIURE;
} else {
$data['success'] = true;
$data['message'] = 'SUCCESS MESSAGE';
}
echo json_encode($data);
?>
Actually the form was in table "td" tag and in the same page too many js conflict,
after removing external linked js (given below), that's worked for me in cross browser.
[Note:] However by this technology we can generate multiple form in while loop and send multiple form-data and get each form submitted response over ajax without page reload,Thank you.
[these js was linked for making table responsive,data search type]
DataTables 1.10.19
Bootstrap integration for DataTables' Responsive
Responsive 2.2.3
FixedHeader 3.1.5
DataTables Bootstrap 3 integration

How to check unique username before form submission

I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.

redirect page upon form submit after AJAX request that calls PHP function

I have an HTML page (index.html) that collects an email address and submits it to a server via an AJAX POST request. When the submit button is clicked, a javascript function executes the post request via AJAX and then the page submits to itself. I need to modify this so that the page submits to another page (thankyou.html) instead of to itself. I'm not sure how to do this in PHP. Is there a way to redirect a PHP page once a form is submitted and the AJAX query is executed?
I'm not sure if I should redirect the page in Javascript or in HTML or in PHP.
This is the form in index.html:
<form class="email-form" method="POST" validate>
<div class="email-input-container register-info-email">
<input class="email-input" type="email" autocapitalize="off" autocorrect="off" autocomplete="off" required name="MERGE0" id="MERGE0" placeholder="Email Address" pattern="[a-z0-9._%+-]+#[a-z0-9-]+\.[a-z]{2,63}$" aria-label="Email Address">
<input id="sub-button" type="submit" class="submit-button" value="Submit" >
<span class="success-message"><span class="sr-only">We got you</span></span>
</div>
</form>
This is the post request in PHP (post.php)
if ( isset($_POST['email']) ) :
$data = [
'email' => $_POST['email']
];
if ( isset($_POST['platform']) ) :
$data["device"] = $_POST['platform'];
endif;
syncMailchimp($data);
endif;
This is the AJAX request:
$.ajax({
type: "POST",
url: 'post.php',
data: data,
success: function(data, status) {
var message = JSON.parse(data).message;
if (message == "error") {
$('.email-form small').html('An error has occurred. Please try submitting again.');
smallHighlight();
} else if (message == "subscribed") {
$('.email-form small').html('You are already subscribed');
smallHighlight();
} else {
$('.email-form').addClass('form-success');
$('.email-form small').attr('style', '');
}
},
If you want to redirect to another page, put this after form is successfully submited
window.location = "http://www.example.com/thankyou.html";
EDIT: You shouldn't handle this redirect in PHP, because this is asynchronous call. You need to reference this somehow in you submit script
Hope it helps
In PHP you can use this.
header('Location: http://www.example.com/thankyou.html');
and In Javascript
window.location.replace("http://www.example.com/thankyou.html");
or
window.location.href = "http://www.example.com/thankyou.html";

Post a form using Jquery ajax and get the response

I'm using this code to post a form using jquery ajax .
my problem is that i want to make php code to be like this:
if (isset($_POST[''])) {
// some code here
}
this is the javascript code:
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" )
$("div#status").html("Please enter your Email");
else
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
$("#myForm").submit( function() {
return false;
});
});
If you tested the code, and the php section works fine, but you can not get a response in jquery, then, you should check your php code(It should be like this):
if (isset($_POST[''])) {
$data = "";
// some code here to fill $data
echo $data; // this is the actual response to the jquery interface.
}
There are 6 b's in php file name but 7 b's in ajax url.
url: "bbbbbbb.php", <--- 7 b's
bbbbbb.php <--- 6 b's
Plus, along with success you should have error also so you'd see what the error is.
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
Despite a lack of actual question, here's a crack at an answer.
The first issue is that the javascript, while working, won't get to do the complete job it's supposed to do. The javascript code appears to want to prevent the form from being manually submitted via the submit event. You may want to reorganise the javascript to look like:
$("#myForm").submit( function() {
return false;
});
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" ) {
$("div#status").html("Please enter your Email");
} else {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
}
});
Additionally, you may want to look up usage of modern event watching in jquery, and the usage of .on(). i.e. $("#myForm").on("submit", function() {});. But that's not quite the point of this post.
As for the PHP code, let's infer you have the following HTML form:
<form action="login.php" id="myForm">
<label for="username">Username: </label>
<input type="text" id="username" name="username" />
<label for="password">Password: </label>
<input type="password" id="password" name="password" />
<button type="submit" id="submit" name="submit" value="submit">Submit</button>
</form>
<div id="status">Please provide username and password to login</div>
In login.php, you would have
if (!empty($_POST)) {
if (isset($_POST['submit']) && $_POST['submit'] == 'submit') {
// validate $_POST contains username and password
...
// sanitize username and password
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);
// do my processing
// doLogin returns true for successful login, or message contain error string
$result = doLogin($_POST['username'], $_POST['password']);
if ($result === true) {
echo 'You have successfully logged in';
} else {
echo $result;
}
} else {
echo 'Unknown form action';
}
} else {
// do GET processing
}
With this, just echo the response you want to appear in the div#status.

Ajax login returning incorrect details even when details are correct

I am new to ajax, jQuery and JavaScript and this is more of a learning exercise for myself to brush up on some skills. I want to move away from login pages that are separate pages (i.e. loginForm.php that sends data to login.php which then redirects to a logged in section) and want to move down a jQuery ajax route.
I have built my index page as follows:
<form id="login_form">
<h1>Login Form</h1>
<div>
<input type="text" placeholder="Username" required="" id="user_name" name="user_name"/>
</div>
<div>
<input type="password" placeholder="Password" required="" id="password" name="password"/>
</div>
<div class="err" id="add_err"></div>
<div>
<input type="submit" value="Log in" id="login" />
</div>
</form>
I have set my JavaScript up like so:
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
console.log(username + " " + password);
var info = {username:username, password:password};
console.log(info);
var sub = $.ajax({
async: false,
type: "POST",
url: "login.php",
data: info,
success: function(html){
if(html=='true')
{
$("#login_form").fadeOut("normal");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
},
error: function(response) { console.log(response); }
});
console.log(sub);
return false;
});
when I console.log(info) it tells me in the log that this is an object and it has the information that I need to send. So I'm sure that this part so far is okay. The following script is my login.php:
<?php
include('secure.php'); // includes PDO database connection here
$username = $_POST['username'];
$password = $_POST['password'];
$sel = $db->prepare("SELECT * FROM aaUsers WHERE username='$username' AND password='$password'");
$sel->execute();
$count = $sel->rowCount();
if ( $count >= 1) {
echo "true";
}
else
{
echo "false";
}
?>
The info is passed across to here and then this script runs, however, when I console.log(sub) I can see that the responseText = "" and this is causing my script to fail over. would someone be able to inform me where I have gone wrong, I feel like I'm doing everything right, just that there seems to be somewhere I have gone wrong.
Are you using chrome, or firefox (with firebug)? Open the developer console and watch what comes back from the AJAX call. If it's blank there, then as scrowler has put well, your php is faulty. You could also create a quick non-ajax testing form to post the two variables the ol' fashioned way.
<html>
<body><form action=login.php method=post><input name=username/> <input name=password/> <input type=submit></form></body></html>
Fill in the blanks and hit submit.
My bad.
Turns out I had called:
$sel = $db->prepare(...);
instead of:
$sel = $conn->prepare(...);
works fine now, thank you for your suggestions for looking at my php script.

Categories

Resources