AJAX reload page with POST - javascript

Can anybody tell me how to refresh the current page with JavaScript, having a POST variable modified or added?
To be clear, I want to set some POST variables prior to reloading the page.

By using jquery ajax you can reload your page
$.ajax({
type: "POST",
url: "packtypeAdd.php",
data: infoPO,
success: function() {
location.reload();
}
});

If you want to refresh the entire page, it makes no sense to use AJAX. Use normal Javascript to post the form element in that page. Make sure the form submits to the same page, or that the form submits to a page which then redirects back to that page
Javascript to be used (always in myForm.php):
function submitform()
{
document.getElementById('myForm').submit();
}
Suppose your form is on myForm.php:
Method 1:
<form action="./myForm.php" method="post" id="myForm">
...
</form>
Method 2:
myForm.php:
<form action="./myFormActor.php" method="post" id="myForm">
...
</form>
myFormActor.php:
<?php
//all code here, no output
header("Location: ./myForm.php");
?>

Reload the current document:
<script type="text/javascript">
function reloadPage()
{
window.location.reload()
}
</script>

There's another way with post instead of ajax
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});

Got trouble making it too but it will be better if you don`t use ajax.
<script>
$(document).ready(function(){
SelectOnChange = document.querySelector("#payment"); //for <select> didn`t include it...
SelectOnChange.onchange = function(){
SelectedValue = SelectOnChange.value;
document.querySelector("#payment_schedule_date").value = SelectedValue;
document.getElementById('paymentform').submit(); //<form>
}
});
</script>
In HTML just put input with hidden and use .submit() to submit using form.
<form name="paymentform" id="paymentform" action="#" method="post">
<input hidden name="payment_schedule_date" id="payment_schedule_date" value="">

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

submit form and check for complete without submit button

I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?
As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.
Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...
for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

jQuery Submit Refreshing Page

The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false; line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
It could be your JavaScript is failing, so the default behaviour is being executed.
Try to examine the XHR in a tool like Firebug.
Also, you could try event.preventDefault() (where the first argument to your event callback is event).
my bet it's because of the $(this), try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.
Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:
$('#bin form').submit(function(ev) {
var _this = this;
ev.preventDefault();
$.post($(this).attr('action'), {
success: function() {
$(_this).hide().siblings('form').show();
},
data: $(this).serialize()
});
})
See a working example.
Is the $(...).submit(...) inside a $(document).ready(function(){ code here }); ?
should be like:
$(document).ready(function() {
$('#bin form').submit(function() {
$.post($(this).attr('action'), {
success: function(data) { $(this).hide().siblings('form').show(); },
data: $(this).serialize()
});
return false;
});
});

Categories

Resources