I have a simple webstore and I'm trying to add multiple shipping options. There are two options and I want to store the option selected by the customer in a session (or alternatively a cookie).
The php script seems to work on its own but results in page reloading so I have been trying to implement ajax using jquery to send the data but either the code doesn't run or the page reloads.
I have tried to follow several answers, including substituting button for type="submit" but that results in the code not seeming to execute at all. Adding 'click' to .on triggers the code but also results in a reload. I've checked the console and can't see any issues. Thanks for any help.
jQuery
$(function(){
$('#shipping_form').on('submit', function(e){
e.preventDefault();
var ship = $('input[name="shipping_val"]').val();
$.ajax({
type: 'GET',
data: { discount: ship },
success: function(data) {
//go to next section
}
});
return false;
});
});
HTML/PHP
<?php
Session_start();
if(isset($_GET['shipping_submit'])){
$shipping_get = $_GET['shipping_val'];
}else{
$shipping_get = '3.99';
}
$_SESSION['shipping'] = $shipping_get ;
?>
<html>
<main class="container">
<form method="GET" name="shipping_form" id="shipping_form" action="">
<p>Please choose your prefered shipping method.</p>
<input type="radio" name="shipping_val" value="3.99" checked>
<label for="shipping_val">
Standard delivery
</label>
<input type="radio" name="shipping_val" value="6.99" >
<label for="shipping_val">
Express delivery
</label>
<button type="submit" id="shipping_submit" name="shipping_submit" >Update</button>
<?php
echo '<h1>' . $_SESSION['shipping'] . '</h1>';
?>
</form>```
Your problem is likely that you are using AJAX to submit data to the same file you are calling it from. Your ajax end point (PHP-side) needs to be a different PHP file.
See this other question:
values not updated after an ajax response
Related
<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/
I spent quite a bit of time looking for this and maybe I'm not approaching this correctly, but I'm trying to .submit and .post after clicking a submit. In other instances I have been able to get the ajax submit to work properly without the refresh, but when I do it in this manner it just doesn't work. I'm curious to know why.
Form
<form id="search" action="process.php" method="post">
Name: <input id="search_text" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
Ajax
$('#search').submit(function() {
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
$('#page_nav').html(data.html_page_nav);
$('#results').html(data.table_html);
},
"json"
);
return false;
});
This works and it will submit without reloading just fine
Below is where I have the problem.
On the php server side I am sending back html that I want to be able to submit, which the initial search will put into the original html page.
$html_page_nav = "
<ul>
";
for($i=1; $i <= get_query_pages(get_query_count($query), 50); $i++) {
$html_page_nav .= "
<li>
<form id='page_".$i."' action='process.php' method='post'>
<input type='hidden' name='action' value='change_page'/>
<input type='hidden' name='page' value='".$i."'/>
<input type='submit' value='".$i."'>
</form>
</li>
";
}
$html_page_nav .= "
</ul>
";
I try to do the same thing as above, but the submit does not work properly
$(document).ready(function() {
$('#page_1').submit(function() {
console.log("this will not display");
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
},
"json"
);
return false;
})
...other jquery
});
This submit will not work properly, the function() will not execute and it will submit like the regular submit and go to the url rather then execute without refreshing the entire page.
Any suggestions or approaches would be much appreciated.
Thanks in advance!
Delegate the submit action to execute on content which will be loaded in future. By default the normal event handlers attached to the content loaded on DOM but not the one which will gets loaded in future, say through Ajax. You can use jQuery "on" function to delegate the action on content which will load in future.
eg.
$('body').on('submit', '#page_1', function() {
// do it here
});
I had a similar problem using ajaxForm n all. I jus used $("#Form").validate();
for it and the page doesnt get refresh
I'm clearly doing something wrong here, but I can't figure out why the Ajax isn't firing and instead insists upon a page load. The newBatable() fires fine, I just can't seem to get the vote to respect the ajax call.
HTML - not sure how to put html in here as code :/ - I feel dumb.
<form class="form-horizontal" id="batable1" action="vote.php" method="GET">
<div id="success-vote-1"></div>
<input type="radio" name="batableResult" value=" include ()" /> include ()<br/>
<input type="radio" name="batableResult" value="require ()" />require ()<br/>
<input type="radio" name="batableResult" value="both of above" />both of above<br/>
<input type="radio" name="batableResult" value="None of above" />None of above<br/>
<button class="btn btn-primary" onClick="vote(1)">Vote</button>
<input type="hidden" name="batableId" id="batable-id" value="1"/>
</form>
JS - the console display everything I want, the php script processes everything nicely and functions perfectly, it is just it has to load the php in the browser so it's not using AJAX
/***************************************/
function newBatable() {
var batableData = $('#new-batable').serialize();
//console.log(batableData);
$.ajax({
url: "process.php",
data: batableData,
success: function(data){
$('#success-new-batable').html(data);
}
});
}
/***************************************/
function vote(poll_id) {
//console.log(poll_id)
var batableId = "#batable" + poll_id;
//console.log(batableId)
var pollData = $(batableId).serialize();
//console.log(pollData);
$.ajax({
url: "vote.php",
data: pollData,
success: function(data){
var batable_success_id = "#success-vote" + poll_id;
$(batable_success_id).html(data);
}
});
}
The submit button fires the JavaScript and then immediately submits the form.
If you are using onclick, then return false to stop that.
You would be better off using a more modern event binding technique though.
how about attaching a click event via jquery to the button?
$(".btn").on('click', function(e){
e.stopPropagation()
e.preventDefault();
vote(1);
});
this would usually be placed in document .ready jquery in an external file or somewhere near the bottom of your page inside script tags.
Does this help?
Since you're already using jQuery, as SubstanceD, you should use jQuery's on() method and stop the event propagation and prevent the default action (submitting the form).
I also noticed a possible bug in your code. It looks like there is a typo. You have
var batable_success_id = "#success-vote" + poll_id;
and <div id="success-vote-1"></div>. You have a dash after vote in the div's ID while you are concatenating batable_success_id into #success-vote1, for example. So even if the AJAX call is made, it probably won't update your HTML like you're expecting.
Greetings from some noob trying to learn JQuery,
I am attempting to make it when you type something in a box below a div layer it reloads that layer upon submission of the form with a php get of the text box in the form. Expected behavior is it would reload that box, actual behavior is it don't do anything. Can someone help me out here.... Below is the code.
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
<input type="submit" name="submit" class="button" id="submit_btn" value="New City" />
</form>
<script>
/* attach a submit handler to the form */
$('form[name="changewx"]').submit(function(event) {
/* get some values from elements on the page: */
var $form = $( this ),
city = $('#city').val()
/* Send the data using post and put the results in a div */
$('#currentwxdiv').load('http://api.mesodiscussion.com/?location=' + city);
return false;
});
</script>
Its giving the Javascript Console Error Error....
"XMLHttpRequest cannot load http://api.mesodiscussion.com/?location=goodjob. Origin http://weatherofoss.com is not allowed by Access-Control-Allow-Origin."
You are using POST method? is impossible to post to an external url because with ajax, the url fails the "Same Origin POlice".
If you use GET method, is possible to do that.
Another solution is to make a proxy. A little script that recive the params and then... using CURL or another thing you have to post to the external URL... finally, you jquery have to do the post thing to the proxy:
For example:
$.ajax({
url: '/proxy.php?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
I do it so:
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
</form>
<script>
$('#city').keyup(function() {
var city = $('#city').val()
$.ajax({
url: 'http://api.mesodiscussion.com/?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
});
</script>
To help you out, i need to test this.
What's the url address of your html code working ?
http://api.mesodiscussion.com/?location= doesn't work... only list the directory content... maybe that's de problem?
Greatings.
I'm not sure if I am making this more complex then what it is... What I want to do: depending on which button the user presses $price should be calculated and displayed without the page beeing reloaded. The $price variable gets its data from a database. I cannot get this to work so if someone could help me would be fantastic, thanks linda
my form
<form id="f1" method="POST">
<label for="r1">Exkl. moms</label><input type="radio" name="radio" value="exkl" checked="checked" id="r1"/>
<label for="r2">Inkl. moms</label><input type="radio" name="radio" value="inkl" id="r2"/>
</form>
<div id="results"></div>
<?php
if(($_SESSION['user_info']['moms'])=="inkl"){
$price*1.25;
}
?>
jquery
function showValues() {
var str = $("#f1").serialize();
$.ajax({
type: "POST",
url: "momsTest2.php",
data: str,
success: function(html){
$('#results').html(html);
}
});
}
$(":radio").change(showValues);
showValues();
momsTest2.php page
session_start();
$_SESSION['user_info']['moms'] = $_POST['radio'];
Does it need to be done server side? Otherwise, what you can do is first load the price from the database and save it to a javascript variable, then perform the calculations client side in javascript instead of using ajax to process the calculation server side.