Hi I've made an eshop and what I want to achieve is when I click the appropriate "add to cart button" I want the top cart (not the main cart-page of the eshop) to be updated. Top cart is one div at the header of the eshop. When I refresh the page the right content appears but this doesn't happen without refresh. I know this must be accomplished with ajax but it seems I am doing something wrong.
Part of my code:
<input type="button" class="add_to_cart" id="add_to_cart" value="BUY" />
<script type="text/javascript">
$('input.add_to_cart').click(function () {
$.ajax({
type: "POST",
url:"add_to_topcart.php",
data:$('.prod_form').serialize(),
success:function(data){
$('#show-quick-cart').text(data);
$(".add_cart_msg").delay(250).fadeIn("slow").delay(2000).fadeOut("slow");
}
});
});
</script>
</form>
</div>
<div class="add_cart_msg" style="display:none;"><img src="images/green_tick.png"/>Product was added to cart!</div>
The above has a result to temporarily count the products I add to cart
First of all, enclose your code in a document ready handler -
$(document).ready(function() {
$('input.add_to_cart').click(function () {
$.ajax({
type: "POST",
url:"add_to_topcart.php",
data:$('.prod_form').serialize(),
success:function(data){
$('#show-quick-cart').text(data);
$(".add_cart_msg").delay(250).fadeIn("slow").delay(2000).fadeOut("slow");
}
});
});
});
Then open your browser's console and any errors will be logged. You can then fix them one at a time or post them here if you need help troubleshooting.
Related
I have this button that sends the information to another php folder. but I want it to send but stay in the same page.
<button class="btn btn-outline-dark w-60"><?php echo "<td> <a href='carrinho.php?acao=adc&id=$PegaID'>Adicionar ao carrinho</a></td>";?></button>
I want it to send but stay in the same page.
You want to use AJAX.
You set your button to call a Javascript function. That Javascript function then launches the call to the URL: carrinho.php?acao=adc&id=$PegaID.
You can handle any returned data or just discard it. Usually, you would want to at least handle it so you can give the user feedback that the button was clicked and it accomplished what it was supposed to accomplish, or an error was generated.
Specifically, you will use XMLHttpRequest. Here's a link to a good write up to get you started.
Using XMLHttpRequest
You can use ajax to send data without referesh html page or change url.
ex:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc('$PegaID')">Change Content</button>
</div>
<script>
function loadDoc(PegaID) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "carrinho.php?acao=adc&id=PegaID", true);
xhttp.send();
}
</script>
</body>
</html>
This code send data using get method. We send PegaID to the javascript function and then send data and then showing the result in demo using change html.
Give your button an ID.
Remove your anchor.
Attach an ajax post to your button.
This is what your code should look like:
<button id="adicionar" class="btn btn-outline-dark" data-id="<?php echo $pegaID;?>">
Adicionar ao carrinho
</button>
<script>
$(document).ready(function(){
$("#adicionar").click(function(event){
let id = $(event.relatedTarget).data("id");
$.ajax({
type: "POST",
data: {id: id},
url: "another php.php"
});
});
});
</script>
If you're getting sent to another page just add event.preventDefault() above let id=$(event.relatedTarget).data("id")
It should look like:
<script>
$(document).ready(function(){
$("#adicionar").click(function(event){
event.preventDefault();
let id = $(event.relatedTarget).data("id");
$.ajax({
type: "POST",
data: {id: id},
url: "another php.php"
});
});
});
</script>
In "another php.php" you'll want to receive the id with $_POST['id'].
Something like $id = $_POST['id'];. Then you can do whatever you want with the id in "another php.php".
I am trying to get response trough ajax,my code (index.html) :
<button id="register">Register</button>
<p id="result">xxx</p>
<script>
$("#register").click(function(){
$.ajax({
url:'registration.php',
type: 'POST',
success:function(response){
$("#result").html(response)
}
})
})
</script>
and php (registration.php):
<?php
echo "yyy"
?>
I am working with xampp, I get response but it fades from page instantly. And again xxx is present inside p tag, does anyone know what is the reason why this happens.
Thanks
It appears that when you click the button to get your response, it also refreshes the page in your browser. You can try the following to prevent this:
<script>
$("#register").click(function(evt) {
evt.preventDefault()
$.ajax({
url:'registration.php',
type: 'POST',
success: function (response) {
$("#result").html(response)
}
})
})
</script>
This prevents your browser from doing what it normally does when you click a button.Any button inside <form>tags will automatically send a GET request within the current window, causing the page to refresh. The other alternative to preventDefault() is to use the attribute type="button" on your button and this will stop the button from being a type="submit" button.
You can read more detailed information about the function I've used here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
https://api.jquery.com/event.preventdefault/
Just prevent page before submitting.
<input type='submit' id='register'>
<div id='result'></div>
$("#register").click(function(e){
e.preventDefault();
$.ajax({
url:'registration.php',
type: 'GET',
success:function(response){
document.getElementById("result").innerHTML = response;
}
})
});
i searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/
I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......
The problem that we have is describing as follows. We have two different pages, the first one is called profile.php and the second one is called save_button.php. In the page profile.php I have this script which is written the following code in jQuery:
<script >
$(function(){
$("#save").bind('click', function(){
document.getElementById('save').style.background='#F26522';
document.getElementById('modify').style.background='#0083A9';
$.ajax({
url: 'save_button.php',
type: 'post',
data: { "callFunc1": "test"},
success: function(response) { alert(response); }
});
})
});
</script>
In the body of profile.php page we have written this code, here we have two different buttons:
<body>
<div class="button_container" >
<input id="modify" type="button" class="buttons" value="Modify" onclick="changeText();" />
<button id="save" class="buttons" >Save</button>
</div>
</body>
When we click the save button we want to execute the PHP code in another page, called save_button.php. Inside this page, save_button.php, we have written the following code:
<?php echo "test works"; ?>
What happens with us is that when we click the save button, in our page is not alerted the words "test works". Do you have any idea what to do in this page? Please, give us a quick feedback as this is a school project and we have to submit within the three next days. Many thanks.