I have a PHP file receiving data from Ajax but after receiving the data I am sending a success message from php using json_encode, but the message error is hit is being alerted even though the SQL query is successful. This process worked well for localhost but when I uploaded it in main server there is an error.
Here Is my JS file:
$(function() {
$("#userReg_btn").click(function(e) {
//user registration in
var array = [];
var flag = false;
var firstName = $("#uFn").val();
var lastName = $("#uLn").val();
var email = $("#uEa").val();
var pass = $("#uPn").val();
var mobile = $("#uMn").val();
var nID = $("#uNm").val();
var age = $("#uAn").val();
var prof = $("#uPc").val();
if (firstName == "" || lastName == "" || email == "" || pass == "" || mobile == "" || nID == "" || age == "" || prof == "") {
e.preventDefault();
alert("Please provide some input");
flag = false;
} else if (mobile.length != 11 || nID.length != 17) {
e.preventDefault();
alert("Please provide correct input");
flag = false;
} else {
array.push(firstName);
array.push(lastName);
array.push(email);
array.push(pass);
array.push(mobile);
array.push(nID);
array.push(age);
array.push(prof);
alert(array);
console.log(array);
flag = true;
}
if (flag == true) {
$.ajax({
url: "http://demoname.co/CustomerRegistration.php",
data: {
firstName: array[0],
lastName: array[1],
email: array[2],
pass: array[3],
mobile: array[4],
nID: array[5],
age: array[6],
prof: array[7]
},
type: "POST",
dataType: "json",
success: function(suc) {
alert("in success");
alert(suc);
console.log("success");
},
error: function(err) {
alert("error is hit");
alert(err);
console.log(err);
}
});
} else {
alert("Form error");
}
alert("USer Reg");
});
Here is my PHP file:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
// The JSON standard MIME header.
header('Content-type: application/json');
$con=mysql_connect("localhost","username", "password");
mysql_select_db("database name",$con);
$fname = $_POST['firstName'];
$lname=$_POST['lastName'];
$username=$_POST['email'];
$password=$_POST['pass'];
$phone=$_POST['mobile'];
$nid=$_POST['nID'];
$age=$_POST['age'];
$profession=$_POST['prof'];
$query="INSERT INTO customerregistration(FirstName,LastName,Username,password,PhoneNumber,NID,Age,Profession) VALUES('$fname','$lname','$username','$password','$phone','$nid','$age','$profession');";
if(mysql_query($query))
{
$suc= 'success';
echo json_encode($suc);
}
else
{
echo mysql_error();
}
?>
Related
I have a simple registration form. What I want to achieve is when the output from PHP is success then do something. Else do something else. Both in AJAX. I hope you can help me because I am totally new in jQuery and AJAX
This is part of my PHP for this form:
if ($kontrolaMenoPocet != 0) {
$error[] = "<p class='text_chyba'>Takéto meno už existuje!</p>";
}
if ($pocetZnakovNick > 15) {
$error[] = "Nick môže mať maximálne 15 znakov!";
}
if ($kontrolaEmailPocet != 0) {
$error[] = "<p class='text_chyba'>Takýto E-mail sa už používa</p>";
}
if ($pocetZnakovHeslo != 0 AND $pocetZnakovHeslo < 6) {
$error[] = "Heslo musí mať minimálne 6 znakov";
}elseif ($pocetZnakovHeslo == 0) {
echo "";
}
if ($heslo != $hesloZnova) {
$error[] = "Hesla sa nezhodujú";
}
if (empty($error)) {
//writte into database
}
if (isset($error)) {
if (empty($error)) {
echo "Success";
}else{
foreach ($error as $chyba) {
echo $chyba;
}
}
}
And this is my jQuery with AJAX:
if (nick == '' || email == '' || heslo == '' || hesloZnova == '') {
$('.registracia_form .nick, .email, .password, .password_again').addClass('inputError');
} else {
$.ajax({
method: 'post',
url: 'PHP/register.php',
data: data,
}).done(function(data) {
console.log("success");
}).fail(function() {
console.log("error");
}).always(function() {
console.log("complete");
});
}
Change your .done() callback to:
.done(function(data) {
console.log(data);
if (data === 'Success') {
// do something
} else {
// do something else
}
})
In PHP, when there is error, use http_response_code function to set status code other than 200 so the fail function in ajax will be called.
after success my page wont reload but it just close the window
this is my jQuery script
jQuery("#edit").dialog({
modal: true,
resizable: false,
draggable: false,
autoOpen: false,
width: 400,
buttons: [
{
text: "Ok",
click: function() {
var message = "";
var id = jQuery.trim(jQuery("#id").val());
var fname = jQuery.trim(jQuery("#firstname").val());
var lname = jQuery.trim(jQuery("#lastname").val());
var email = jQuery.trim(jQuery("#email").val());
var telephone = jQuery.trim(jQuery("#telephone").val());
var mobile = jQuery.trim(jQuery("#mobile").val());
var address = jQuery.trim(jQuery("#address").val());
var bdate = jQuery.trim(jQuery("#bdate").val());
if (fname == "") {message += "Please enter firstname\n"};
if (lname == "") {message += "Please enter lastname\n"};
if (email == "") {
message += "Please enter email\n"
}
else{
if(!ValidateEmail(email)){
message += "Please enter valid email address.\n"
}
}
if (telephone == "") {message += "Please enter telephone\n"};
if (mobile == "") {message += "Please enter mobile\n"};
if (address == "") {message += "Please enter address\n"};
if (bdate == "") {message += "Please enter birthdate"};
if (message != "")
{
alert(message);
return false;
}
else
{
jQuery.ajax({
type: "POST",
dataType: "json",
url: "update.php",
async:true,
data: {
"id": id,
"firstname": fname,
"lastname": lname,
"email": email,
"telephone": telephone,
"mobile": mobile,
"address": address,
"bdate": bdate
},
sucess: function(){
window.location.reload(true);
}
});
}
}
},
{
text: "Cancel",
click: function() {
jQuery(this).dialog( "close" );
}
}
]
});
and here is my PHP
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$bdate = date("Y-m-d",strtotime($_POST['bdate']));
$sql = "UPDATE user SET
firstname='$firstname', lastname='$lastname', email='$email', telephone='$telephone', mobile='$mobile', address='$address', bdate='$bdate' WHERE id=$id";
$result = mysql_query($sql);
if($result){
echo json_encode(array(
"success" => true,
));
}
i tried also this but doesnt reload the page
sucess: function(data){
if(data.success == true){
window.location.reload(true);
}
}
also i changed the window.location.reload into location.reload and i tried also removing the true in it
I have a simple PHP file which logs the details of an order to a text file.
It is used on a custom shopping cart in Drupal using the form_wizard which collects the order details (what was ordered, where to ship it, etc) to a cookie, then processes the order via PayPal.
When the user clicks the place order button, the log file saves that order info as a JSON object.
However, the PHP file seems to only log the order to the file if the user is using Chrome. If the user is using Safari, the log does not get appended.
The PHP is below:
<?php
logcart();
function logcart() {
$file = 'cart.txt';
$today = date("F j, Y, g:i a");
$customer = $_COOKIE["address"];
$cart = $_COOKIE["votre_commande"];
$cart_contents = $today.PHP_EOL.$customer.PHP_EOL.$cart;
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same
// time file_put_contents($file, $cart_contents, FILE_APPEND | LOCK_EX);
}
Along with the above PHP is the following JS:
function cartToLog() {
console.log('logging the cart!');
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.withCredentials = false;
},
crossDomain: true,
dataType: 'jsonp',
url: "http://example.com/modules/form_example/js/logcart.php",
headers: {
'Access-Control-Allow-Origin': '*'
},
contentType: 'application/json',
data: "",
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
Drupal.behaviors.select_paypal = {
attach: function(context) {
$('.paypal-button', context).once(function() {
$(this).click(function(e) {
if ($('#edit-tf-prenom').val() == '' ) { $('#edit-tf-prenom').addClass('error'); } else { $('#edit-tf-prenom').removeClass('error');}
if ($('#edit-tf-nom').val() == '' ) { $('#edit-tf-nom').addClass('error'); } else { $('#edit-tf-nom').removeClass('error');}
if ($('#edit-tf-adresse').val() == '' ) { $('#edit-tf-adresse').addClass('error'); } else { $('#edit-tf-adresse').removeClass('error');}
if ($('#edit-tf-code-postal').val() == '' ) { $('#edit-tf-code-postal').addClass('error'); } else { $('#edit-tf-code-postal').removeClass('error');}
if ($('#edit-tf-ville').val() == '' ) { $('#edit-tf-ville').addClass('error'); } else { $('#edit-tf-ville').removeClass('error');}
if ($('#edit-tf-pays').val() == '' ) { $('#edit-tf-pays').addClass('error'); } else { $('#edit-tf-pays').removeClass('error');}
if ($('#edit-tf-email').val() == '' ) { $('#edit-tf-email').addClass('error'); } else { $('#edit-tf-email').removeClass('error');}
if ($('#edit-tf-telephone').val() == '' ) { $('#edit-tf-telephone').addClass('error'); } else { $('#edit-tf-telephone').removeClass('error');}
if ($('#edit-tf-prenom2').val() == '' ) { $('#edit-tf-prenom2').addClass('error'); } else { $('#edit-tf-prenom2').removeClass('error');}
if ($('#edit-tf-nom2').val() == '' ) { $('#edit-tf-nom2').addClass('error'); } else { $('#edit-tf-nom2').removeClass('error');}
if ($('#edit-tf-adresse2').val() == '' ) { $('#edit-tf-adresse2').addClass('error'); } else { $('#edit-tf-adresse2').removeClass('error');}
if ($('#edit-tf-code-postal2').val() == '' ) { $('#edit-tf-code-postal2').addClass('error'); } else { $('#edit-tf-code-postal2').removeClass('error');}
if ($('#edit-tf-ville2').val() == '' ) { $('#edit-tf-ville2').addClass('error'); } else { $('#edit-tf-ville2').removeClass('error');}
if ($('#edit-tf-pays2').val() == '' ) { $('#edit-tf-pays2').addClass('error'); } else { $('#edit-tf-pays2').removeClass('error');}
if ($('#edit-tf-email2').val() == '' ) { $('#edit-tf-email2').addClass('error'); } else { $('#edit-tf-email2').removeClass('error');}
if ($('#edit-tf-telephone2').val() == '' ) { $('#edit-tf-telephone2').addClass('error'); } else { $('#edit-tf-telephone2').removeClass('error');}
if (!$.cookie('livraison')) {
$('.livraison-error-messages').html('<p class="error medmarginsides">Sélectionnez un mode de livraison');
e.preventDefault();
} else if ( ($('#edit-tf-prenom').val() == '') || ($('#edit-tf-nom').val() == '') || ($('#edit-tf-adresse').val() == '') || ($('#edit-tf-code-postal').val() == '') || ($('#edit-tf-ville').val() == '') || ($('#edit-tf-pays').val() == '') || ($('#edit-tf-email').val() == '') || ($('#edit-tf-telephone').val() == '') ) {
$('.facturation-error-messages').html('<p class="error medmarginsides">Les champs encadrés en rouge sont obligatoires');
e.preventDefault();
} else if ($.cookie('expediera')) {
if ( ($('#edit-tf-prenom2').val() == '') || ($('#edit-tf-nom2').val() == '') || ($('#edit-tf-adresse2').val() == '') || ($('#edit-tf-code-postal2').val() == '') || ($('#edit-tf-ville2').val() == '') || ($('#edit-tf-pays2').val() == '') || ($('#edit-tf-email2').val() == '') || ($('#edit-tf-telephone2').val() == '') ) {
$('.expediera-error-messages').html('<p class="error medmarginsides">Les champs encadrés en rouge sont obligatoires expediera');
e.preventDefault();
}
} else if (!$.cookie('conditions')) {
$('.conditions-error-messages').html('<p class="error medmarginsides">SVP, vérifiez que vous avez lu et approuver les conditions générales');
e.preventDefault();
} else {
deleteError('.facturation-error-messages');
deleteError('.expediera-error-messages');
// Reset cookies and return to start of order
$.cookie('reset', 'yes');
// Save address to cookie
address_array = [];
if ($.cookie('expediera')) {
adresse = $('#edit-tf-adresse2').val();
appartement = $('#edit-tf-appartement-suite2').val();
code_postal = $('#edit-tf-code-postal2').val();
ville = $('#edit-tf-ville2').val();
canton = $('#edit-tf-canton-province2').val();
pays = $('#edit-tf-pays2').val();
telephone = $('#edit-tf-telephone2').val();
instructions = $('#edit-instructions').val();
address_array.push({adresse: adresse, appartement: appartement, code_postal: code_postal, ville: ville, canton: canton, pays: pays, telephone: telephone, instructions: instructions});
address_json = JSON.stringify(address_array);
$.cookie('address', address_json);
} else {
adresse = $('#edit-tf-adresse').val();
appartement = $('#edit-tf-appartement-suite').val();
code_postal = $('#edit-tf-code-postal').val();
ville = $('#edit-tf-ville').val();
canton = $('#edit-tf-canton-province').val();
pays = $('#edit-tf-pays').val();
telephone = $('#edit-tf-telephone').val();
email = $('#edit-tf-email').val();
instructions = $('#edit-instructions').val();
address_array.push({adresse: adresse, appartement: appartement, code_postal: code_postal, ville: ville, canton: canton, pays: pays, telephone: telephone, email: email, instructions: instructions});
address_json = JSON.stringify(address_array);
$.cookie('address', address_json);
cartToLog();
}
}
});
});
}
}
NB: I have changed the URL in the script snippet to http://example.com/
The log file that is generated is as follows:
January 2, 2015, 6:11 pm
[{"adresse":"49 some street","appartement":"","code_postal":"1227","ville":"Carouge","pays":"Suisse","telephone":"079 123 45 67","email":"user#example.com","instructions":""}]
[{"order":"Pack XS","price":"99.00 CHF","cat":"Cat1"},{"order":"1 CD/DVD","price":"10.00 CHF","cat":"Cat5"},{"order":"1 Lot","price":"2.00 CHF","cat":"Cat6"},{"order":"Postpac","price":"0.00 CHF","cat":"Cat7"}]January 2, 2015, 6:11 pm
[{"adresse":"49 some street","appartement":"","code_postal":"1227","ville":"Carouge","pays":"Suisse","telephone":"079 123 45 67","email":"user#example.com","instructions":""}]
[{"order":"Pack XS","price":"99.00 CHF","cat":"Cat1"},{"order":"1 CD/DVD","price":"10.00 CHF","cat":"Cat5"},{"order":"1 Lot","price":"2.00 CHF","cat":"Cat6"},{"order":"Postpac","price":"0.00 CHF","cat":"Cat7"}]
I don't understand why the problem is. I see no reason why it shouldn't work on other browsers. I don't see any console errors.
Additionally, as you can see above, for some reason, when the log is appended to the file (so using Chrome) it appends the data twice. This is of minor consequence, but it would be nice to sanitise the file to only log an order detail once per order.
Any advice would be most appreciated.
I have used location.href in my earlier days but now its not redirecting to page. here is my code
function AuthenticateUserWithPage() {
var UId = $('#amwayId').val();//username
var UPw = $('#amwayPw').val();//password
var ischecked = $('#idSave').is(':checked');// check remember me checkbox status
if (UId != '' && UPw != '') {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../KPPRMobService/PNBMobWebService.asmx/IsValidUserWithPage",
data: JSON.stringify({ username: UId, password: UPw, ischecked: ischecked }),
async: false,
success: function (data) {
var obj = data.d;
if (obj != "FALSE") {
var targetUrl = "http://" + window.location.host + obj;
window.location.href = targetUrl;
//window.location.replace(targetUrl);
return false;
}
else {
$('#amwayId').val('');
//if username or password is invalid
alert("Please check your ID or password. The ID is not registered or the ID/ password is wrong.");
}
},
error: function (result) {
//if error occured.
$('#amwayId').val('');
alert("You cannot log in. Contact support center for further inquiries..");
}
});
}
else {
//if username or password is null
alert("Please enter ID/ password.");
return false;
}
}
I use this link as reference: reference.Thanks in Advance.
Php:
$form_data = array();
$form_data['message'] = "success";
$form_data['redirect'] = "http://www.example.com/example";
echo json_encode($form_data)
Ajax:
if (data.message == 'success') {
window.location.href = data.redirect;
return false;
}else if(){
etc...
}
I have been struggle with this now for two days and I do not know where the problem is.
When I leave the textbox the Ajax call is correct and the result are returned as a true or false and the success: function is executing.
The problem is that the image and error text is not displaying next to the textbox. If I type in more than 50 characters in the textbox the "Must be under 50 characters" message is showing but it I type in a user name that already exist the message is not showing.
What am I missing? Any suggestions?
I use a DevExpress Text Box
Html.DevExpress().Label(
edtSettings =>
{
edtSettings.ControlStyle.CssClass = "label";
edtSettings.Text = "User Name:";
edtSettings.AssociatedControlName = "UserName";
}
)
.Render();
Html.DevExpress().TextBox(
edtSettings =>
{
edtSettings.Name = "UserName";
edtSettings.ControlStyle.CssClass = "editor";
edtSettings.ShowModelErrors = true;
edtSettings.Width = 100;
edtSettings.Properties.ValidationSettings.Assign(IserValidationHelper.UserNameValidationSettings);
edtSettings.Properties.ClientSideEvents.Validation = "OnNameValidation";
edtSettings.ControlStyle.BackColor = System.Drawing.Color.LightYellow;
}
)
.Bind(DataBinder.Eval(IserUser, "UserName"))
.Render();
I have the following JavaScript.
<script type="text/javascript">
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/Admin/CheckUsername',
dataType: 'json',
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 50) {
e.isValid = false;
e.errorText = "Must be under 50 characters";
}
}
I have the following method in my controller.
[HttpPost]
public ActionResult CheckUsername(string userName)
{
bool status = WebSecurity.UserExists(userName);
return Json(new { result = status });
}
The problem was with my $.ajax call. I had to include the setting async (async:false,) as the default async is true. It is working now correctly.
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/ISERAdmin/CheckUsername',
dataType: 'json',
async:false,
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 56) {
e.isValid = false;
e.errorText = "Must be under 56 characters";
}
}