Ajax is not working when I fetch data from MySQL - javascript

I'm building an ecommerce.and for this I'm fetching data products from database, I want to let people add products in cart without refreshing the page, I have tried AJAX but I don't know why but it works only when data is not in a loop, I'm in PHP, and MySQL.
Code:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="upcart(<?php echo $list['id']; ?>)">
</form>
<?php
}
?>
<script>
$(document).ready(function() {
function upcart(id){
e.preventDefault();
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId"+ id).serialize(),
// dataType: "text",
success: function (response) {
alert("success");
}
// return false;
});
};
});
</script>

Use events instead of manually calling the javascript function.
We then don't need to generate id's for the forms since it we will have access to the correct form in the callback.
The PHP part:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" class="some-form-class">
<input type="hidden" name="name" value="value" />
<input type="submit" />
</form>
<?php
}
?>
The JS part:
<script>
$(document).ready(function() {
// Bind the forms submit event
$('.some-form-class').on('submit', function (event) {
event.preventDefault();
// Here we can use $(this) to reference the correct form
$.ajax({
method: "POST",
url: "data.php",
data: $(this).serialize(),
success: function (response) {
alert("success");
}
});
});
});
</script>

NOTE: Magnus Eriksson answer is far cleaner
since function upcart(id) is not in the global scope, onclick="upcart(<?php echo $list['id']; ?>)"> will fail due to the missing function
You need to declare that function in the global scope
Also, you need to prevent the form submission properly
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="return upcart(<?php echo $list['id']; ?>)">
</form>
<?php
note the return upcart .... - very important
NOT INSIDE $(document).ready(function() { since you don't need to wait for document ready to declare a function!
function upcart(id) {
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId" + id).serialize(),
success: function (response) {
alert("success");
}
});
return false; // to prevent normal form submission
}

Related

Unable to get button value/attribute in jquery using php loop

