jQuery AJAX referencing $(this) within success function - php

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);
}
}
});
});

Related

How to pass foreach data to ajax

I have stored two JSON arrays in local storage i.e,
viewbody=>json data1 , viewcollar=>json data2. I am fetching these arrays in foreach loop from local storage with data name attribute dynamically. But am not able to pass two arrays data to php ajax. Kindly help me, someone.
Below is my code,
$(document).on('click','.startDesignbtn', function() {
var product_id = $(this).data("id");
$(".getoption").each(function(){
var option_name = $(".getoption").data("name");
// alert(option_name);
var views = localStorage.getItem("view"+option_name);
});
$.ajax({
url: 'index.php?route=product/design/designMultiImage',
type: 'post',
//dataType: 'text',
data:{
'product_id': product_id,
'views' : views,
},
success: function(data) {
alert(data);return false;
var intValArray = data.split(',');
var count = 0;
$.each(intValArray,function(i){
localStorage.setItem("view_"+count,intValArray[i]);
count++;
});
localStorage.setItem('design-image',data);
localStorage.setItem('parent-id',product_id);
// var custom_link = data;
window.location = "<?php echo $customize_link;?>";
}
});
});
Use array.push() to append values to an array. Also, you need to define the array outside of the each loop otherwise you reset it every time. Also, inside the loop, use $(this) as opposed to targeting the element by class. Fixed your click function below:
$(document).on('click','.startDesignbtn', function() {
var product_id = $(this).data("id");
var views = [];
$(".getoption").each(function(){
var option_name = $(this).data("name");
// alert(option_name);
views.push("view"+option_name);
});
$.ajax({
url: 'index.php?route=product/design/designMultiImage',
type: 'post',
//dataType: 'text',
data:{
'product_id': product_id,
'views' : views,
},
success: ...

How to output json array value in ajax success?

I have post the data and return the value with json_encode and get that in ajax success stage. but i can't out that data value in specific input. Here is my html input. The return value are show in console and alert box as below.
{"status":"0","data":[{"user_id":"1","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"\u304a\u306a\u307e\u30481"},{"user_id":"31","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"uchida"}]}
<input type="text" id="admin_id" class="form-control">
Here is my ajax
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
alert(result);
}
});
}
Use JSON.parse to get specific input from result
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
var obj = JSON.parse(result);
alert(obj.status);
//alert(result);
var user_id = [];
var start_time = [];
for (i = 0; i < obj.data.length; i++) {
user_id[i] = obj.data[i].user_id;
start_time[i] = obj.data[i].start_time;
}
alert(' First user '+user_id[0]+' Second User '+ user_id[1]+' First start_time '+start_time[0]+' Second start_time '+ start_time[1] );
}
});
}
Use a each loop to get the ids,result is a object that has a data array:
$.each(result.data,function(i,v){
console.log(v.user_id);
//$('.admin_id').val(v.user_id);//use val to append the value, note you have multiple ids so you need multiple inputs
});
if this doesn't work then you return a string not json so you need to convert it to json using:
var result = JSON.parse(result);
Read Following posts you will get idea about json parsing
Parse JSON from JQuery.ajax success data
how to parse json data with jquery / javascript?
and you can try looping like this
var parsedJson = $.parseJSON(json);
$(parsedJson).each(function(index, element) {
console.log(element.status);
$(element.data).each(function(k,v) {
console.log(v.user_id);
});
});
When in an AJAX callback, you can use result.data to access the array of objects being returned. You can work with these like you would any other Javascript object. You may need to deserialize the JSON first.
To accomplish what you're trying to do, the following code would do the trick, although it will only use the very first object in the array as you only have one text box.
var responseObj = JSON.parse(result);
document.getElementById('admin_id').value = responseObj.data[0].user_id;

How to capture id of clicked div - jquery

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/

When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database

