Javascript Console Commands Not Working After Ajax Sending Back in Page - javascript

I'm controlling a website in Chrome developer console. There is a form and a submit button for sending the form via ajax (I guess) without refreshing the page. The form is resetting after sending information.
I assigned some attributes to a form element in the page with Javascript. There are some processes that do not matter, and I'm sending the form but the attributes of the elements are resetting in the new form. I am forced into calling the same scripts again.
Is there anyway for global valid command with console coding, because the webpage isn't mine? (In pure-JavaScript)

there are a couple ways to achieve this.
the easiest: will probably be to create a snippet in the web developer tools, and run it from there.
Another manner would be to create a google extension (with 'declarativeContent' and 'activeTab' permissions) that can inject content script or execute script on a page.
you can find more information on developing chrome extensions and background page events here: https://developer.chrome.com/extensions/background_pages

While using the form in a html page the values inside the form get submitted to the url given in the form action without checking the javascript if some callback functions are defined.
<form method="post" action="your_url">
....
</form>
If you doesn't provide the action then the form get submitted to the same page, and no javascript action will take place.
If you want to submit the form using the javascript action then you can use one of the following methods.
Method 1: Calling javascript function from action
<form method="" action="Javascript:your_function()">
....
</form>
<script>
function your_function(){
...
}
</script>
In this method all the form validation and ajax submission should be carried out manually inside the function. URL and METHOD should also be defined inside the ajax call.
Method 2: Using JQuery form onSubmit
<form id="target" method="" action="">
....
</form>
<script>
$( "#target" ).submit(function( event ) {
event.preventDefault();
alert( "Handler for .submit() called." );
});
</script>
In this method the form validation is handled and callback to submit function will take place only when the form is validated. The ajax url should be given inside the ajax call.
Method 3: Using JQuery Ajax Validation Submit
<form id="target" method="post" action="your_url">
....
</form>
<script>
$("#target").validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
dataType: 'json', //optional
success: function(data) {
...
}
})
}
})
</script>
In this method the URL and METHOD are defined in the form. The validate function will check whether the form is valid and submitHandler will execute when the form is valid. $(form).ajaxSubmit callback function will handle the ajax call to the URL and METHOD given the the form. This method will well suit for your question. Also try other methods in you need so
NOTE: Refer https://jqueryvalidation.org/validate/ for documentation.

Remove any submit listener on the form. Then attach your own submit listener with js event.stopPropagation() break.

Related

Use javascript AND PHP in one <input> tag?

I feel like I've looked around for the answer for this question, but most of the responses are very hacky: involving javascript that pops in via AJAX, redirects and other ways of modifying the DOM on the fly.
What I want to do is make the submit button disappear when a user submits a document (javascript) and submit the message via mail (php). The code I have is the following:
<form action="" method="post">
...
<input onclick="removeElements()" id="subButton" class="submit" name="submit" type="submit" value="submit">
The php mail function is in the same document.
Here is the removeElements() function:
var el = document.getElementById("subButton");
el.remove();
document.getElementById("thankYouMessage").setAttribute("style", "display:block");
The submit function works without the javascript call, but when I add the onclick="removeElements()" part, then the javascript part starts working, but the php is no longer executed.
I know that there are other methods for doing this, but in this case, I'm actually curious about why this doesn't function as I had planned. By removing the submit button, am I in effect killing the child PHP process mid(or pre)-execution?
Thanks!
If you add onclick you will have to fire the submit manually.
The other option is add your javascript call code in onsubmit="removeElements()" on the form tag. This way, it will execute your code after executing submit
Related question here
Don't remove the button, rather set visible: hidden or display: none for its style. This way it will still be in the document and will work, it just won't be shown.
When you send the form reloads your page so I suggest:
Using Ajax and only delete button on the response, or
Not generate the button when reloads your page.
Jquery Ajax examples: You can see them here api.jquery.com/jquery.ajax/
Regards.
You could simple use the .hide functionality which JQuery gives you. It's very simple to use and very clean.
Example1 using JQuery:
$("#FormID").submit(function(e)
{
e.preventDefault();
// Hide button
$("#subButton").hide();
// Display thank-you message
$("#thankYouMessage").css("display", "block");
});
Example2 using JQuery:
$(document).ready(function() {
$(".submit").click(function() {
$("#subButton").hide();
$("#thankYouMessage").css("display", "block");
return false;
});
});

XHR call using plain JavaScript

