Staged and Nested Ajax calls producing the error - "listener-indicated-an-asynchronous-response-by-returning-true.." - javascript

I have a number of Ajax calls that are both staged and nested. The code below works but I am getting the error "A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received", What does that mean? however I am not sure how that answer applies to my code, hence the question.
I suspect the error is being caused by the way I am I am using the Ajax calls and would appreciate any insight as to what is the likely cause is.
Thanks
`<!-- This name of this module is downloadFiles.php - it downloads files from FolderID -->
<!-- FolderID is submitted by the user from the downloadFilesModalBody submit btn-->
<script>
$form.submit(function () {
var pattern = "someStringToMatch" //valid type of folderID?
var formId = this.id;
if (formId == "folderID") { //Was this data submitted from the submit folderID form?
//The name of the folder is serialized and this ajax.post calls this php module
$.post($(this).attr('action'), $(this).serialize(), function (response) {
if (response.match(pattern) == null) {
$("#failure").show();
return false;
}
/*
* Folder is valid so call recursively call "Download Files Routine" using Ajax
*/
$.post("/downloadFiles.php", response, function (response) {
}, 'json');
/*
* Here we take the results from the Ajax call process the result
*/
$.post("/resources/extractData.php", response, function (response) {
$.post("/resources/processData.php", response, function (response) {
$.post("/resources/updateDatabases.php", response, function (response) {
}, 'json');
}, 'json');
$("#success").show();
}, 'json');
}, 'json');
return false; //ends the process
}
});
</script>
<body>
<?php
// Start a session to get the folderID from the AJAX call above..
session_start();
if (isset($_SESSION['folderID'])) {
$folder_name = $_SESSION['folderID'];
|
"Download Folders Routine"
|
}
exit(); //don't return anything
?>
<!-- This is the modal that has the form submit button and UI-->
<?php include 'modal-bodies/downloadFilesModalBody.html'; ?>
</body>`

Related

Update a DIV tag from PHP

I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});

how can I trigger javascript css action?

I have a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Ajax request to check username

I am creating a signup form in HTML/CSS/JS which uses an AJAX request to get response from server. In my jQuery, I use a method to validate form contents which also calls a function (containing ajax) to see if the username exists or not. I have checked the similar questions but couldn't relate to my problem.
The AJAX goes inside a function like this
function checkIfUserNameAlreadyExists(username)
{
// false means ok, i.e. no similar uname exists
$.ajax
({
url : 'validateUsername.php',
type : 'POST',
data : {username:username},
success : function(data,status)
{
return data;
}
});
}
The PHP code looks like this
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$enteredLoop=false;
$linkobj = new mysqli('localhost','root','','alumni');
$query = "select username from user where username='".$uname."'";
$stmt = $linkobj->prepare($query);
$stmt->execute();
$stmt->bind_result($uname);
while($stmt->fetch())
$enteredLoop=true;
if($enteredLoop)
{
echo "
<script type='text/javascript'>
$('.unamestar').html('Sorry username already exists');
$('.userName').css('background-color','rgb(246, 71, 71)');
$('html,body').animate({
scrollTop: $('.userName').offset().top},
'slow');
</script>";
return;
}
}
?>
The function checkIfUserNameAlreadyExists returns false by default (don't know how) or this ajax request is not submitted, and it submits the form details to php.
Any help ?
Your checkIfUserNameAlreadyExists() function is synchronous and your ajax call is asynchronous. That means that your function will return a value (actually no value is returned at all in your case...) before the ajax call is finished.
The easiest way to solve this, is to generate the html in the success function, based on the return value of the data variable.
Something like:
success : function(data,status) {
if (data === 'some_error') {
// display your error message, set classes, etc.
} else {
// do something else?
}
}
Apart from that, are you actually setting the value of $uname to $_POST['username']?
You need to append response script to the document for executing.
function checkIfUserNameAlreadyExists(username)
{
// false means ok, i.e. no similar uname exists
$.ajax
({
url : 'validateUsername.php',
type : 'POST',
data : {username:username},
success : function(response)
{
$('body').append(response);
}
});
}

jQuery ajax returns error but data being added to database

I'm currently trying to store data into a database via ajax.
This works fine but the ajax always returns "error" even if the php code has been executing fine.
Javascript
jQuery.ajax({
type:'POST',
url:ajaxurl,
data: { game:game, variation:variation, player:player, win:win },
success: function(data){
alert('success');
},
error: function(data) {
alert('error');
}
});
PHP
<?php
include('connectdb.php');
function addNewMatch() {
$game = $_POST['game'];
$variation = $_POST['variation'];
$date = time();
$player = $_POST['player'];
$win = $_POST['win'];
$queryMatch = "INSERT INTO pd_match VALUES (
NULL,
'".$game."',
'".$variation."',
'".$date."',
'".$player."',
'".$win."'
)";
$doQueryMatch = mysql_query($queryMatch);
if (!$doQueryMatch) { return (false); } else { echo 'success'; }
} // end function addNewMatch
addNewMatch();
?>
As I said, it works fine but ajax is returning the alert("error").
I must be missing somthing.
(It's done locally on localhost)
try this
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
and let us know what error you are getting.
If you are using ajax you shouldn't use
<form method="POST" action="phpfile.php">
And if you are wrapping the Ajax function inside a .on('click') or .click event your buttun should be button type button instead of button type submit, like this:
<button type="button"></button>
I havn't seen your HTML but usually when I have a problem like this it's because of that.
I hope it helps.

Categories