Displaying PHP success and fail messages with Ajax - javascript

What went wrong in this code? I ready many post here on this issue but can't fix my error. I have the following.
HTML Code
<div id="successMessage" style="display:none;"> It worked </div>
<div id="failMessage" style="display:none;"> It failed </div>
<div container>
<div class="modal">
<form>
....
</form>
</div>
</div>
PHP Code
if(!$stmnt->execute()){
echo "Failed!";
}else{
echo "Inserted";
}
AJAX Code
success: function(data){
viewData();
if (data=="Failed!") {
console.log(data);
$("#failMessage").show();
} else if(data=="Inserted"){
console.log(data);
$("#successMessage").show();
}
}
Problem: I would like to display the error in the page not in console. I want to inform the user. Why is it not working with $("#successMessage").show();?
PS: I am using Bootstrap. Also how can I show my messages using one(1) div="msg" tag?

Found a mistake in your code
PHP Code
if(!$stmnt->execute()){
echo "Failed!"; // Check the exclamation mark
}else{
echo "Inserted";
}
AJAX Code
success: function(data){
viewData();
$('#addData').modal('hide');//close the modal.
if (data=="Failed!") { // Add an exclamation mark to correct code
$("#failMessage").show();
//console.log(data); is showing message from PHP
} else if (data=="Inserted") { // Change this else to else if
$("#successMessage").show();
//console.log(data); is showing message from PHP
}
Change "Failed" in ajax to "Failed!". Also, change the else to correct format of else if

Related

Json response not displaying a success message in the view (Laravel)

I'm trying to return the following message via Json as shown below. The $message is showing in the Response, but not sure how to display it in the view. I tried the below attempt, but failed.
Also If I don't use location.reload(); , the edit done will not show without reloading the page. So how can I do this properly?
Controller :
$message = "Successfully edited!";
return response()->json(['new_body' => $greq->title, 'message' => $message], 200);
JS :
.done(function () {
// location.reload();
$('#message').text(msg['message']);
$('#edit-greq').modal('hide');
});
View :
#if(Session::has('message'))
<div class="alert alert-success" align="center" id="message">
<strong>{{Session::get('message')}}</strong>
</div>
#endif
JS
.done(function (msg) { // You need to add return variable
$('#message').text(msg['message']); // In order to make it show you need to have this HTML element
$('#edit-greq').modal('hide');
});
View
<div class="alert alert-success" align="center" id="message">
#if(Session::has('message'))
<strong>{{Session::get('message')}}</strong>
#endif
</div>

Trying to send js variables to a php file

I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.

Why this ajax call is not working?

$(document).ready(function(){
$('.clickthetext').click(function(){
$.post("submit.php", $("#formbox").serialize(), function(response) {
$('#content').html(response);
});
return false;
});
});
My target to pass content from the form and edit the data and show response at current page.
.clickthetext button content:
<div class="clickthetext">Click here to see the result</div>
content inside id #formbox:
Part of the form inside this id. rest of the form is out side this id will be processed later. only content/input inside of id "formbox" will be processed.
Whatever response we will get, we will show inside of "#content" id.
What i am doing wrong here?
----edit----
i didn't add anything on submit.php
only to show response, i wrote there:
<?php
echo 'somthing blah blah blah something';
?>
Maybe there is a problem with the result of submit.php
You can try calling
$(document).ready(function(){
$('.clickthetext').click(function(){
$.ajax({
type: "POST",
url: "submit.php",
data: $("#formbox").serialize(),
success: function(response) { $('#content').html(response); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); },
dataType: dataType
});
return false;
});
});
instead and get more detail of the result of the ajax call.
Here's the API for the ajax object in jQuery
Recreating your set up,
JS/HTML
<form action="" id="formbox">
<input type="text" name="firstName" value="First Name">
</form>
<button class="clickthetext">Button</button>
<div id="content"></div>
<script>
jQuery(document).ready(function ($) {
$('.clickthetext').click(function() {
$.post("submit.php", $("#formbox").serialize(), function (response) {
$('#content').html(response);
})
})
});
</script>
PHP: submit.php
<?php echo 'this is the response'; ?>
Everything works perfectly.
Debugging tips:
1) Most likely - Check your javascript console for any errors. You probably have errors elsewhere in the page.
2) Ensure you're accessing the HTML page with the javascript via localhost, not a filepath
3) Unlikely, but check your PHP log.

