Ajax Request dont work without alert statement - javascript

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.

Related

Javascript Console Commands Not Working After Ajax Sending Back in Page

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.

Jquery var to php but do not return

I have a HTML form that I want to send to PHP but also some javascript variables. These JS vars are not in the form. How can I get both to th PHP class?
Below is the code I have so far.
$("#login_FORM").submit(function() {
event.preventDefault();
$.post('../class/login.Class.php',{
//.. serialized form data
screen:screen.width
//...ser
//...
},function(data){
alert(data);
window.location.href = "";
});
});
The screen variable ends up perfectly in login.Class.php but when it gets to the end of the php file... it returns to above javascript function.
Even when using a header into php it returns to the javascript function. It simply reads that page as well and returns everything thats returned in there.
echo $_POST['hash'];
header('Location: ../index.php'); die();
Only if I use a window.location.href = ""; in javascript I can redirect to a correct page after processing the javascript data in the login.class.php file (redirecting to correct page isn't the only reason I'm asking the question...fyi)
How can I send variables from jquery / javascript to PHP and continue from there? aka not return to the (success) function the variables were send from.
If I understand you correctly you want to pass the serialized form data plus some jquery variables if that's the case you could use serializeArray()
var data = $('#myForm').serializeArray();
data.push({var1: 'value', var2: 'value'});
$.post("myPage.php", data);
EDIT
I think i got what you are trying to do, if you submit the form using jquery ajax it will always return to the success function because any redirection in php will only redirect the ajax request and not the current "screen".In that case try the following (not a 100% but here it goes):
add hidden fields to your form say:
<form action="/class/login.Class.php">
<!-- form content n stuff -->
<input id="var1" name="var1" type="hidden" value="someValue" />
<button id="letsGo" type="submit">Submit</button>
</form>
$('#letsGo').click(function(e) {
e.preventDefault();
var form = $(this).closest('form');
$('#var1').val('dasValue');
// replace as many hidden inputs as you need
form.submit();
});
Hope this helps.

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

How to stay on same position after submitting an html form?

I have a simple html form:
<form action="addToCart" method="post"><br><br>
<input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit">
</form>
Every time I click on "submit", it brings me straight back to top which creates a poor user experience because the user would have to scroll back down where he was browsing the products... Can I do this without using a script?
-Every time I click on "submit", it brings me straight back to top.
Yes that is what default functionality when submitting forms, it always repaints the dom so it causes a jump and page's top position is rendered.
-which creates a poor user experience because the user would have to scroll back down where he was browsing the products
To make a good user experience you can use ajax for this functionality, as you tagged jQuery in your question then you can try with jquery ajax:
$('form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"text",
success:function(data){
alert(data); // you can alert the success message.
},
error:function(err){
console.log(err);
}
});
});
I have used a dataType:"text", just assuming if you are going to echo "Added in the cart."; kind of message from the php.
Ajax is your best bet if you want to achieve what you want
$('.submit').on('click',function(event){
event.preventDefault(); //this is important else page will get submitted
$.ajax({
url:'where you want to process data',
dataType:'html',
data: your form data as json or whatever type
success: function(result){
//here you can update any thing on the frontside
}
});
});
Since you're using onclick attribute on your button, you have to change type attribute from submit to button. That way you can get your addedCart() method to fire. Then handle form submission inside that method (if your submit handler isn't already there).
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">
Script:
function addedCart(){
// ... your method on click
// $.ajax({...});
};
If you're not using jQuery, you can handle form submission with XMLHttpRequest :
How to make an AJAX call without jQuery?

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

Categories

Resources