how to create an function using jquery live? - ajax

I am writing a function that well keep the user in lightbox images while he adds to cart.
When you click any image it well enlarge using lightbox v2, so when the user clicks the Add image, it will refresh the page. When I asked about it at jcart support they told me to use jquery live, but I dont know how to do that. T tried this code but still nothing is happening:
jQuery(function($) {
$('#button')
.livequery(eventType, function(event) {
alert('clicked'); // to check if it works or not
return false;
});
});
I also used
jQuery(function($) {
$('input=[name=addto')
.livequery(eventType, function(event) {
alert('clicked'); // to check if it works or not
return false;
});
});
yet nothing worked.
for code to create those images http://pasite.org/code/572
I also tried:
function adding(form){
$( "form.jcart" ).livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}
});
return false;
}
and it seems to add to jcart but yet it still refreshes

.live() is to assign handlers to future creating elements. On your site, however, you are re-loading the page so .live would have no bearing. (you are submitting a form)
It sounds like you want to make an ajax request to add the item to the cart and update that display on the site? That would be in the submit of the form and if jcart is dynamically created then yes, live is the answer.
$('.jcart').live('submit', function() {
// aggregate form elements into object and send via ajax
// update the cart on the page, since we haven't reloaded the page the light box is still displayed
});
Regarding comment:
When you send an ajax request, jquery takes an object as an argument. Such as $.post('urlToPostTo.php', { title: 'title of whatever', id: 5 } );
The server sees this the same as:
<form id="myForm" action="uroToPostTo.php" method="POST" >
<input type="text" name="title" value="title of whatever" />
<input type="hidden" name="id" value="5" />
<input type="submit" name="submit" value="submit" />
</form>
So if you were to aggregate the form inputs into an object, there's a few ways (even some jquery plugins to help you out). The primitive way would be:
var $form = $('#myForm'); // instead of finding myForm over and over, cache it as a variable to use
var objToSend = {};
objToSend.title = $form.find('input[name=title]').val();
objTosend.id = $form.find('input[name=id]').val();
$.post( 'urlToPostTo.php', objToSend );
A more Elegant solution is to have something loop through all form elements and put them into an object for you. Plugins like http://docs.jquery.com/Plugins:Forms make that a bit easier.
The end result is the form elements are stuffed into an object to send to your script.

Related

sending form data through Jquery and AJAX is not working as expected

I have a form containing two submit buttons, i want it to update the current page as soon as i submit the form without refreshing the whole page, but the code keeps reloading the page and the page is not even updated.
HTML form
<form id="paymentForm" style="margin-left: 15%;margin-bottom: 15px;margin-top:15px;font-size: 18px;" action="#">
<input class="paymentButton" type="submit" name="COD" value="Cash on Delivery(COD)" style="background-color:#F80;color:white;height: 60px;border-radius: 5px ">
<input class="paymentButton" type="submit" name="POD" value="Paytm on Delivery(POD)" style="margin-left: 25px;background-color: #F80;color:white;height: 60px;border-radius: 5px">
Jquery and AJAX code
$(document).ready(function(){
$("#paymentForm").submit(function(e){
e.preventDefault();
var buttonpressed;
var paymentValue;
$("#paymentbutton").click(function() {
paymentValue = $(this).attr('value') ;
});
$.ajax({
url:"payment.php",
type:'POST',
data:"{
buttonValue:paymentValue;
}",
success:function(data){
getElementById('panel13').innerHTML=data;
}
});
return false;
});
});
PHP script payment.php where data is being sent
<?php
$paymentMode=""
if(isset($_POST["buttonValue"]==POD))
$paymentMode="Paytm On Delivery";
else
$paymentMode="Cash on Delivery";
echo "Your Order is placed succesfully with payment mode as" .$paymentMode;
?>
You have an syntax error in php code
$paymentMode="";
Youre mising semicolon... Next time, each time you send an ajax request. Turn on chrome dev tool -> network -> XHR to see what really haapen with your request. If request has failse. Click on request(i have red color) to see. back end error.. Hope this helpfull...
You are using getElementById, use document.getElementById instead. Hope it helps.

