4 weeks ago I wrote a php script which adds products to a cart. As I am new to javascript, I decided to make it better by page loading using ajax.
My work looks like this:
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php
if(isset($_SESSION["products"])){
echo count($_SESSION["products"]);
}else{
echo 0;
}
?>
</a>
<form class="form-item">
<div class="cart">
<input type="submit" value="Add to Cart" class="button" />
</div>
</form>
<script>
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
$("input[type=submit]").val('Adding...'); //Loading button text
$.ajax({ //make ajax request to cart_process.php
url: "test2.php",
type: "POST",
dataType:"json", //expect json value from server
data: form_data
}).done(function(data){ //on Ajax success
$("#cart-info").html(data.items); //total items in cart-info element
$("input[type=submit]").val('Add to Cart'); //reset button text to original text
alert("Item added to Cart!"); //alert user
})
e.preventDefault();
});
});
</script>
It seems like the code stops working when I start making the ajax request to test2.php
because I can't access the file test2.php
and I do not really know where the error is coming from.
Thanks for helping
</div>