Change text of Ajax post return - php

I have a loop:
do {
// show items
<input type="hidden" id="contestant_id" value="'.$row_contestants['contestant_id'].'">
<input type="hidden" id="user_id" value="'.$userinfo['user_id'].'">
<button class="vote" onclick="vote()">vote</button>
<div id="result"></div>
} while ($row....);
And my function:
function vote () {
var val1 = $('#contestant_id').val();
var val2 = $('#user_id').val();
$.ajax({
url:"vote.php",
type: "POST",
data: { contestant_id: val1, user_id: val2 },
success: function(response) {
$('#result').html(response);
}
});
}
What I want to do is have the "vote" text from here:
<button class="vote" onclick="vote()">vote</button>
change to something else like "voted!" when I get the response. I sort of had it but of course it's showing here:
<div id="result"></div>
And it's only showing under the 1st result of my loop.
Any ideas?
Thanks.

You can pass this from html to function and handle in the script
<button class="vote" onclick="vote(this)">vote</button>
function vote (el) {
var val1 = $('#contestant_id').val();
var val2 = $('#user_id').val();
$.ajax({
url:"vote.php",
type: "POST",
data: { contestant_id: val1, user_id: val2 },
success: function(response) {
$('#result').html(response);
if (response == 'Yes') {
var text = el.text();
var values = text.split(' ');
var count = 1;
if (values.length == 2) {
count = values[1].parseInt + 1;
}
el.text('Voted ' + count);
}
}
});
}

Related

How to create jquery array from ajax data?

I wanna create array from ajax response. I took array from ajax and i have to create dynamic data for chips
materializecss autocomplete
response from ajax
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});
}
});
$('.chips-placeholder').chips({
placeholder: lang_('Your tag'),
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
// I need data like this from response
data: {
'Google', null
'Googol', null
},
limit: 5,
minLength: 2
}
});
<div class="chips chips-placeholder chips-autocomplete input-field" style="background:#fff">
<input class="input tags" placeholder="tag" autocomplete="off" />
</div>
that's my code
Finally, thanks to #Vel to find right answer.
jsfiddle - work code
You need to do like this.
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
/*$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});*/
// ['google', 'googol'] <- this array I take from ajax
tag = ['google', 'googol'];
var obj = {};
$(tag).each(function (index, value) {
obj[value] = null;
});
$('.chips').chips({
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
data:obj,
}
});
}
});
fiddle link

AJAX live search working with radio button

I'm able to get jQuery AJAX live search working on an input field and it returns the desired result that I want.
for example : Search for my word returns the desired result .
But Now I want to do a compound search on two fields.
for example :
Search for the word + today
or
Search for the word + tomorrow
This is what I have but it is not working or does not returning any errors.
index.php
<form>
<input placeholder="Search the area" class="input-large search-query" type="text" id="key">
<input type="radio" name="b_selected" class="radio" value="1" > Today
<input type="radio" name="b_selected" class="radio" value="2" > Tomorrow<br>
<div class="result"><div class="loading"></div></div>
</form>
quicksearch.php
include('config.php');
$count= 0;
if(isset($_POST["b_selected"]))
{ $b_selected = $_POST['b_selected']; }
$key = $_POST['key'];
$b_selected = $_POST['b_selected'];
$key = addslashes($key);
$sql = mysql_query("select * from account WHERE b_today='1' and title LIKE '%$key%' ") or die(mysql_error());
While($row = mysql_fetch_array($sql)) {
$count++;
$id= $row['id'];
$title=$row['title'];
if($count<= 10){
search.js
/*quick search*/
$(document).ready( function() {
$(".result").hide();
$("#key").keyup( function(event){
var key = $("#key").val();
if( key != 0){
$.ajax({
type: "POST",
data:{ key: key },
url:"quicksearch.php",
success: function(response) {
$(".result").slideDown().html(response);
}
})
}else{
$(".result").slideUp();
$(".result").val("");
}
})
})
/* Search for work plan for today or Tomorrow*/
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var b_selected = $(this).val();
$.ajax({
url:"quicksearch.php",
method:"POST",
data:{b_selected:b_selected},
success:function(data){
$('#result').html(data);
}
});
});
});
You should POST both variables - the word plus the value of the radio-button. If you POST only the word or only the radio-button - you won't get what you want:
$(document).ready( function()
{
$(".result").hide();
/*quick search*/
$("#key").keyup( function()
{
var key = $(this).val();
var b_selected = $('input[type="radio"]').val();
$.ajax({
method: "POST",
url: "quicksearch.php",
data:
{
key: key,
b_selected: b_selected
},
success: function(response)
{
$(".result").slideDown().html(response);
}
});
});
/* Search for work plan for today or Tomorrow*/
$('input[type="radio"]').click(function()
{
var key = $('#key').val();
var b_selected = $(this).val();
$.ajax({
method: "POST",
url: "quicksearch.php",
data:
{
key: key,
b_selected: b_selected
},
success: function(response)
{
$('#result').slideDown().html(response);
}
});
});
})

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

