Check if alert box was shown in PHP using AJAX - javascript

I am sending data to a PHP file using AJAX and depending on what data is sent, an alert() is either shown or not shown.
Inside the success function in AJAX, how do I detect if an alert box was shown?
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if(alert box was shown) {
// something happens
}else{
// alert box wasn't shown, something else happens.
}
}
});
send.php:
<?php
if($_POST['name'] == 'john') {
echo'
<script>
alert("Correct name");
</script>
';
}

It would be better to send back a result form the ajax request and show/don't show the alert in the success callback:
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if ( data == "show" ) {
// something happens
alert("Correct name");
} else {
// alert box wasn't shown, something else happens.
}
}
});
And on your server:
if ( $_POST['name'] == 'john' ) {
echo "show";
}

You could use json_encode() php function to return data from php.
This will be a better approach :
PHP :
if (!isset($_POST['name'] || empty($_POST['name']) {
die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
die(json_encode(array('return' => true)));
} else {
die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}
At this point, you will be allowed to check the returned values from JS and decide if you need to display the success alert or send an error message to the console (or do what ever you want...).
JS :
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
dataType: "JSON", // set the type of returned data to json
data: {name: called}, // use more readable syntaxe
success: function(data) {
if (data.return) { // access the json data object
alert("Congrats ! Your name is John !");
} else {
console.log("Sorry, something went wrong : " + data.error);
}
}
});
So, json_encode() allows to return easy accessible object from JS and will also allows you to set and display error messages easily in case the return is false.
Hope it helps !

PHP does not know if an alert has been shown, because in javascript the alert() function has no return value and no events which you could use to send an ajax request a click confirmation to the server.
One solution is to use a confirm() command inside the success event of your $.ajax(), which sends anothe ajax request if the user clicked "ok" or "cancel".
Something like this
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,
success: function(data) {
if (data == "show") {
var clicked = confirm("Correct name");
if (clicked == true || clicked == false) {
$.ajax({
url: "send.php?clicked=1",
});
}
}
else {
// Whatever to do than...
}
}
});

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

JSON is null but data passes to success in ajax

I'm running into a problem in ajax. the scenario is: I would like to verify if the user is available or not when typing his email. So I create a function in javascript to do this with an Ajax script within it.
here my code :
$('#username').keyup(function () {
var email = $(this).val();
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
});
});
my problem is : when I type any words it calls the function of keyup then it passes into success even if the data is null. I would like to let it pass to the success only if the data is correctly done.
thank you.
Try Following..Hope it works as you want...
$('#username').keyup(function () {
var email = $(this).val();
if(email != "") {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
// Check response data...
if(data == 'true') {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
}
});
}
});
Try some error checking before doing anything. Therefore, the success callback will be invoked (you cannot stop it conditionally), but the code inside will be prevented.
Encapsulate everything in the success event handler with the following so that it only executes if data is not null (empty string):
if(data != "") {
// action here
}
I'm not sure what you mean when you say that "the data is null", so a simple empty-string conditional as shown above may not be sufficient to check whether or not the data is null. This will simply check if the data parameter is empty.

jQuery AJAX response always returns blank message

Hi I'am trying to make HTML form, and need to validate it before executing the form action. But the AJAX respond always returns a blank message?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log(msg);
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});
PHP:
$post = (!empty($_POST)) ? true : false;
if ($post) {
$orderid = stripslashes($_POST['orderid']);
$amount = stripslashes($_POST['amount']);
$betingelser = stripslashes($_POST['betingelser']);
$error = ''; // Check ordreid
if (!$orderid) {
$error. = 'Venligst indtast dit ordreid.<br />';
} // Check amount
if (!$amount) {
$error. = 'Venligst indtast et beløb.<br />';
}
if (!$error) {
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.
'</div>';
}
}
Can anyone tell me what wrong?
You're in the click handler of a submit button. You're calling $(this).serialize(), where this is that submit button. Calling serialize on the submit button is going to return an empty string.
So, you're not passing any data to the server. The first thing you do server-side is check empty($_POST), which it will be, so if ($post) is false, and none of your server-side code is eve executed.
You need to serialize the form, not the submit button.
A simple solution would be to serialize the form itself....
str = $('"#ajax-payment-form').serialize()
but really, the larger problem is that you're binding to the click of the submit button, instead of to the submit event on the form itself.
Instead of this rather convoluted way of handling form submits...
$("#ajax-payment-form input[type='submit']").click(function(e) {
Just do this:
$("#ajax-payment-form").submit(function (e) {
try this in jquery:
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this,
success: function(msg){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
}
else {
console.log(msg);
}
}
error: function(msg){
// if call fails or any error occurs
}
});

jquery ajax json doesnt return true

i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}
You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");
you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.

Javascript Logic Fail?

I'm really confused on this one. I'm trying to do a simple ajax request, and I have php executing 'echo "true";' if the ajax request is successful, or return a string containing the error if it isn't. I'm using this exact technique elsewhere in the code and it compares as expected (msg != "true") { //do something }. The first function I'll post below works with that method, the second doesn't (also I am checking with Firebug the response is "true", and I've done console.log(typeof msg) to verify it is of type string).
This works as expected (the php echoes "true", and it executes show_step2()):
function step2_register() {
var values = $('.signup .txt').serialize();
$.ajax({
type: "POST",
url: base_url+"login/create_account",
data: values,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup .error_container #error1").html(msg).css("visibility", "visible");
}
else {
show_step2();
}
},
error: function(error) {
alert(error);
}
});
}
This doesn't work (the php echoes "true", but the js always executes the slideDown() part of the code):
function register() {
var data = $("#login_form .input").serialize();
$.ajax({
type: "POST",
url: base_url+"login/register",
data: data,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup #error2").html(msg).slideDown();
}
else {
show_success();
}
},
error: function(error) {
alert(error);
}
});
}
What's going on here?
Your php is likely outputting something else invisible like a newline character after the word "true". Either make sure you call die(); or exit(); right after outputting "true", (and doing everything else you need), or make sure there are no line breaks in your PHP editor before the <?php and after the ?>.
You can also check that the string begins with "true" instead of equals "true" by trying something like msg.substring(0,4) == "true"

Categories

Resources