Ajax, add to database and update div content

Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.
Here is the relevant ajax-code:
$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
var message = $("#message").val();
//assumming validate_post returns true of false(y)
if(!validatepost(message)){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post(message);
});
});
function update_post(message){
var dataString = "message=" + message;
alert(dataString);
$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});
}
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
function validatepost(text){
$(document).ready(function(){
var y = $.trim(text);
if (y==null || y=="") {
alert("String is empty");
return false;
} else {
return true;
}
});
}
Here is the post_process.php:
<?php
// Contains sessionStart and the db-connection
require_once "include/bootstrap.php";
$message = $con->real_escape_string($_POST["message"]);
if (validateEmpty($message)){
send();
}
function send(){
global $con, $message;
$con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}
//header("Location: index.php");
?>
And lastly, here is the html-form:
<div id="post_div">
<form name="threadForm" method="POST" action="">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
create_post is a function I've written, it and everything else worked fine until I introduced ajax.
As it is now, none of the console.log:S are getting reached.
Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.
I apologize for forgetting some info. I am tired and just want this to work.
I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}
If it's not successful then the problem is in the php.
You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.
First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
//assumming validate_post returns true of false(y)
if(!validate_post()){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post();
});
Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.
Your function posts could use jQuery as well as it makes the code shorter:
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
UPDATE
Can you console log if the form is found when you attach the event listener to it?
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
....
Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.
Looking at your code it seems you got the post ajax request wrong.
function update_post(message){
console.log(message);
$.ajax({
url: 'post_process.php',
async: true,
//data could be a string but I guess it has to
// be a valid POST or GET string (escape message)
// easier to just let jQuery handle this one
data: {message:message} ,
type: 'post',
success: function() {
posts();
}
});
UPDATE
Something is wrong with your binding to the submit event. Here is an example how it can be done:
<!DOCTYPE html>
<html>
<head>
<script src="the jquery library"></script>
</head>
<body>
<form name="threadForm" method="POST" action="http://www.google.com">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
<script>
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
console.log("message is:",$("#message").val());
});
</script>
</body>
</html>
Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.

Can Ajax update a dynamic navigation menu?

I'm using a PHP function to determine what links are being displayed:
<?php
//amend toplinks if logged in
if($general->loggedIn()){ ?>
<nav class = "memberHeaderArea">
<ul>
<li>
Profile<span class="user icon"></span>
</li>
<li>
Log out<span class="lock icon"> </span>
</li>
</ul>
</nav>
<?php
//toplinks for when not logged in
}else{ ?>
I've just changed the structure of my login to use Ajax and it works perfectly with the exception of the nav. It still shows login / register until a page refresh is called. Obviously the reason for using Ajax was to avoid the page refresh, but is there a way I can update these links within the success function?
success: function(data) {
$("#statusLogin").hide();
if(data.success == true){
$('#loginContent').slideToggle();
}else{
// alert("data.message... " + data.message);//undefined
$("#error").show().html(data.message);
}
From what I've found, it looks like I may need to assign the nav's id and then use Ajax / jQuery to target that. But I'm not sure how. Any help greatly appreciated.
This is a basic (and dummy) stuff for checking login status with AJAX after page loading. Probably you want more serious check then if(true) and an echo call, but it will be something like this :) Check the fiddle below, so you can see the html and the css too...
$.getJSON('/echo/json/').done(function (data) {
console.log("Call returned");
if (true){
//successful login
$('#loggedin').slideToggle();
}else {
//unsuccessful login
$('#login').slideToggle();
}
}).fail(function (data) {
console.log("Call failed");
$('#login,#error').slideToggle();
}).always(function (data) {
console.log("Always running");
});
JSFiddle

Categories