I've been trying different options for over a week now and nothing seems to work. What makes this slightly more complicated is that I have multiple forms on the page that all need to be tied to this same submit function. They all have different IDs.
The following is a simplified version of my jQuery:
$('form').on('submit', function(form){
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
// The following fires on first AND second submit
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I have also tried using $('form').submit() with the same results.
Relevant sections of process.php:
$query = 'UPDATE pop_contents
SET ';
$id = $_POST['content_id'];
/* to avoid including in MySQL query later */
unset($_POST['content_id']);
$length = count($_POST);
$count = 0;
foreach($_POST as $col => $value){
$value = trim($value);
$query .= $col."='".escapeString($value);
// don't add comma after last value to update
if(++$count != $length){ $query .= "', "; }
// add space before WHERE clause
else{ $query .= "' "; }
}
$query .= 'WHERE id='.$id;
$update_result = $mysqli->query($query);
After much hair pulling and swearing, I've solved the problem.
TinyMCE editor instances do not directly edit textareas, so in order to submit the form, I needed to first call tinyMCE.triggerSave() from the TinyMCE API. So, the working code looks like this:
$('form').on('submit', function(form){
// save TinyMCE instances before serialize
tinyMCE.triggerSave();
var data = $(this).serialize();
$.ajax({
type: 'POST',
cache: false,
url: 'inc/process.php',
data: data,
success: function(){
console.log("Updates have successfully been ajaxed");
}
});
return false;
});
I was confused when i pass the Ajax String data via tinyMce ..but it is not save to database with php...then i use the
tinyMCE.triggerSave();
event.preventDefault();
then fine.........
$("#save").click(function() {
tinyMCE.triggerSave();
event.preventDefault();
var data = $(this).serialize();
var position = $("#position").val();
var location = $("#job_location").val();
|
|
|
|
var end_date = $("#end_date").val();
var dataString = '&position='+ position + '&job_location=' + location + '&job_category=' + category + '&job_des=' + job_des +'&job_res='+ job_res + '&job_requ='+ job_requ + '&start_date='+ start_date + '&end_date='+ end_date;
alert(dataString);
$.ajax({
type: "POST",
url: "regis.php",
data: dataString,
success: function(data){
}
});
return false;
});
i believe the problem is that you don't prevent the default action of the form. try this
$('form').bind( 'submit', function(event) {
event.preventDefault(); // added
console.log("Binding"); // changed to console.log
$.ajax({
type: "POST",
url: "inc/process.php",
data: $(this).serialize(),
success: function() {
console.log("Your updates have successfully been added."); // changed to console.log
}
});
});
Another neat trick to go along with this is setting the progress state on the tinymce editor, giving you a very simple way to add a loading icon. This article in the TinyMCE docs explains how to do that.
Also from that article, using ed.setContent() will allow you to set the text showing in the editor. I used it to blank the editor, but only after a successful post.

jQuery each() results to array to php to database

Basically what I am doing is making a sort of invitation system, the user clicks on users and they go into a list, that all works, I can get the ids of them using each() but I need to pass it through jQuery Ajax to php to send it to the database for notifications. This is basically what I have:
$(".group-video-create").click(function(){
var url = $(".group-input-url").val();
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var checked_url = url.match(exp,"<a href='$1'>$1</a>");
if(checked_url)
{
$("#group-input-names li").each(function(){ // This is the relevant code
var user_id = $(this).attr("id"); // Here too
}); // & here
if(user_id)
{
$.ajax({
type: "POST",
//url: "",
//data: "", //this would be an array of all of the ids, (could be 1, could be 100).
cache: false,
success: function(html){
///Once all invitations have been sent to the database it would then load a new div and hide the previous one.
}
});
}
}
});
if you want to see what I'm trying to accomplish just go here:
http://www.kithell.com/#/video
usr: PhpFreak#yahoo.com
pass: phpfreaklogin
It's under Group Video. (You should be automatically directed there once logged in)
You might be able to use jQuery.serialize to bundle up all of your form data. Also, jQuery.post is a nice shortcut for doing a POST request with jQuery.ajax.
A rough example might look this:
$.post( '/my-ajax-service.php',
$('#MyForm').serialize(),
function(data, txtStatus, jqXHR) {
//Do stuff
});
Here is one possibility
http://jsfiddle.net/nickywaites/9GZ2e/
$(function() {
//I would use jQuery Map to build Array
//http://api.jquery.com/map/
var ids = $("#group-input-names li").map(function() {
return $(this).attr("id");
}).get(); //Get Required to convert to regular javascript array
console.log(ids);
var invites = {}
invites.users = ids;
//Then use JSON.stringify() to pass array to server
//https://github.com/douglascrockford/JSON-js
if (ids.length > 0) {
$.ajax({
type: "POST",
//url: "",
data: JSON.stringify(invites),
cache: false,
success: function(html) {}
});
}
});

Categories