Select2 in a complex form as abstract class

I need to use the select2 object in my form. This is my form
http://i.stack.imgur.com/jVILq.jpg
There are many select html objects.
For instance If I would like to change the Customers select box into a Select2 object I have written this little snipped of code posted at jsfiddle.net but I cannot create a copy of this function for each select because it too difficult to maintain.
How have I to abstract it?
I have posted a sample here: http://jsfiddle.net/GcJgU/7/
I have already found a potential solution from the user Flip but it is not complete because I need to apply this JQuery object to all the input hidden html objects in the page.
This is an example:
$(".select2").select2({
ajax: {
url: $(this).attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = $(this).attr("field-id");
var fieldname = $(this).attr("fields-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
formatResult: function (object, container, query) {
console.log(object);
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = $(element).attr("field-id");
var fieldname = $(element).attr("fields-data");
$.ajax($(element).attr("url-searchid") + "/term/" + id, {
dataType: "json"
}).done(function (items) {
var data = {
id: items[0][fieldid],
text: items[0][fieldname]
};
callback(data);
});
}
});
Seems that $(this).attr("url-search") is not read and the search process doesn't start. I don't understand why.
Thanks guys
function select2Factory(select2) {
return {
minimumInputLength: 3,
ajax: {
url: select2.attr("callback-url"),
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var $this = $(this);
var id = select2.attr("field-id");
var fieldname = select2.attr("field-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var fieldname = select2.attr("field-data");
$.ajax("/admin/customers/searchbyid/term/" + id, {
dataType: "json"}).done(function(items) {
var data = {id: items[0][fieldid], text: items[0][fieldname] };
callback(data);
});
}
}
}
$el = $("#customer_id");
$el.select2(select2Factory($el));
I have solved in this way thanks to Flip:
http://jsfiddle.net/GcJgU/10/
HTML:
<input type="hidden" id="customer_id" title="" required="1" class="form-control select2 select2-offscreen" url-searchid="/admin/customers/searchbyid" url-search="/admin/customers/search" fields-data="lastname firstname ( company )" field-id="customer_id" value="12" name="customer_id" tabindex="-1">
JQUERY:
function select2Factory(select2) {
return {
ajax: {
url: select2.attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = item[mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
results.push({
id: item[id],
text: output
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
$.ajax(select2.attr("url-searchid") + "/term/" + id, {
dataType: "json"}).done(function(items) {
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = items[0][mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
var data = {id: items[0][fieldid], text: output };
callback(data);
});
}
};

AJAX Post two id

can I send two id in ajax post? can i make like this? but this script not work..
<a href='#' class='plyshr' id1="<?php echo $tracks['track_id']; ?>" id2="<?php echo $row[2]; ?>">
<?php echo $row[2]; ?>
</a>
and in AJAX
some more details
$(document).ready(function(){
$(".plyshr").click(function () {
var id = $(this).attr("id");
var dataString = 'id1=' + id1;
var dataString = 'id2=' + id2;
var parent = $(this);
$.ajax({
type: "POST",
url: "playlist.php",
data: dataString,
cache: false,
success: function (html) {
parent.html(html);
}
});
return false;
});
});
Assuming rest of the code is working.
var id1 = $(this).attr("id1"); // Get the first id.
var id2 = $(this).attr("id2"); // Get the second id.
var dataString = 'id1='+ id1 ;
dataString += '&id2='+ id2 ; // Set both in string with & separtor
var id1 = $(this).attr('id1'),
id2 = $(this).attr('id2'),
dataString = 'id1='+ id1 ;
dataString += '&id2='+ id2 ;
Why are you using custom attributes, you can use data attribute, like
<a href='#' class='plyshr' data-id1="<?php echo $tracks['track_id']; ?>"
data-id2="<?php echo $row[2]; ?>">
<?php echo $row[2]; ?>
</a>
SCRIPT
$(".plyshr").click(function () {
var self=this;
var parent = $(this);
$.ajax({
type: "POST",
url: "playlist.php",
// use jquery data function here
data:{id1: $(self).data('id1'),id2:$(self).data('id2')},
cache: false,
success: function (html) {
parent.html(html);
}
});
return false;
});

Categories