How to access string from PHP to jQuery using AJAX - javascript

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.

Related

rerturning response of an ajax post

i am trying to check if an email exists in the db but the function doesn't return a value.
This is the code:
function checkemail(email)
{
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1)
{
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
}
else
{
returnVal = 3;
}//email
return returnVal;
}
EDIT: email is send as a string
I short, You can not return values from ajax calls as it is asynchronous by nature, the statement return value executes before
To address such cases, use callback, a function accepted as argument and which is executed when response is been received (when asynchronous action is completed).
Try this:
function checkemail(email, callback) {
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1) {
$.post("registreren.php?email=" + email, function(response) {
callback(response);
});
} else {
callback(3);
}
}
checkemail('abc#xyz.com', function(val) {
alert(val);
});
checkemail('INVALID_EMAIL', function(val) {
alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Can you use something simple like below
$.ajax({
url: 'registreren.php',
type: 'post',
dataType: "json",
data: {'email': email},
success: function (response) {
if (response == 1)
{
returnVal = 1;
}
else
{
returnVal = 3;
}
}
});
instead of
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});

PHP/JS log of order details to text file only works in chrome, not other browsers

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.

Validation error not displaying with AJAX

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";
}
}

check on return value from jquery fails

I use jquery to validate the form, check the math-captcha and finally, send a mail.
The validation works fine and the mail works fine. There is only one problem. When my ajax returns false, the bool validCaptcha keeps always true...
$(document).ready(function() {
$("#confirm").on("click", function(e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function() {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function() {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function() {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
validCaptcha = false;
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
}
}
});
//Send email
if (validName == true && validEmail == true && validMessage == true && validCaptcha == true) {
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
}
else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
} else {
reloadCaptcha();
$("#inputcaptcha").val("");
}
});
});
In Firebug I see I get a 'false' back from checkCaptcha.php when e.g. I left the field blank of entered a wrong code.
checkCaptcha.php
session_start();
if ( !empty($_POST['inputcaptcha']) ) {
if ( $_POST['inputcaptcha'] == $_SESSION['security_number'] ) {
echo 'true';
}
else {
echo 'false';
}
}
else {
echo 'false';
}
To check I first checked the result-value from the captcha-ajax
alert(result)
//returned false as it should when leaving blank or entering wrong value
Then before calling the mail-ajax I called all bools
alert('validName='+validName+' & validEmail='+validEmail+' & validMessage='+validMessage+' & validCaptcha='+validCaptcha);
//validCaptcha was true, even when result was false...
What do I not see??
Simply put you can't do that since the validate captcha is an asynchronous request,
Instead you can move the email code to the validate captcha success handler like
$(document).ready(function () {
$("#confirm").on("click", function (e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function () {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function () {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function () {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
if (validName == true && validEmail == true && validMessage == true) {
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
reloadCaptcha();
$("#inputcaptcha").val("");
} else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
}
}
});
}
});
});

cross browsing problem in ajax call

When i execute it in firefox mozila than this code is working well (in case of register user) but when we try it in IE (iternet explorer 8) then alert("sorry u must have to login first"); this message is comming. ( in both cases as register or gest).
Another thing: for gest user returning data from server is null. means d = null,
Another thing when execute in firefox mozila as a gest user then nothing happen means alert("sorry u must have to login first"); this message is not comming.
What should i do?
function manageVoting() {
var parameter;
var myVoting;
var divVoting;
var divVotes;
var value = -1;
var parameterData;
$('div.votemaincontainer').each(function() {
parameter = $(this).find('#[id$= hfUrl]').val();
myVoting = parseInt($(this).find('#[id$=hfMyVote]').val());
divVoting = $(this).find('[id$=divVoting]');
divVotes = $(this).find('[id$=divVotes]');
function processVote(value) {
if (value == 0 || value == 1) {
parameterData = parameter + value + "'}";
$.ajax({
type: 'POST',
url: 'UserControls/Vote/VoteAction.aspx/Voting',
data: parameterData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
var result = eval(data.d);
if (result) {
if (result.length > 1) {
if (result[1] == 1 && result[2] == 1) {
$('img.voteupImage').attr('src', 'UserControls/Vote/Images/aftervote_arrow_up.png');
$('img.votedownImage').attr('src', 'UserControls/Vote/Images/arrow_down.png');
$('div.divVotes').html(result[0]);
$(myVoting).val(value);
}
else if (result[1] == 0 && result[2] == 1) {
$('img.voteupImage').attr('src', 'UserControls/Vote/Images/Arrow Up.png');
$('img.votedownImage').attr('src', 'UserControls/Vote/Images/aftervote_down.png');
$('div.divVotes').html(result[0]);
$(myVoting).val(value);
}
else if (result[2] < 0 && value == 0) {
alert('U HAVE ALL READY VOTED DOWN');
}
else {
alert('U HAVE ALL READY VOTED UP');
}
$('#[id$=hfMyVote]').html(result[1]);
}
else {
alert('I AM ENSIDE ELSE');
//$('div.divVotes').html(result[0] - 1);
alertDialog("Rating any knowledge item is only available for Registered User.<br>Do you want to <a class='signUpPopUp' href='signup.aspx'> signup</a> Now?");
}
}
},
error: function() {
alert("sorry u must have to login first");
}
});
}
}
$('img.voteupImage').live('click', function() {
value = 1;
processVote(value);
});
$('img.votedownImage').live('click', function() {
value = 0;
processVote(value);
});
});
}
$(function() {
manageVoting();
});
For the ajax call to be successful or not does not depend on the user being authenticated. The http server should return a 403 code if the user is not authenticated and 200 if everything is ok.
success(data, textStatus, XMLHttpRequest){
if (XMLHttpRequest.status == 403){
alert("sorry u must have to login first");
return;
}
}

Categories