I am posting this questions due to the previous one being so long (It might create confusion if I cut parts up in it). I made the question more simple in this post :).
jQuery code:-
function op_prof(id) {
var attr_u_search = $(".u_search").attr('id');
var dataString = 'u_search=' + attr_u_search;
alert(dataString);
$.ajax({
type: "POST",
url: '/script/profile.php',
data: dataString,
cache: false,
success: function(data) {
$('#ui_profile').show();
$('#ui_profile').html(data);
location.hash = 'profile' + 'id=' + dataString;
$(".searchbox").val('');
$("#usr_suggest").hide();
}
});
};
PHP:-
echo "<tr id='" . $id . "' class='u_search' height='40px' onclick='javascript:op_prof(1)'><td width='40px'><img class='avatar' src='$avater' /></td><td>" . $fname_ . " " . $lname_ . "</td></tr>";
}}
I am having trouble retrieving the ID of each div (each one has a unique ID). It seems that the jQuery captures the ID of the div on top (the first div) instead of capturing the IDs of all the divs.
Screen shots:-
http://prntscr.com/118dhv
http://prntscr.com/118dus
P.S: I am 100% sure that there is an error in the jQuery :-> prntscr.com/118eb5
Try to modify the on-click attribute of tr
From this:
onclick='javascript:op_prof(1)
To this:
onclick='javascript:op_prof(this)'
And the js to this:
function op_prof(obj) {
var attr_u_search = obj.id;
....
Since you're using jQuery already, here's a full jQuery solution:
$("tr.u_search").on("click", function() {
var attr_u_search = $(this).attr('id');
var dataString = 'u_search=' + attr_u_search;
alert(dataString);
$.ajax({
type: "POST",
url: '/script/profile.php',
data: dataString,
cache: false,
success: function(data) {
$('#ui_profile').show();
// $('#ui_profile').html(data);
location.hash = 'profile' + 'id=' + dataString;
$(".searchbox").val('');
$("#usr_suggest").hide();
}
});
};
Is first param of 'ob_prof' always = 1?
javascript:op_prof(1)
The attr() method sets or returns attributes and values of the selected elements.
When this method is used to return the attribute value, it returns the value of the FIRST matched element.
use $.each()
api.jquery.com/jQuery.each/
Related
I would like to onsubmit, fetch the positioning of all the divs on the page and return the ids of the divs and the absolute positioning values.
This is the result I get in the console of how the array looks:
[Object { name="app1", coord="10,10"}, Object { name="app2", coord="60,10"}]
One, am I populating the array correctly? Two, how can I print it and return a string via result?
HTML page:
var apps = $(".block"),
positions = [];
$.each(apps, function (index, app) {
var positionInfo = $(app).position();
var input = $(this).attr('id');
var lines = input.split('_');
var appname = lines[0];
positions.push({value: appname + "," + positionInfo.top + "," + positionInfo.left});
console.log(appname + ":" + positionInfo.top + ":" + positionInfo.left);
});
$.ajax({
type: 'post',
cache: false ,
url: 'result_savechange.php',
data: {result:positions},
success: function(resp) {
$('#mainCanvas').html(''); // Clear #content div
$('#mainCanvas').append(resp);
}
});
PHP page:
<?php
$string = '';
foreach($_POST["result"] as $position){
$string .= $position['value'];
}
echo $string;
?>
There's no reason to use JSON here. It's overkill for this scenario. Just do this:
$.ajax({
type: 'post',
cache: false ,
url: 'result_savechange.php',
data: {result: positions},
success: function(resp) {
alert(resp);
}
});
Then in PHP, $_POST["result"] will be an array.
foreach($_POST["result"] as $position){
echo $position['name'];
echo $position['coord'];
}
I need to serialize two forms in the same ajax function with one call. I have tried the following but it just serialize the last one.
function sssssss2(page){
var form1 = document.myform1;
var form2 = document.myform2;
var dataString1 = $(form1).serialize() + '&page=' + page;
var dataString2 = $(form2).serialize() + '&page=' + page;
$.ajax
({
type: "GET",
url: "load_data.php",
data: {dataString1, dataString2}
success: function(ccc)
{
$("#container").html(ccc);
}
});
}
It doesn't work. How may I serialize both of them within the same function?
Try this one
var dataString1 = $(form1).serialize() + '&page=' + page +$(form2).serialize();
data: {dataString1}
I have been trying to get the id of a clicked div of same classes but with different IDs. I tried everything I know.
Here is one code I tried (in this one, the .click function() does not work .. edit: meaning it does not seem to run the code when clicked at all!):-
$(".u_search").click(function() {
var attr_u_search = $(this).attr('id');
var dataString = '&u_search=' + $(".u_search").attr('id');
alert(dataString);
$.ajax({
type: "POST",
url: '/script/profile.php',
data: dataString,
cache: false,
success: function(data) {
$('#ui_profile').show();
$('#ui_profile').html(data);
location.hash = 'profile' + 'id=' + dataString;
$(".searchbox").val('');
$("#usr_suggest").hide();
}
});
});
PHP:-
echo "<tr id='" . $id . "' class='u_search' height='40px'><td width='40px'><img class='avatar' src='$avater' /></td><td>" . $fname_ . " " . $lname_ . "</td></tr>";
}}
Here is another combination of codes I tried (error in this one: suppose I have 5 divs, and even if I clicked the 2nd div or the 3rd div, it only captures the id of the first div [div 1] and not the clicked div. I want to be able to capture the id of the clicked div.):-
$(".u_search").click(function() {
var attr_u_search = $(".u_search").attr('id');
var dataString = '&u_search=' + $(".u_search").attr('id');
alert(dataString);
$.ajax({
type: "POST",
url: '/script/profile.php',
data: dataString,
cache: false,
success: function(data) {
$('#ui_profile').show();
$('#ui_profile').html(data);
location.hash = 'profile' + 'id=' + dataString;
$(".searchbox").val('');
$("#usr_suggest").hide();
}
});
});
PHP:-
echo "<tr id='" . $id . "' class='u_search' height='40px' onclick='javascript:op_prof(1)'><td width='40px'><img class='avatar' src='$avater' /></td><td>" . $fname_ . " " . $lname_ . "</td></tr>";
}}
edit: when I use the first code (the one with .click function()) the code does not seem to run at all! .. I am using jquery library version 1.9.1
Inside your function change
$('.u_search').attr('id')
To
$(this).attr('id')
The quotes are important, but this is not inside quotes ;)
When you do
$(".u_search").click(function() {...
your callback function has now an object called this. You can use it to get the actual object you've clicked. So in this case, if you want to get the ID of the clicked object, simply do this:
var the_id = $(this).attr("id");
Inside a function, you can reference to the active jquery object by using $(this)
$(".u_search").click(function() {
...
//get ID of button being clicked upon
//Jquery Solution
$(this).attr('id');
//Or Javascript
this.id;
...
}
$("div").on("click",function(){
var id = this.id; //returns id
});
var attr_u_search = $(this).attr('id');
var dataString = '&u_search=' + $(".u_search").attr('id');
You're selecting every u_search div again to build your datastring, instead of using the already fetched id:
var attr_u_search = $(this).attr('id');
var dataString = '&u_search=' + attr_u_search;
i think it's : $(this).attr('id')
You need use $(this) to have the object that clicked..
var attr_u_search = $(this).attr('id');
var dataString = '&u_search=' + attr_u_search; // it's better !
Try this :
$('body').on('click', '.u_search', function() {
var attr_u_search = $(this).attr('id');
var dataString = '&u_search=' + attr_u_search;
alert(dataString);
// REST OF CODE
});
(Tested and working, if it still does not work, the issue might be somewhere else)
$('body').delegate('.u_search', 'click', function() {
var attr_u_search = $(this).attr('id');
var dataString = '&u_search=' + attr_u_search;
alert(dataString);
});
I'm working on an existing script at the moment which uses Ajax, something I've never worked with before. I have a variable set in my javascript file which gets its value from an input field on my page. I need to use Ajax to post this to my PHP page only I've no idea where to start,
Im not sure what code you would need to see, but My javascript/AJAX code is, the variable I need to pass is 'var credoff'
$(".getPoint").click(function () {
var theid = $(this).attr("id");
var onlyID = theid.split("_");
var onlyID = onlyID[1];
var credoff = parseInt($(this).children('input.credoff:hidden').val());
$.ajax({
url: 'do.php',
type: 'POST',
data: "userID=" + onlyID,
success: function (data) {
if (data != "success1" && data != "success5") {
$("#" + theid).text(data);
} else {
$("#thediv_" + onlyID).fadeOut("slow");
$('#creditsBalance').fadeOut("slow");
newbalance = parseInt($('#creditsBalance').text());
Wouldit have to be in this format?
data: "userID=" + onlyID,
"credoff=" + credoff
...
data: {
userId: onlyID,
credoff: credoff
},
...
Or you can do this:
data: "userID=" + onlyID + "&credoff=" + credoff
don't forget the ampersand! &
I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.
This is the jQuery:
$(".vote_up").click(function(){
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
$(".votes_up").find(id).html(data[x].vote_up);
$(".votes_down").find(id).html(data[x].vote_down);
}
}
});
});
So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?
This is the PHP for reference:
$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
$output[] = Array(
"vote_up" => $row['vote_up'],
"vote_down" => $row['vote_down'],
);
}
echo json_encode($output);
If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.
$.ajax({
context: this, // set the context of the callbacks
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data) {
// now "this" refers to the element that was clicked
}
You can test it by doing something a little more generic, like:
$(this).html("yep, it works");
... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.
Use .append() instead if you're appending data from the loop:
for(var x in data) {
$(this).append(data[x].vote_up);
$(this).append(data[x].vote_down);
}
Wouldn't:
$(".votes_up").find(id).html(...);
Really just need to be:
$('#' + id).html(..);
If you define a variable within the click() method callback, you'll be able to reference it within your ajax success callback. Something similar to this should do you:
$(".vote_up").click(function(){
// Assign the clicked element to a scoped variable...
var target = $(this);
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
// Then refer to it within your callback
target.html(data[x].vote_up);
target.html(data[x].vote_down);
}
}
});
});