I'm working on "like" and "dislike" module in jQuery with PHP,And I'm facing these two problems:
Right now unable to get id of button (like=1, dislike=0)
Query showing correct result but how to display ajax response under "like dislike" section ?
Here is my code, following code inside foreach loop:
<?php foreach // ?>
<form class="form-horizontals1" method="post" >
<input type="hidden" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
<button class="likebutn_r" id="show<?php echo "1";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<label class="lilkcount">10(dynamic) </label>
<button class="likebutn_r" id="shows<?php echo "0";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumbdown.png" height="24" width="24"></button>
<label class="lilkcount">5(dynamic)</label>
<div id="counter"></div>
</form>
<?php end foreach // ?>
<script type="text/javascript">
$(document).ready(function(){
//likebutn_r
$('.form-horizontals1').submit(function(e){
var ids = $(this).attr('ids');
console.log(ids);
alert($(this).attr("id"));
e.preventDefault();
$.ajax({
url:'<?php echo base_url();?>main/AddVote',
type:"post",
data:new FormData(this),
//dataType: 'json',
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
console.log(data);
alert(data);
$('#counter').html(data);
}
});
});
});
</script>
Here is my controller code, please tell me how I can get "like dislike" value in script and how I can show result in views ?
function AddVote()
{
$ReviewId=$_POST['ReviewId'];
$vote=$_POST['vote'];
echo $result['TotalUpVotes'] = $this->M_main->CountSubmittedCoinVote($ReviewId,$vote);
echo $result['TotalDownVotes'] = $this->M_main->CountSubmittedDownVotes($ReviewId,$vote);
}
First, move the form ouside the loop.
<form class="form-horizontals1" method="post" >
<?php foreach // ?>
<div class="my-rev-container js-rev-container">
...
</div>
<?php end foreach // ?>
</form>
Add a class to the inputs, you whould access with
<input type="hidden" class="js-form__rev" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
Finaly access them
$('.form-horizontals1').submit(function(e){
var ids = $(this).find(".js-form__rev");
console.log(ids);

Inserting through AJAX page is refreshing [duplicate]

This question already has answers here:
insert query with ajax without reloading whole page
(2 answers)
Closed 4 years ago.
Inserting the data through AJAX it's working but pages refreshing, why is that give a feedback to fix this issues.
This is my ajax code
<script>
$(document).ready(function(){
$("#button").click(function(){
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
Here I'm using HTML
<form>
<input type="hidden" id="postId" name="postId" value="<?php echo $_GET["postId"]; ?>">
<input type="hidden" id="userId" name="userId" value="<?php echo $_SESSION["u_id"]; ?>">
<textarea placeholder="Post your comment" id="postComments"></textarea>
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
</form>
You are facing it due to the button having input type “Submit”
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
Just change it to normal “button”
<button type="button " id="button"><i class="fa fa-paper-plane"></i></button>
Easy fix: Add a preventDefault(). Notice the 'e' I added to your click function.
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
You can prevent the default submit button behavior - submitting the form - with event.preventDefault();
<script>
$(document).ready(function(){
$("#button").click(function(event){
// prevent the default submit button behaviour
event.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
another ajax i'm using but some issue is coming page is refreshing.
<script>
function inspire(x){
var insPer =$("#insPer"+x).val();
var insPos =$("#insPos"+x).val();
$.ajax({
url:'../validate/inspire.php',
method:'POST',
data:{
u_id:insPer,
p_id:insPos
},
success:function(data){
//alert(data);
}
});
}
</script>
this is html code
<input type="hidden" id="insPer<?php echo $p_id; ?>" name="insPer" value="<?php echo $_SESSION["u_id"]; ?>">
<input type="hidden" id="insPos<?php echo $p_id; ?>" name="insPos" value="<?php echo $p_id; ?>">
<a href="#" onclick="inspire(<?php echo $p_id; ?>);">
Better do this
$(document).ready(function(){
$("form#comment").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
// console.log(formData);
$.ajax({
url: '../validate/inserPostComm.php',
type: 'POST',
data: formData, //The Form data contain array (postId,userId,postComments)
success: function (data) {
// do something if success
},
error: function(xhr, ajaxOptions, thrownError) {
//If error thrown here
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="comment" method="post" enctype="multipart/form-data">
<input type="hidden" id="postId" name="postId" value="...">
<input type="hidden" id="userId" name="userId" value="...">
<textarea placeholder="Post your comment" id="postComments" name="postComments"></textarea>
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
</form>

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

Form action onclick without refreshing with Ajax

I have a simple chat app. Users type in username and message and it is supposed to be inserted into database.
This is not happening with this code, and obviously I am missing something:
FORM + SCRIPT
<form action="chat_s.php" method="post" class="send" id="form1" >
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
</p>
<div style="width: 480px; height: 400px; text-align: left;" id="DIV_CHAT">
</div>
<p>
<textarea id="msg" rows="5" cols="66" name="msg" placeholder="Your Message"></textarea></p>
</p>
<input class="submit" type="submit" id="button1" name="submit" value="Send" onfocus="this.blur()" />
</form>
<script>
var frm = $('#form1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
});
ev.preventDefault();
});
</script>
This is the php file that is supposed to insert into the database the users input:
CHAT_S.PHP
<?php
include_once 'connection.php';
if(!isset($_POST['submit'])) {}else
{
$name = mysqli_real_escape_string( $mysqli,$_POST['name']);
$msg = mysqli_real_escape_string($mysqli, $_POST['msg']);
$dt = date("Y-m-d H:i:s");
$sql = "INSERT INTO messages (username, chatdate, msg) VALUES ('$name', '$dt', '$msg')";
mysqli_query($mysqli, $sql); }
$mysqli->close();
?>
But the result is nothing. It alerts nothing! And it does not insert anything into the database, it just refreshes the chat box :(
try:
var frm = $('#form1');
frm.submit(function (ev) {
f = $('#form1');
$.ajax({
type: f.attr('method'),
url: f.attr('action'),
data: f.serialize(),
success: function (data) {
alert(data);
}
});
ev.preventDefault();
});

Getting form $_POST data from Ajax/Jquery in php

As always thanks in advance if you can help with this one.
I'm trying to use Ajax to call a script and post the form data at the same time. Everything works as expected except the $POST data which comes back blank when I try to echo or print it. Can anyone shine a light on what I have missed here please?
<form id="guestlist" name="guestlist">
<?php // Collect CLUBS data to pass to guestlist script ?>
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Collect USERS data to pass to guestlist script ?>
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />
<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
<input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton">Send Message</div>
</form>
<script type="text/javascript">
$(document).ready(function($){
$(".guestlistbutton").on('click',function(event) {
event.preventDefault();
$("#clubcontactform").empty();
var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#guestlist").serialize(), // serializes the form's elements.
success: function(data)
{
$('#clubcontactform').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is the php file that it pulls in
<?php
echo 'Pulling in guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;
?>
Thanks!
Every thing seems to be correct only you forget to include the jquery file. please include and try once. If still persist the issue will create the Jsfiddle
I checked your code in my local machine and I got the following error "Caution provisional headers are shown". If you have the same message in your browser console, this information can help you: "CAUTION: provisional headers are shown" in Chrome debugger
Also, I see that js work perfectly. Problem in your url address. Try send your form to itself, just write html part and php part of code in one file.
<div>
<form id="Get_FRm_Data">
/*
Some field using.....
/*
</form>
<button type="button" name="submit" class="submit_act">Submit</button>
</div>
<script>
var file_pathname = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
var $this_val=$(this);
$this_val.html("Loading...").prop("disabled",true);
var $data_ref = new FormData($("#Get_FRm_Data")[0]);
$data_ref.append("action", "fileaction_name");
$pathname = file_pathname + "filename.php";
$.ajax({
url: $pathname,
type: 'POST',
data: $data_ref,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result, status)
{
console.log(result);
if (status == "success")
{
$this_val.html("Submit").prop("disabled",false);
}
}
});
});
</script>
<?php
if (isset($_POST['action']))
{
$action = $_POST['action'];
if($action=="fileaction_name")
{
print_r($_POST);
}
}
?>

Categories

Resources