Ajax html response to div

Hi I am printing the ajax html response to div element and giving radio input option to select the file. after selecting the specific file the another div should show the message. but the ajax html response is not working
Jquery script:
$(document).ready(function()
{
$('#upload').ajaxForm({
beforeSubmit: function() {
$('#Analysis').show();
$('#Content_column').hide();
$('#file_list').show();
$('#trait').show();
$('#trait').html('Submitting...');
},
success: function(data) {
var $out = $('#file_list');
$out.html('&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFile list:');
$out.append('<div id="list">');
$('#list').html(data);
$out.append('</div>');
}
});
});
The output of this script is
<ul class="php-file-tree"><li class="pft-directory">Genotypic<ul><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/jquery.txt" />jquery.txt<br><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/marker.csv" />marker.csv<br></ul></li><li class="pft-directory">Other</li><li class="pft-directory">Penotypic<ul><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/namPheno.csv" />namPheno.csv<br><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/perl.pl" />perl.pl<br></ul></li></ul>
Jquery script:
$('#Penotypic').click(function() {
var $out1 = $('#trait');
$('#trait').show();
$out1.append('Submitted...');
});
this is not showing anything in the div trait. may be the html response is loading as a tesxt so the #Penotypic is not recognised. please help me to fix this.
Thanku
You have many inputs of id="Penotypic". Make every id unique or use classes as function trigger.
I wouldn't use "/" in the name attribute. See: http://www.w3.org/TR/html401/types.html#type-name
Then try if your ajax script does work. If it doesn't work, try if it works from static page (don't use your first jQuery script, but it's output as a static form). You probably need to bind your event trigger. Use jQuery's on().

Strange issue with ajax POST

