<?php
session_start();
?>
<?php
$con=mysqli_connect("localhost","root","") or die(mysqli_error());
mysqli_select_db($con, "sada_r_t_m");
$result=mysqli_query($con, "SELECT * FROM products ");
echo "<h2 fontsize = '26' color = 'yellow' align = 'center'>Flipkart</h2>";
echo "<table border = '5' cellpadding = '12' align = 'center' background-color = '#84ed86' color = '#761a9b' >";
echo "<tr>";
echo "<th>SNO</th>";
echo "<th>Product Name</th>";
echo "<th>Price</th>";
echo "<th>Cart</th>";
echo "</tr>";
while($data = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<th>".$data['id']."</th>";
echo "<th>".$data['name']."</th>";
echo "<th>".$data['price']."</th>";
echo "<th><a href='#' Onclick='add(".$data['id'].")'>Add to Cart</a></th>";
echo "</tr>";
}
echo "</table>";
?>
<script type="text/javascript">
function add(id){
alert(id);
$.ajax({
url: '../ajax.php',
type: 'POST',
data: { action: "add",id: id, val:1} ,
//contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
</script>
I passed the values through ajax in php. I wrote only in single php page.
How to pass values through ajax in php. While passing values,i am getting below error
Uncaught ReferenceError: $ is not defined
How to achieved this error i am new to php.
Please add jquery library file for use $. Please put this code in your file at top.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
OR
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Your JavaScript Change this type. Error alert show what error Occurred
Add Jquery library file at head tag
<script type="text/javascript">
function add(id){
alert(id);
$.ajax({
url: '../ajax.php',
type: 'POST',
data: { action: "add",id: id, val:1} ,
success: function (response) {
try{
alert(response.status);
}
catch(e){
alert("Error"+e);
}
},
error: function (e) {
alert("error"+e); or alert("error"+JSON.stringify(e));
}
});
}
</script>
You use try and catch . this show where error show
this code useful for you
I cannot comment yet, so I posted here. There's a good example on another answer on how to properly do ajax post requests:
http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php
Also, this is a good tutorial that will set you on the right track:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
http://hayageek.com/jquery-ajax-post/
Also, try to change ../ajax.php to the full url.