I am having issue with XHR call made to GitHub domain from localhost.
Upon clicking on the button Click to get User Profile with Ajax+JS, a JS function getUser() gets called. Code works as expected, i.e., gets a particular GitHub user details(full name and avatar) and displays on the page.
## Code for "Click to get User Profile with Ajax+JS" button
<input type="button" value="Click to get User Profile with Ajax+JS" onclick="getUser()" id="jsBtn" />
BUT, when I call the same JS function on form submission using submit button (or return), it does not return the expected result i.e., user details.
## Code for "Submit" button
<form id="myForm" onsubmit="getUser()">
#...
<input type="submit"/>
</form>
Upon inspecting under Network, I see the difference in the way Request URL is formed in Request Headers Section:
## With GitHub username input as kirtithorat
## First Case With "Click to get User Profile with Ajax+JS" button
Request URL:https://api.github.com/users/kirtithorat
## Second Case With "submit" button
Request URL:http://localhost:3000/html_file_name?username=kirtithorat
Why the difference in behavior? The same JS function works for onclick but not for onsubmit.
NOTE:
I am looking for a Pure JS Solution. I know how to do it in
jQuery.
I don't actually want the form to be submitted, only the
onSubmit event should be triggered.
Here is my JSFiddle
Your second URL looks like the form submission, NOT the result of calling getUser() (the getUser() ajax call probably came right before the form submission).
If you don't want the form to actually submit (which it appears is how you want it) and only want your onSubmit handler to be called, then you need to make sure the default behavior of submitting the form is prevented.
You can block form submission by just adding a
return false;
to the end of your getUser() onsubmit handler function.
Or, you can block the form submission by passing the event into the getUser() function and using e.preventDefault().
The other reason to block the form submission is that the page will reload with the results of the form submission and your javascript will not still be active to receive the results of the getUser() ajax call. So, you must use one and only one of the Ajax call or the form submission (it looks like you just want the ajax call so you can prevent the form submission).

Ajax Request dont work without alert statement

I have a problem with a AJAX call. I am trying to access the inputs of a HTML
form element and write this to a database with a PHP script.
My JS code looks like this....
function getWriteValues() {
var x = document.getElementById("eingabemaske");
var jqxhr = $.post( "source/form_handler.php",
$( "#eingabemaske" ).serialize() );
alert( 'Eintragung erfolgreich durchlaufen' );
}
The PHP part isn't interesting because there nothing except the database insert happens.
Now to my Problem. The Function makes what it should do. But when I delete the alert() statement, nothing works any more. That means that nothing is written to the database and the ajax call could not be made. I can't figure out where the problem is.
I use jQuery in Version 2.1.1.
When you click the submit button you:
Run the JS
Send the Ajax HTTP request
Submit the form
Leave the current page
Cancel the Ajax HTTP request because there isn't going to be anything left to handle it.
Either:
Prevent the default action of the submit button so you don't leave the page or
Get rid of the JS and do your database insertion in the program you specify in the action of the form
Do you call getWriteValues(), if the the form is submitted?
If so, don't forget to return false;
Check in your html "name" attribute is defined for each form elements or not as serialize() takes element name and its value.
Check whether you're getting the values in getWriteValues()
Verify these values are passed to form_handler.php script.
sample:
<form id="eingabemaske">
<input id="abc" name="abc" value="test" />
<input type="button" id="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function(){
$('#submit').on('click',function(e){
e.preventDefault();
getWriteValues();
});
});
function getWriteValues() {
console.log($( "#eingabemaske" ).serialize());
var jqxhr = $.post( "form_handler.php",
$( "#eingabemaske" ).serialize() );
//alert( 'Eintragung erfolgreich durchlaufen' );
}
</script>
in php script
print_r($_REQUEST);
It may be due to that alert message is giving time to ajax to perform its work. please check all the process that happens before and after the ajax. Also, as you are calling ajax from submit button (i suppose that that u have called this function from "onsubmit" attribute of the form), may be its submtting the form before ajax is completed. Please return false at the end of function in order to stop function processing further.

ajax call doesn't work when a submit button is used

