I made a moderation script, voting up and down question and answers. Time ago the script worked, but when i came back to start coding in this project one more time, it doesn't work anymore.
The script was doing: when you click in a div called vote, or vote1 a link, it ask if it's up or down. If it's up, it loads url: "mod_up_vote.php" sending by post some info about the question you are voting on. It was ok. But not now. It doesn't load that page, because i was printing and inserting in database the $_POST variable and nothing was there.
What do you think is wrong here? Thanks.
$(document).ready(function()
{
$(document).delegate('.vote, .vote1', '.vote2', 'click', function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='mod_up')
{
$(this).fadeIn(200).html('<img src="dot.gif" align="absmiddle">');
$.ajax({
type: "POST",
url: "mod_up_vote.php",
dataType: "xml",
data: dataString,
cache: false,
success: function(xml)
{
//$("#mod-pregunta").html(html);
//$("#mod-respuesta").html(html);
//parent.html(html);
$(xml).find('pregunta').each(function(){
var id = $(this).attr('id');
var pregunta = $(this).find('preguntadato').text();
var respuesta = $(this).find('respuestadato').text();
var votoup = $(this).find('votoup').text();
var votodown = $(this).find('votodown').text();
var id_pregunta = $(this).find('id_pregunta').text();
var id_respuesta = $(this).find('id_respuesta').text();
$("#mod-pregunta").html(pregunta);
$("#mod-respuesta").html(respuesta);
//$(".vote").attr('id', $(this).find('id_pregunta').text());
$(".vote1").html("Aceptar");
$(".vote2").html("Rechazar");
//$("span", this).html("(ID = '<b>" + this.id + "</b>')");
});
} });
}
return false;
});
This looks like a problem with your JQuery. Why are you using delegate instead of click? Also, your arguments to delegate appear to be incorrect. If you look at the documentation you'll see the function signature is:
$(elements).delegate(selector, events, data, handler); // jQuery 1.4.3+
You are binding your function to an event called '.vote2', which I can only assume does not exist.
Try using click instead, there's no reason to use delegate as far as I can tell.
edit:
Try using click like so:
$('.vote, .vote1').click(function(){ /* your code here */ });
Related
I have written this code but it didn't work. I have searched so much but those code are not properly work. what should I do? I want to fetch data without refreshing whole page.
I have looked at this other question.
$(document).ready(function() {
$("#pair_form").submit(function(e) {
e.preventDefault();
var devicename = $("#devicename").val();
var id = $("#id").val();
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var ignition = $("#ignition").val();
var Arming = $("#Arming").val();
function showData() {
$.ajax({
url: 'http://example.com/ddd/cfg.php',
method: 'get',
dataType: 'text',
success: function(response) {
$('#result').html(response)
}
});
}
});
});
I have done some reading and I think i need to use json for this. I have never used this before. I am trying to accomplish this, but in jQuery
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//stop and make user write something else
} else {
//keep going
}
I am switching my website over from php to jQuery, which is also very new to me but seems so much better. Here is a piece of my jQuery. I am validating a form. The form works and submits, but now i want to see if the email exists in my database before submission. How would i do this?
if (email == "") {
$("#error5").css("display", "inline");
$("#email").focus();
return false;
}
// Im guessing the new code would go here
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
url: action,
data: dataString,
success: window.location.assign("cashcheck_order.php")
});
This is a basic ajax call using jquery
var thing1; //thing 1 to use in js
var thing2; //thing 2 to use
var form = ("#acc_form"); //localize the form to a variable. you don't need to keep looking it up
var dataString = form.serialize();
var action = form.attr('action');
$.ajax({
url: action,
data: dataString,
type: "post",
success: function(data){
var responseData = $.parseJSON(data); //json native decoding if available, otherwise will do it with jquery
thing1 = responseData["thing1"];
thing2 = responseData["thing2"];
},
error: function(data){
console.log("error", data);
}
});
On the php side, to bring the vars in you use
$input1 = isset($_GET["name_of_input1"]) ? $_GET["name_of_input1"] : "";
if this is set, set this value, else set blank.
you can use $_POST, $_REQUEST if you prefer.
do not forget to sanitize your inputs.
Now to send it back to the js file
$dataToReturn = [
"thing1"=>"I'm thing 1",
"thing2"=>"I'm thing 2"
];
//sending back data
echo json_encode($dataToReturn);
I am trying to pass in mutliple data into AJAX .post(). This is what I've done so far:
$('form#tutorTableForm').live('submit', function()
{
var cid = $('#courseSelect').val();
var lid = $('#lessonSelect').val();
var lessonCount = $('#lessonSelect option:selected').attr('id');
$.post('', $(this).serialize(), function(response){
alert(response);
});
return false;
});
I want to also pass in cid and lid. How would I do that?
I'm using live instead of on because our app is using the old version.
I guess you could create an object that contains all the data, like this:
var cid = $('#courseSelect').val();
var lid = $('#lessonSelect').val();
var lessonCount = $('#lessonSelect option:selected').attr('id');
var postdata = {
formdata: $(this).serialize(),
cid: cid,
lid: lid
};
$.post('', postdata, function(response){ alert(response); });
place them inside the form as input hidden or whatever and the serialize should add them automatically. without seeing your html it's a bit difficult to see exactly what you need.
I have a simple toggle button that the user can use to either subscribe or unsubscribe from a group they belong to. I have 2 forms that get the post and depending on which page the form posts to, the user is subscribed or unsubscribed. Here's my code and I'm looking for a better way to do this. Currently, my user can click to subscribe or unsubscribe but he or she will have to reload the page to change their setting. In other words, it works fine but there's no toggle...users can't click back and forth between subscribe and unsubscribe, as they have to refresh the page and resubmit. I also would love to fix the toggle function. Thanks for any help.
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataString,
success: function(){
$("#subscribe").removeClass("notifications_subsc");
$("#subscribe").addClass("not_subscribed_group");
}
});
});
});
</script>
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#notsubscribed").click(function(){
$.ajax({
type: "POST",
url: "groupnotificationsoff.php",
data: dataString,
success: function(){
$("#notsubscribed").removeClass("not_subscribed_group");
$("#notsubscribed").addClass("notifications_subsc");
}
});
});
});
</script>
There's no need to rely on parsing out the query string when server-side scripting is available. Instead, when the page is initially served, arrange for PHP to write the group_id value into (eg.) a hidden input field, which then becomes available client-side to be read into javascript/jQuery. (Other techniques are available)
It's also a good idea to arrange for your "groupnotifications.php" script to receive a $_POST['action'] instruction to either subscribe or unsubscribe. That way the client-side half of the application exercises control.
With those changes in place, the code will be something like this:
$(function() {
$("#subscribe").click(function(){
var $s = $(this).attr('disabled',true);//disable button until ajax response received to prevent user clicking again
var clss = ['not_subscribed_group','notifications_subsc'];//The two classnames that are to be toggled.
var dataOj = {
owner : $s.closest(".groupContainer").find('.group_id').val(),//relating to element <input class="group_id" type="hidden" value="..." />
action : ($s.hasClass(clss[0])) ? 1 : 0;//Instruction to 1:subscribe or 0:unsubscribe
};
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataObj,
success: function(status) {//status = 1:subscribed or 0:unsubscribed
switch(Number(status)){
case 1:
$s.removeClass(clss[1]).addClass(clss[0]);
break;
case 0:
$s.removeClass(clss[0]).addClass(clss[1]);
break;
default:
//display error message to user
}
}
error: function(){
//display error message to user
}
complete: function(){
$s.attr('disabled',false);
}
});
});
});
untested
Note: The statement $s.closest(".groupContainer").find('.group_id').val() relies on the hidden input element having class="group_id" and allows for multiple groups, each with its own toggle action, on the same page. Just make sure each group is wrapped in an element (eg div or td) with class="groupContainer".
I am implementing a twitter-style follow/unfollow functionality with the following jquery.
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
I have a similar unfollow function. However i have the following problem:
When I have N items {1,2..i.N} each with id = followi and I click on the follow button. I find that some of the items respond while others do not. I suspect it is a pure javascript issue...otherwise i figure none of the buttons would respond at all.
Is it a timing issue...all help is appreciated. Also i'd appreciate it if you could point me to a simpler method.
Thanks!
Well you are doing the UI update in your ajax success handler, so the reaction time for the UI updated is based on the speed of the Ajax response. And if the server doesn't return successfully, the UI update won't happen at all.
A simpler method with instant response:
$(function() {
$(document.body).delegate(".follow","click",function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif"/>');
$('#follow'+I).fadeOut(200); // act instantly since we assume it will go well
$('#remove'+I).fadeIn(200); // act instantly since we assume it will go well
$.ajax({
type: "POST",
url: "follow.php",
data: info,
complete: function(){ //always remove the loader no matter if it goes well or not
$("#loading").slideUp();
},
error: function() {
//handle error
$('#follow'+I).fadeIn(200); // correct mistake
$('#remove'+I).fadeOut(200); // correct mistake
}
});
return false;
});
});