JSON is null but data passes to success in ajax - javascript

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.

Related

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Check if alert box was shown in PHP using AJAX

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...
}
}
});

Pass PHP variable to JavaScript with Callback

I want to validate a password via JavaScript with help of an Ajax function.
If it is successful, I want to pass back the variable (boolean, true or false) and do something in my PHP file depending on the callback.
But this doesn't work. Here is my code:
PHP file: update.php
<input href="javascript:void(0);" role="button" ype="submit" value="Submit" onclick="ValidatePassword()>'
JAVASCRIPT: ValidatePassword()
In my Javascript function I check the password with this ajax call and if it is successfull, it should callback the result to the php function.
$.ajax({
type: "POST",
url: "checkpw.php",
data: dataString,
cache: false,
success: function(response)
{
if (result != -1 )
{
$("#passwd").val('');
// RETURN TO PHP FILE update.php -> PW IS VALID
} else {
// RETURN TO PHP FILE update.php -> PW IS INVALID
}
}
});
PHP file: update.php
Now I want to use the callback in the php function like:
<?php
if (passwordCallback == true)
...
else
...
?>
What should I do in the ajax success function to return the value to my php file?
As I suggested in the comments, if this is not coded correctly it can lead to security issues. If it is coded correctly then it will end up doing the password check twice when it only needs to be done once.
Instead what you could do is:
$.ajax({
type: "POST",
url: "checkandupdate.php", //Combination of both
data: dataString,
cache: false,
success: function(response)
{
if (result != -1 ) {
$("#passwd").val('');
}
}
});
File checkandupdate.php
<?php
require "checkpw.php"; // Or whatever you need to do to validate the password
// At this point "checkpw.php" determined if the password is valid and(ideally) you can check the outcome
//Assume we store the outcome of the check in $passwordIsValid as a boolean indicating success
if ($passwordIsValid) {
//Do whatever you need to do when the password is valid
echo "1"
}
else {
// Do whatever you need to do when the password is invalid
echo "-1";
}
?>
You need to write a JavaScript function like:
function sendReturnToPHP(url, result) {
$.ajax({
type: "POST",
url: url,
data: JSON.parse(result),
cache: false,
success: function(response) {}
});
}
Now you can easily call it in your request success.

How to Enable Submit Button After API Call and Within if Statement

I am disabling the submit button #myButton after i execute an api call doAjax();
$("#myButton").click(function (e) {
doAjax();
$('input:submit').attr("disabled", true);
});
But it wont enable after the callback .. i want to enable it if the call back meets a certain criteria i.e.
$.ajax({
type: "GET",
url: "api5.php",
data: dataString,
dataType: "json",
//if received a response from the server
success: function (response) {
var status = response.status;
enter code here
if ((status == 'READY' && response.endpoints[0].statusMessage == 'Ready')) {
$('input:submit').attr("disabled", false);
doesn't seem to work though.. button stays disabled.
Are you sue the your if block is getting executed ? Try doing console.log or alert inside the if block. Also, try the following :
$('input:submit').removeAttr('disabled');
or you can also try input[type=submit] as the selector or give a class or id and make it selector.
the code works for me, only comment this line enter code here
$.ajax({
type: "GET",
url: "api5.php",
data: dataString,
dataType: "json",
//if received a response from the server
success: function (response) {
var status = response.status;
//enter code here
if ((status == 'READY' && response.endpoints[0].statusMessage == 'Ready')) {
$('input:submit').attr("disabled", false);
Try : $(el).prop('disabled', false)

On PHP script end send message to jquery, print to page with jquery

I have a page with buttons, that when pressed send an ajax request through jquery to a PHP script. This script runs with these variables. When this PHP script is finished I would like to send a message back to the jquery function, which then prints out this message. Currently I have:
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
request = $.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
});
request.done(function (response, textStatus, jqXHR) {
buttonz.text('Finished');
});
});
Instead of 'finished' I would like to echo a varaible from my php script.
First need to check console error if you have any error then try to alert response in success section try
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
$.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
success: function (data) {
buttonz.text(data);
// or use buttonz.val(data);
}
});
});
You cannot ECHO from jQuery as this is PHP and the server-side script has already been run. What you need to do is enter the text or html into an existing element.
For example..
On your page (before ajax is done) create a blank DIV with space to put the response ie...
<div id="MyAnswerHere"></div>
Then in your ajax call in the success area add the code to insert the answer. For example
$("#MyAnswerHere").html(response);
Or if just text you could use...
$("#MyAnswerHere").text(response);
So in your code..
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
request = $.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
});
request.done(function (response, textStatus, jqXHR) {
$("#MyAnswerHere").text(response);
buttonz.text('Finished');
});
});
And add the div to enter the message do with the ID that we are selecting in the DOM before hand.
`<div id="MyAnswerHere"></div>`
simply put the response from ajax in your button,
buttonz.text(response);
cheers
You could try something like this, which will change your button text when the ajax has succeeded:
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
request = $.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
success: function (data) {
buttonz.text(data);
}
});
});
Change buttonz.text('Finished'); to:
buttonz.text('<?php echo json_encode(utf8_encode($your_Value))?>');
So why not just to echo the variable with php??
Change buttonz.text('Finished'); to:
buttonz.text('<?php echo $your_variable;?>');
The value of the variable will be parsed by the PHP engine, it will appear in your HTML page as requested

Categories

Resources