Call for another ajax from the result one ajax request got - php

I've header file in which I have search box where user can search for products, this works on ajax request & for getting the info I've livesearch.php file.
Now with the searched products, I want to add 'Add to Cart' button directly. So in fact for every search result there will be one button to add that product in cart. To achieve this, I need to add another ajax request for adding that product into cart.
But nothing's happening while I click on add button. Here's my code.
Header.php
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function()
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function()
{
$(document).live('click', '.buynow', function()
{
var productid = $(this).attr('id');
var quantity = $('.quantity_'+productid).val();
var type= $('.type_'+productid).val();
$.ajax
({
type: "POST",
url: "db_addtocart.php",
data: {'quantity'=quantity, 'type'=type, 'productid'=productid},
success: function(option)
{
this.attr('value','Added');
}
});
return false;
});
});
</script>
<?php
<input type="text" id="text" class="searchproductbrand">
?>
livesearch.php
<?php
while(blah blah){
echo "<input type='text' id='quantity' class='quantity_".$row["productid"]."'>".
" <select name='type' class='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>";
"</select>";
echo " <input type='button' class='button' id='".$row["productid"]."'
class='buynow' value='Buy Now'>";
}
?>
db_addtocart.php
This file gets the values of variables & insert into table, nothing sort of important.
What wrong am I doing? Any help will be appreciated.

Try updating your js to the code below. I used .delegate() instead of .live() as according to the manual it is better to use with jQuery 1.4.3+.
$(document).ready(function() {
$(".searchproductbrand").keyup(function(){
var kw = $(".searchproductbrand").val();
if(kw != ''){
$.ajax({
type: "POST",
url: "livesearch.php",
data: {kw:kw},
success: function(option){
$("#livesearch").show();
$("#livesearch").html(option);
$("#livesearch").css("border","1px solid #A5ACB2"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
});
}
else {
$("#livesearch").html("").css("border","0px"); // used $('#...') instead of document.getElementById() AND .css() instead of style.border
}
return false;
});
$(document).delegate('.buynow','click', function(){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val(); // changed from .quantity_ to #quantity - requires change in php code
var type= $('#type_'+productid).val(); // changed from .type_ to #type - requires change in php code
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this, // added as 'this' below was out of scope. see the docs for more info
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added'; // changed from this.attr('value','Added');
}
});
return false;
});
});
This will also require you to update the html created in livesearch.php to the following code. Mainly changing from class=... to id=...
<?php
while(blah blah){
echo "<input type='text' id='quantity_".$row["productid"]."' />";
echo " <select name='type' id='type_".$row["productid"]."'>".
"<option value='Unit'>Unit</option>".
"</select>";
echo " <input type='button' class='button buynow' id='".$row["productid"]."' value='Buy Now'>";
}
?>
Here is a working JSFiddle example - http://jsfiddle.net/X8n3d/

What's going on is that your $(".buynow").click is bound to the element which are in the dom on load of your page. Any button with .buynow added after that has no event.
You need to use jQuery's on() method so the click event works for all elements.
Juste replace $('.buynow').click(function(e){..}) with $(document).on('click', '.buynow', function(e){..}) and it should work.

Related

Success message displaying on the wrong page

