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

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

Related

document.form.submit() is too slow to complete before window.close()

I am having an issue with saving a form. The form itself has about 40 rows with around 12 inputs for each row in this style:
On save, it should POST and then close the window. However, it never truly saves it. This makes me think that it is closing the window before it saves. Here's the code in question:
$('#save-btn').click(function() {
document.form.submit();
window.close();
};
If I remove the window.close() and use the inspector than I see in the parameters field that all the values save correctly. This is again what lead me to think that the window is closing to early.
I have tried using the following in the above #save-btn function:
setTimeout('window.close()',5000)
Yet this never seemed to execute the window.close() after the 5 seconds and all around seems like bad programming to force it to wait 5 seconds and then close when it could take any amount of time.
I then attempted to use an AJAX request like:
var _url = 'submit?nameParam="+nameParam+"&com=editlist&'+$('form').serialize();
console.log(_url); //just to see what its pushing out
$.ajax({
url: _url,
error: function(){
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
This resulted in 414 Request-URI Too Long. I know the case for this is it should be a POST to begin with, but I was just trying to make it work.
Just because, this is how our form is set up:
<form name="form" action="submit" method="post">
Our solution was to close the page from our action page
Remove the serialized data from your _url and instead pass it through the .ajax() request with the data setting:
var _url = 'submit?nameParam="+nameParam+"&com=editlist';
$.ajax({
url: _url,
method: "POST",
data: $('form').serialize(),
error: function() {
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
Your ajax approach is correct because you can understand that form submit done correctly with code, on success post it is easy to close the window.
For sending a POST request, you have to make some small changes in your code...
Don't serialize your form and add URL, it is not safe (not working for your situation).
Post your values as "post data".
Here is documentation about it.
https://api.jquery.com/jquery.post/
Please try and update your question if you cannot understand how.

Location: Header not working for one particular trigger

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";

Calling a static method from cshtml file

I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background
I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.
You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?

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>

Prototype Ajax.Request never returns

I'm trying to learn Prototype, so I threw together a simple Log-in page, with username and password fields, and a Log-in button.
I have a controller class, where I want to put all of my onclick functions.
function Controller()
{
this.logIn = function(){
this.username = Field.getValue("username");
this.password = Field.getValue("password");
this.logInResults = function (response){
alert(response.responseText);
}
new Ajax.Request("../../php/tis/LogIn.php",
{
method:'get',
parameters: {username: this.username, password: this.password},
onComplete: this.logInResults
});
}
}
Yet, when I click the button that has the LogIn function attached, the HTTP request is sent, but returns an empty response string. When I manually follow the link to the php page, it's there, and functions as intended.
Firebug shows the following:
GET http://localhost/AJAXSeedOrder/php/tis/LogIn.php?username=User%20Name&password=
Firebug cannot find _firebugConsole element true Window tis?username=User+Name
Firebug cannot find _firebugConsole element true Window tis?username=User+Name
Firebug cannot find _firebugConsole element true Window tis?username=User+Name
I'm completely at a loss - any help would be appreciated.
Well, it turns out that my problem was in the Event.observe call that I used to bind controller.logIn to the form submit button. Invoking LogIn through the observe call would make the AJAX request, and then reload the page - which would happen faster then the webserver would return my request.
That was the reason for why the requests would return empty response strings.

Categories

Resources