I'm trying fetch a live currency rate using the following API.
"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"
When I click on a button, it alerts the rate and works just fine. I'm using the following Ajax code.
<script type="text/javascript" language="javascript">
function testCurrencyRate()
{
$.ajax({
datatype:"html",
type: "GET",
url: "ajax/LiveCurrencyRate.php",
data: "t="+new Date().getTime(),
success: function(response)
{
alert(response);
},
error: function(e)
{
alert('Error while fetchig the live currency rate.');
}
});
}
</script>
The Ajax request goes to the LiveCurrencyRate.php page which is as follows.
$url="http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj";
$result = file_get_contents($url);
echo $result;
and the <form></form> which contains the only button which when clicked makes an Ajax request on this URL ajax/LiveCurrencyRate.php.
<form id="testForm" name="testForm" action="" method="post">
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>
Everything is fine. The problem however arises when I change the button type from type="button" to type="submit", it doesn't work. The alert box in the error part of the Ajax function shows the alert box just for a while and all of a sudden it disappears. I can't find any reasonable cause that may prevent this request from being completed. The same thing worked for me in my previous project but I was using XMLHttpRequest for making Ajax requests. What's going wrong here?
type="submit" causes the web browser to submit the form via a postback (because your method attribute is set to "POST"), which causes the page to refresh. The action attribute of the <form> tag determines where the data gets sent to, and then that page loads with the data provided. When this happens, all javascript on the page terminates because you are effectively going to a different page or reloading the current one.
The page is submitting because you are not cancelling the default action of the click. You need to stop that event from happening. With your code, you can add a return false to the onclick, but it is better to add the events in an unobtrusive manner.
$("#btnTestCurrencyRate").on("click",function(e){
testCurrencyRate();
e.preventDefault();
});
better to catch it on the form submission and not onclick
$("#testForm").on("submit",function(e){
testCurrencyRate();
e.preventDefault();
});
When you click the submit button your form is being posted to you web server. You need to prevent the form from posting by using something like:
$("#testForm").submit(function(e){
e.preventDefault();
});
because your page is submitting. you need to return false from the onclick handler if you want to prevent the submit.
HTML:
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test"/>
JS:
document.getElementById('btnTestCurrencyRate').onclick = testCurrencyRate;
function testCurrencyRate() {
... snip ...
return false;
}

javascript form.submit() losing querystring created by GA _linkByPost

We have a booking form that POSTs to the parent company website. Because this is a different domain we need to implement the GA _linkByPost to pass the GA tracking cookie info across domains.
As the booking form is in a .NET user control it does a postback. On postback we validate, wrap up the booking info, and write a form back to the client with hidden elements required by the target booking engine and add line of javascript to submit the form.
Below is the javascript function I'm using to submit the form:
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
thisForm.submit();
}
And the relevant form info:
<form id="PostForm" name="PostForm" action="ClientBookingEngineUrl" method="post" >
booking form info in here
</form>
The result is that we fill in the form, hit submit which does a round trip to the server generates a new form and POSTs the info. This all works fine apart from the URL loses the GA cookie info from the query string. If I comment out the form submit line and look at source code I can see the GA cookie info on the querystring - but when posting, I do not see the querystring (using Fiddler).
To clarify:
The above technique works and does what we want with regards to POSTing form data to the booking engine and taking the user there.
If the submit line is commented out you can see the form with the modified action that has the GA stuff appended (using Firebug).
If the form is submitted with the submit line, the querystring info is removed (confirmed by Fiddler).
Am I missing something obvious? Are there some gotchas regarding JS submit, form POSTs and querystrings? Or is there a simple trick I'm missing?
Cheers
EDIT 1
An oddity has occured.
If I alert the form action before and after the _gaqPush then we can see the URL in its before and after state and it's as expected.
alert('1 form action = ' + thisForm.action);
_gaq.push(['_linkByPost', thisForm]);
alert('2 form action = ' + thisForm.action);
Alert 1 shows the pre-modified action and alert 2 shows the action with the GA info.
With the alerts in place it submits WITH the GA info in the query string.
If I comment out the alerts the GA info is NOT in the query string...
I'm starting to think the form or something is not ready so I'm trying it with JQuery's document ready.
EDIT 2
Wrapping the method call in document ready doesn't help. I'm confused as to why action URL is correct AFTER displaying it in an alert but incorrect if I don't alert it.
Answering this for posterity.
The problem is the _qaq (Google Analytics Queue) hasn't had time to modify the form before the call to submit() the form.
The solution is to push a function onto the _gaq object that submits the form so it will happen directly after the form modification is done.
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
_gaq.push(function() { thisForm.submit(); });
}
I tried a simple HTML page that calls _gaqPush and submits immediately. This also fails.
Adding a 1000ms delay works (for the most part) so I suspect the alerts just gave the GA script time to modify the form.
I'm closing/accepting this as it seems down to submitting the form too quickly after the GA call.

Categories

Resources