Location: Header not working for one particular trigger - javascript

Okay, so, I have a PHP and JS-based webapp that does mostly what it's supposed to do. This being said, before I show any code, bear in mind a few things.
1.)The top two location headers inside the 'if' loops work as intended.
2.)In the development tools in Chrome, the location is in the header for this request.
PasteBin to my code here.
In my JQuery (defined in html head), we see a button name "subAll2", which is supposed to post the intended data, and do a redirect using aforementioned JQuery. The other two redirects work via intended forms. Why does this one not work?
$('#subAll2').click(function() {
var action = $('#frmUser').attr('action');
$.ajax({
url : action,
type : 'POST',
data : $('#frmUser,
#frmUser2').serialize()+"&butSubmitAll=submitAll",
success : function() {
window.location.replace(action);
}
});
return false;
});
Obligatory codeblock for requirements. Please check the PasteBin.

I found the answer. In the JS, replace the success function with
success : function(data) {
if (data == "success")
windows.location = "list_user.php";
else
alert("Form didn't go through.");
}
And instead of
header("Location:list_user.php");
Replace with
echo "success";

Related

how to adjust margin session flash in php?

I am trying to flash a success message when data store successfully. My database code and every other thing working fine but when I give $_SESSION success message it always come under navigation.
1) I want to know is there any way in php to set margin of $_SESSION['success_flash'] message
2) is there any way like /n/n type so that my flash message will show two line below
3)
My real code is:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried /n/n but not working:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried style="margin-top:200px;" but not working:
$_SESSION['success_flash'] = '<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
Kindly check the image below only green background is showing under the navigation bar and the text message "Data saved successfully!" not showing because it is hidden under the navigation.
One more thing I am using below code after the flash message and my code end.
echo "<script type='text/javascript'> document.location = 'index.php'; </script>";
Any idea or suggestion would be helpful.
Thanks you.
I am getting data and passing the data to database successfully. I just want to reload my page after php call and show sucess flash to the user.
My Ajax Call: top my php page.
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
PHP once loaded it does not change on the page, it is not dynamic. The way you do this is rather weird, but can be acomplished if you will set $_SESSION['success_flash'] just right after saving the data in the database, and reaload the page.
In my opinion the best way is to use ajax here, and the ajax response can change the container under the menu to "success".
But I don't know how do you send your data, is it by POST form or something?
Add display:inline-block; or display:block; in the styles of the span.
As long as dom elements behaviour can depend on outer dom objects (and you do not specify them): if it still does not work try using padding instead of margin, if it still does not work place two span tags one inside other both with inline-block.
All that stuff using $_SESSION is kinda weird, however XD... but from your description I assume that it shows already the span, but without the margin... but you should not use $_SESSION in that way.
OK, now we are getting somewhere. But now location.reload is unnecessary, because if you will receive 'passed' answer, you can set the communicate without reloading (and without using any code in session variable, get rid of $_SESSION['success_flash']), like below.
Please note that I do not know what is the CSS class or ID of your green DIV (if any), so for this specific example I will assume, that it has a class ".msg-response"
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
// this new line will change the content of your message div
$('div.msg-response').html('<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>');
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
there is also a security risk here: "if (data != 'passed')" - you will echo PHP errors (path, filename, variables, class, code row etc.) when something unpredictionary will happen, unless you will turn display_errors off on your server (display errors should be enabled only in development mode, that's a good practice).
To avoid it you can use JSON response here, handle the "error" status, "success" status, and do nothing if JSON response is different from "success" or "error".

Why am I getting a double response from this AJAX request?

Can anyone explain why I seem to be getting a double success response from this AJAX request using Bootstrap modals?
I am getting back testtest instead of test.
I'm pretty sure from looking at the console there is only 1 request being made and I've checked the scripts are only being loaded once.
Button triggers script:
<i class="fas fa-pencil-alt">Notes
Javascript(A bit convoluted from trying previous fixes found on S.O.)
function openNotesModal() {
$('#notesModal').modal({
keyboard: false,
backdrop: 'static'
});
}
$('.openNotesModal').click(function() {
openNotesModal();
});
$('#notesModal').on('shown.bs.modal', function(e) {
jQuery.ajax({
url: $('.openNotesModal').attr('data-note'),
success: function(response) {
$('#notesModal #theNote').val(response);
console.log(response);
}
});
});
AJAX request routed to this method
public function action_thisNote($ra,$qID,$bID = null)
{
echo "test";
}
Should return 'test' but returns 'testtest' instead
Modifying the method my AJAX call was routed to has fixed this. The issue is actually related to Concrete5 CMS which I'm building on top of.
Controller methods prefixed action_ are routed via urls for use in form submission. I think they auto-redirect after a form is submitted and this was causing problems with my AJAX request in the bootstrap modal. Calling exit(); function after returning my value stops the redirect and any other onward processing by the CMS.
Thanks to #epascarello in the comments above for leading me to the fix by suggesting the obvious of checking the URL outside of AJAX request helping to isolate the issue.
Fixed PHP function/method:
public function action_thisNote($ra,$qID,$bID = null)
{
echo 'test';
exit();
}

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Do ajax requests works if JavaScript is disabled in the browser?

I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions.
If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax?
Find a below a sample button click event:
$("#renameCategory").live('click', function (event) {
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: '#Url.Action("UpdateCategoryName", "Category")',
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
How can I handle this?
Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the <a> tag href like so:
Click Me!
$("#renameCategory").on('click', function (evt) {
//To prevent the link from sending the default request
//call preventDefault() on the jQuery event object
evt.preventDefault();
//
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
//GET THE URL FOR THE AJAX REQUEST
var actionUrl = $(this).attr('href');
//
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: actionUrl,
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
You will also need to check for ajax requests in your Controller like below:
public ActionResult UpdateCategoryName() {
...
if(Request.IsAjaxRequest()) {
return Json(yourData);
}
return View();
}
This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
Ajax call works when javascript is enabled.
You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application.
If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp
View stackoverflow's page source to see how they use noscript
If JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code. The most common way to implement interactive web application other than Javascript is Flash, so you can still have a backup plan. You can also go with the old-school server side only generated dynamic pages.
Today, however it is very rare for someone not to have JavaScript enabled, so it should not be an issue at all.
Anyway you can make use of the <noscript> html tag to display a message to these users.
<script type="text/javascript">
... Js code ...
</script>
<noscript>You have JavaScript disabled in your browser. Please enable it.</noscript>
Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in.
It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run.
The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow.
All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended.

Mootools ajax form response

I'm trying to send a form with mootools and depending on the response from the php script do such or such thing. The thing is I fail to be able to use conditional statements inside of the onComplete part of the code.
I'm missing something really obvious probably, please help me :)
$('formName').addEvent('submit', function(e){
e.stop();
var req = new Request.HTML({
url : 'phpUrl.php',
data : $('formName'),
update : $('modify-me'),
onComplete: function(){
$('formName').reset();
if($('modify-me').get('text') = "1"){
alert("succeed");
}else{
alert("failure");
}
}
}).send();
});
This was my lame attempt to use the php response in the code, but of course it didn't work.
Needless to say I'm new to all this asynchronous client-server communication stuff, but I'm really intrigued by it.
You are assigning in your if statement (single =), not checking equality (==). Change the line
if($('modify-me').get('text') = "1")
to
if($('modify-me').get('text') == "1")
Sorry guys, maybe I'm late... I'm working on Mootools 1.2.4 for the client side and on PHP for the backend. This is the way I submit forms and get response from the server...
$('myFormID').set('send', {
noCache: true,
onRequest: function(){
// show some rotating loader gif...
},
onComplete: function(response) {
// hide the loader gif...
objJson = JSON.decode(response);
if(objJson.success){
// do your success stuff...
alert(objJson.msg);
} else {
alert(objJson.msg);
}
},
onFailure: function(){
alert("Request Aborted.");
}
}).send();
In my case the form submit is triggered by a button, but could be whatever... let's look at the server side (I use PHP but any other language is good)
if($somethingWentWrong){
echo json_encode(array("success" => false, "msg" => "Check your form."));
} else {
echo json_encode(array("success" => true, "msg" => "Data saved."));
}
after all the server-side checks and validations (and maybe an Update on a MySql batabase) I just return a Json array (that's whay I have a JSON.decode(response) on the client-side-earth) and then just check the "success" key to discover if the submitting succeded on the server-side-moon. I just add a small message that I display in an alert. Obviously I could use the JSON array to send back a lot more data to the client, but in this case is enough. Hope this helps and please let me know of better solutions.

Categories

Resources