I have this html page with the form
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
</form>
And this is my javascript function to do the POST call
function post_comment(event,item_id)
{
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}}
Backend is done using Django and this is the return statement
data=simplejson.dumps(data)
return HttpResponse(data, mimetype='application/json')
The referral url is say "/xyz".
The thing is, after the form gets submitted, it is being automatically redirect to the "/status_comment/save" page instead of remaining on the same page.
I tried the get method and it works fine but not the POST method.
I tried debugging it, so changed the url in post call to the referral url, then it refreshs the page instead of doing nothing.
Also the alert() command inside the function above doesnt work, so its probably not being entered into.
Interesting thing I have noticed, when looking at the web developer console, the Initiator for the POST call in this page is being displayed as "Other" while the initiator for GET call and POST call (in other pages, where its working) is "jquery-1.8.0.min.js:2"
Any thoughts? Thanks...
First you really shouldn't try to capture the enter if you can avoid it. Use the submit binding. It makes everything more obvious and easier for your fellow developers (I bet I am not the only one who thought "What the heck is KeyCode 13?").
I'm wondering if perhaps being more explicit might help. Have you tried calling preventDefault and stopImmediatePropagation?
$('#form1').submit(function(evt) {
evt.preventDefault();
evt.stopImmediatePropagation();
// serialize and be AJAXy yada yada yada
If that doesn't work, or for some reason you prefer to handle capturing enter on your own, then you might want to have the above code in addition to your keydown handler. So it would be:
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
...
$('#form1').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function post_comment(event,item_id)
{
event.preventDefault();
event.stopImmediatePropagation();
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}
}
Start by getting rid of the onkeydown attribute from the input:
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" />
</form>
And then simply subscribe to the .submit() event of this form using jquery and perform the AJAX request in there. Don't forget to return false from it to ensure that the default action is canceled and the browser stays on the same page:
$('#form1').submit(function() {
var str = $(this).serialize(); // Gets all the filled details
$.post(this.action, str, function(data) {
alert(data);
});
return false; // <!-- that's the important part
});

How can I return an id value from a div already populated through ajax

I am having some difficulty passing a correct id function back to AJAX.
I'm creating a product bulletin generator that lets items to be added by their SKU code (which works fine). My problem is that when a bulletin is clicked on, a preview of that bulletin is loaded into a div and shows all products associated with that bulletin.
From inside those results, I am trying to add the ability to delete a product from the bulletin. The problem is that the value being passed back to AJAX belongs to the first product only. It won't send the value belonging to the particular item if it is any other item than the first one.
This is the code (belonging to main.php) that gets loaded via AJAX into a div and is looped with each product associated with a selected bulletin
echo "<form name='myDelForm'>
$news_gen_id<br>
<input type='hidden' id='delccode' value='".$news_gen_id."'>
<input type='hidden' id='deledit' value='".$edit."'>
<input type='button' onclick='ajaxDelCcode()' value='Delete' /><br></form>
</td>";
The AJAX code (on index.php, where the div that calls in main.php is also located) is this
function ajaxDelCcode(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new
ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxMain2");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var deledit = document.getElementById("deledit").value;
var delccode = document.getElementById("delccode").value;
var queryString = "?delccode=" + delccode + "&deledit=" + deledit;
ajaxRequest.open("GET", "main.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
Currently, using those two pieces of code, I can successfully delete only the first product. The delccode variables do not seem to change when the products are looped (although when I echo the variables during the loop, it is definitely changing to the appropriate value...it's just not passing it correctly back to AJAX.)
I tried taking the AJAX code, putting it inside the main.php product loop, and change the function name during each loop (so ajaxDelCcode$news_gen_id() for example) and also to the button itself so that it is calling the AJAX specific to it. And it works if you are visiting main.php directly...but not from index.php after main.php has been called into the div.
I can't figure out how to pass the correct looped value from main.php within the div, back to the AJAX code on index.php
Can anyone help me with this?
Thanks,
Dustin
Instead of storing the id in the input, just pass it as an argument to the function:
function ajaxDelCcode(delccode) { ...
<input type='button' onclick='ajaxDelCcode(\"".$news_gen_id."\")' value='Delete' />
Also, I'd swap the quotes if I were you. Or better yet, instead of using echo, break the PHP code and just write HTML:
<? ... ?><input type="button" onclick="ajaxDelCcode('<?= $news_gen_id ?>')" value="Delete" /><? ... ?>
What does the code you use to delete look like? Is it in the same php file as the form you posted above? If so, is the form getting submitted to itself accidentally? Like perhaps when a user presses enter while on an input type=text control? I understand that you want to do this by ajax but I am suspecting that the form is your problem.
Seconding the jQuery comment.
Here try this
1) add jquery to your document.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
2) give your inputs name attributes
<input type='hidden' name='delcode' id='delccode' value='".$news_gen_id."'>
<input type='hidden' name='deledit' id='deledit' value='".$edit."'>
3) Use a function something like this instead of all that code above
function ajaxDelCcode() {
$.ajax({
url: "main.php",
type: "GET",
dataType: "text",
data: $("#myDelForm").serialize(),
success: function(rText) {
$("#ajaxMain2").text(rText);
}
});
}

API trouble with jQuery / AJAX

This is my second day with jQuery & AJAX. I've done as much googleing as I know to do for this. But, with not knowing what I'm looking for, I'm lost. This is very close to working, but I can't quite figure it out.
I'm trying to use my company's ("xyz") API, and it won't work when I have the form action = a url to the page.
I've done this many times in PHP. The APIs URL is:
xyz.com/getdata.php?from=tt&isbn={variable_int}
Can someone give me a hand?
<form method="post" action="xyz.com/getdata.php" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
<div id="result"></div>
{literal}
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
url = $form.attr( 'action' );
// Send the data using post and put the results in a div
// $.post( url, { doSearch: "Search", isbn: term } ,
$.post( url, { from: "tt", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).html( content );
}
);
});
</script>
Thanks so much (in advance)!
Cross-domain with an AJAX request is not as easy as it seems.
Here's an interesting link you should read: http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
I'm not sure but if you use the string below
xyz.com/getdata.php?from=tt&isbn={variable_int}
the method to send data is "get". The form uses the method "post". I think there is a conflict.

Resources