I am new to Ajax and I am trying CRUD operations using the same. I have an index.php page where I can insert and display data, also I have links to update and delete data over there.Create, Read, Update are working fine. Now the problem is that when I click the link to Delete, I am successfully sending the id to the delete_back.php and the value is getting deleted but the success message which should be printed on the index.php as I have a div named #delete_msg over there but somehow the success message is being printed on delete_back.php.
index.php
<div id="delete_msg"></div>
select_back.php
<?php
include("config.php");
$data=mysqli_query($con,"select * from student");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a href='update_front.php?id=$row[0]&nm=$row[1]&add=$row[2]&cont=$row[3]'> Update </a></td>";
echo "<td><a class='delete' href='delete_back.php?id=$row[0]'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
?>
delete_back.php
<?php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data=="true")
{
echo "Data Deleted";
}
else
{
echo "Delete Error";
}
?>
ajax file
$(".delete").click(function(event){
event.preventDefault();
$.ajax({
url:"delete_back.php",
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
add data-id attribute to anchor tag:
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can do in your ajax be like:
$("#delete").click(function(event){
var obj = $(this); // first store $(this) in obj
var id = $(this).data('id'); // get id of data using this
$.ajax({
url:"delete_back.php",
dataType:"html",
data: { id: id },
type: "Post",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
})
})
in your php file:
$id=$_POST['id'];
First of all, I really hope you don't have a loop which prints multiple anchors with same ID...
That said, according to your html, your JS should be like the followin, otherwise you will lose your id value:
$("#delete").click(function(event){
event.preventDefault();
var my_href = $(this).attr('href');
$.ajax({
url: my_href,
dataType:"html",
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
return false;
});
But this isn't a really nice coding style.. I would suggest to use html5 data- attribute to store your id value
echo "<td><a id='delete' data-id='".$row[0]."' href='#'>Delete</a></td>";
You can also use javascript:; instead of # if you don't want your url to change..
And your JS should be like:
$("#delete").click(function(event){
// you can avoid preventing default behaviour because your anchor doesn't have any href value
var del_id= $(this).data('id');
$.ajax({
url: "delete_back.php",
dataType:"html",
data: {id: del_id} // use object for better reading
success:function(msgStr){
$("#delete_msg").html(msgStr);
}
});
});
I also suggest you to check .done() construct LINK and deferred.done()
I believe that the delete link is coming from a loop containing other delete links too. If so, this is what you should do.
echo '<td><a class="lnk-delete" href="#" data-id="'.$row[0].'">Delete</a></td>'; //The delete links should have 1 class name
Then make your ajax call
$('.lnk-delete').click(function(e){
var id = $(this).data('id');
ajax({
url: 'delete_back.php'
data: {id: id},
type: 'POST',
success: function(data){
$('#delete_msg').html(data);
}
});
});
Get the id of the item you want to delete in php
$id = $_POST['id'];
<?php
//select_back.php
echo "<td><a id='delete' href='#'>Delete</a></td>";
?>
<input type="hidden" id="hidden_id" name="id" value="<?php echo $row[0]; ?>">
<script>
$("#delete").click(function(event){
event.preventDefault();
var hidden_id =$("#hidden_id").val();
$.ajax({
type:'GET',
url:"delete_back.php",
data:"id="+hidden_id,
success:function(data){
if(data.trim() == 'success')
{
$("#delete_msg").html("<div style='color:green;'>deleted successfully</div>");
}else{
//error
}
}
});
});
</script>
<?php
// delete_back.php
$id=$_GET['id'];
include("config.php");
$data=mysqli_query($con,"delete from student where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "Delete Error";
}
?>

Uncaught ReferenceError: $_POST is not defined

I'm new in AJAX and want to send 2 IDs on an AJAX page here is my code
Click Here
<script>
$(document).ready(function() {
$(".edit3").click(function() {
var moduleID = $(this).attr('id');
var studentID = $_POST['studentAssignID']; //Problem is Here
$.ajax({
type: "POST",
url: 'assign-assignment-ajax.php',
data: "moduleID="+moduleID+"&studentID="+studentID,
success: function(data)
{
$("#editform2").html(data);
$("#editform2").show('slow');
}
});
});
});
I'm getting module ID by clicking on a href, while I also want student ID with it, which part i'm doing wrong?
try this :
var studentID = "<?php echo $_POST['studentAssignID']; ?>";
Declare 'StudentAssignID' in hidden field.
<input type='hidden' class="StudentAssignID" value="<?echo $_POST['studentAssignID'];?>">
Then Use This Value in Script.
<script>
.
.
var studentID = $('.StudentAssignID').val();
.
.
</script>

Div not updating on successful ajax request (works fine on first request)

I've header.php file in which I've code to do livesearch. In that search, I've directly included 'Add to Cart' button so that user can directly add products through search only.
I've Cart div in my header file in which I display number of items in cart.
Livesearch result is coming absolutely fine with add to cart button properly.
When for the first time I add any product into cart, that replaces value of cart in header file & also replaces 'Add to Cart' button to 'Added'.
When for the second time I add product to cart with the SAME SEARCH RESULT, it updates value of button to 'Added' but it doesn't update the value of cart in my header. So this is the issue.
Here's my code:
HEADER.PHP
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function()
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
return false;
});
$(document).delegate('.buynow','click', function(){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
var type= $('#type_'+productid).val();
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this,
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added';
$('#carttotal').empty();
$('#carttotal').replaceWith(option);
}
});
return false;
});
});
</script>
<div id='carttotal'><input type='button' class='button' id='cartdetails'
value='<?php echo "Cart&nbsp(".$proInCart.")"?>' style='padding:7px;
border-radius:15px;'></div>
For an example if I search for 'he' it displays 14 results. For first result, if I click on 'Add to Cart' button, it changes the value of this button to 'Added' & update the Cart div. But from second request with the same search result, it doesn't update the cart however it updates the value of button to 'Added'.
Why is that? Can anyone help?
The reason your code is not working after the first request is that you are returning false at the end of the functions.
You should change your function into something like:
<script type="text/javascript">
$(document).ready(function()
{
$(".searchproductbrand").keyup(function(e)
{
var kw = $(".searchproductbrand").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "livesearch.php",
data: "kw="+ kw,
success: function(option)
{
$("#livesearch").show();
$("#livesearch").html(option);
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
});
}
else
{
$("#livesearch").html("");
document.getElementById("livesearch").style.border="0px";
}
e.preventDefault();
});
$(document).delegate('.buynow','click', function(e){
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
var type= $('#type_'+productid).val();
$.ajax({
type: "POST",
url: "db_addtocart.php",
context: this,
data: {quantity:quantity,
type:type,
productid:productid},
success: function(option){
this.value = 'Added';
$('#carttotal').empty();
$('#carttotal').replaceWith(option);
}
});
e.preventDefault();
});
});
</script>

getting values from textbox using jquery [output via php variable]

main.php:
<SCRIPT type="text/javascript">
$("#btnSubmit").click(function () {
alert("What will i put here!");
});
</SCRIPT>
<input type = "submit" id = "btnSubmit" value = "Try IT!" />
<div id = "show_search2">
</div>
output.php:
<?php $val = $_POST['btnSubmit'];
echo "<H1>$val</H1>"; ?>
What specific jQuery functionality can get the value of the btnSubmit and access it through $_POST and output it to the div show_search2? I used prototype.js but it provides conflict with my other JS scripts in the index.
Note: all my script source is included in index and that's why I didn't include the source in this post.
Do you mean something like this:
$("#btnSubmit").click(function (e) {
e.preventDefault();
var submitVal = $(this).val();
$.ajax({
type: "POST",
url: "url_of_your_output.php",
data: {btnSubmit : submitVal},
success: function(response) {
$("#show_search2").html(response); //response from output.php
}
});
});

Submitting form with jQuery

Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.

Categories