jQuery (this) as succession of jQuery Ajax? - php

In this script, I'm fetching a load of data from a MySQL aray, and adding in a little favourite button on each array of returned data, the code for that is
...php while code to fetch array...
...more output...
<a class="favlink" id="'.$row['id'].'">favourite</a>
..more output...
and from that, I've used this bit of jQuery to run a PHP script:
<script>
$(function() {
$(".favlink").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "fav.php",
success: function(data) {
alert('asf');
}
});
});
});
</script>
That works fine, but what I actually want to do, is change the success to something like this:
success: function(data) {
$(this).html("<font color='#ccc'><a href='#'>favourited</a></font>");
}
And, that didn't work!
Is there any way I can change the clicked favourite link to a different font color / and change the text from 'favourite' to 'favourited'?
I assume the 'this' property is no longer 'this' on success for some reason, but I'm not sure?
Thank You!

You have to define the context of the ajax. See the docs from Jquery site:
contextObject This object will be made the context of all Ajax-related
callbacks. By default, the context is an object that represents the
ajax settings used in the call ($.ajaxSettings merged with the
settings passed to $.ajax). For example specifying a DOM element as
the context will make that the context for the complete callback of a
request, like so:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
So in your's case I think this is what you need:
$.ajax({
url: "test.html",
context: this,//OR: $(".favlink")[0], // Depends on your scope.
success: function(){
$(this).html("<font color='#ccc'><a href='#'>favourited</a></font>");
}
});

Add the following line to the $.ajax parameters. By default the context is linked to the $.ajaxSettings of the request. Setting the below line changes the context of this in the ajax request to equal that of the calling method.
context: this,
So your new code will look like this:
<script>
$(function() {
$(".favlink").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "fav.php",
context: this,
success: function(data) {
$(this).html("<font color='#ccc'><a href='#'>favourited</a></font>");
}
});
});
});
</script>

$(function() {
$('.favlink').click(function() { // this may match more than one element
var $this = $(this);
$.ajax({
'type': 'GET',
'data': 'v=' + this.id,
'url': 'fav.php',
'success': function(data) {
$this.html('whatever you want');
}
});
});
});
You could also use the context parameter for jQuery.ajax, but I personally think this (hah!) is more readable.

Related

function loads only on change, i would it to load on document load

My knowledge of this is very limited, but I figured that the problem that I have is in this function. What it does is that it displays some options to be selected in an item post. From what I see it only loads when a category is changed. Because of that when you edit this post, this function will not display unless you change category to another one and then revert back to the one you want. I would like it to display every time, except for those categories that are in the if statement.
Please assist....
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function(){
if($(optgroups).children("option:selected").length){
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function(data) {
if(data) {
$("#condition-container").html(data);
}
}
});
}
});
});
You just need to trigger your change event on document load. So under you on change function put this code
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function () {
if ($(optgroups).children("option:selected").length) {
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function (data) {
if (data) {
$("#condition-container").html(data);
}
}
});
}
});
});
//Trigger change
$(document).ready(function () {
$("#catId").trigger("change");
});
hi I assume you want the function fired on document load and on change, but for that you will need to use 2 triggers.
1) you allready have the on change trigger
2) use the $(document).ready() (https://learn.jquery.com/using-jquery-core/document-ready/) wrapper for onload.
There is possibly a much more gracefull solution, but I'm no JS expert so this will only get you to a working, although not the pretiest state

Pass input value to ajax get Laravel

I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that

Change PHP Function Argument with AJAX

I'm trying to update information from a PHP function on the fly. I use a PHP function on my page:
main();
main() works like:
function main() {
global $news;
$news = api($news);
}
When someone clicks a different 'News' topic on my menu, I want to refresh main() with AJAX to reflect the new news category request. Racking my brain and Stack, I'm not sure where the slip up is. The AJAX request originates from this list:
<div class="mainleft">
<ul>
<li>World News</li>
<li>Sports</li>
</ul>
</div>
My JS looks like the following (adding the alert at the end to try and debug the variable):
$(document).ready(function() {
$(".mainleft > ul > li").click(function(){
$.ajax({
type: "POST",
url: "/includes/ajax.php",
data: $(this).text(),
success: function(msg){
alert($(this).text()); // this alert fires but the result is blank
}
});
});
});
ajax.php looks like:
if ($_POST) {
$news = $_POST;
}
I've tried GET with the same results, so it's something fundamental I'm doing wrong.
UPDATE #1:
Somebody suggested a fix and then deleted the reply, but another member suggested the same fix in a comment. The fix didn't work but they clarified that I need a key/val pair for the POST which changed my javascript to:
data: { news: $(this).text() },
and then my ajax.php to:
if (isset($_POST['news'])) {
$news = $_POST['news'];
}
UPDATE #2:
Thanks to #Sean I understand that I was displaying my debug alert improperly, adding the following to the javascript corrected that and now alerts the proper list item:
context: this
But the PHP function still isn't updating.
Your $(this) in alert($(this).text()); inside your $.ajax is out of scope. You can either save to a var before your ajax call, and reference the var -
$(".mainleft > ul > li").click(function(){
var liText = $(this).text();
$.ajax({
type: "POST",
url: "/includes/ajax.php",
data: liText,
success: function(msg){
alert(liText);
}
});
});
or use context ajax option -
$(".mainleft > ul > li").click(function(){
$.ajax({
type: "POST",
url: "/includes/ajax.php",
context: this,
data: $(this).text(),
success: function(msg){
alert($(this).text());
}
});
});
Note: as #Mark B mentioned, your data should have a key to be able to access in php -
$(".mainleft > ul > li").click(function(){
$.ajax({
type: "POST",
url: "/includes/ajax.php",
context: this,
data: {key: $(this).text()},
success: function(msg){
alert($(this).text());
}
});
});
reference: https://stackoverflow.com/a/1570160/689579 https://stackoverflow.com/a/8070183/689579
jsFiddle: http://jsfiddle.net/h2FLg/ (examples of saving $(this) to var, context:, and out of scope)

How can I set a jquery var to be another jquery ajax functions callback

Sorry for my terms incase they are incorrect, but I have a php function that I am going to interop with ajax so I can use a php function to get a value for a jquery variable.
So now I am just at the point where I have received the ajax callback and would like to set the jquery variable to the response value I got back. Here is my code as an example:
$(document).ready(function() {
$('body').videoBG({
position:"fixed",
zIndex:0,
mp4:'', //This is where I want to use the ajax response value
opacity:1,
});
})
jQuery.ajax({
type : "POST",
url : "index.php",
data : {
request : "getvideo_Action"
},
success : function(response) {
alert(response);
//Do my response stuff
}
});
So basically what I want to do is set the 'Mp4' var(or is it property?) with the value that I get from the response. Can anyone help me out with this? Thanks.
You can put the entire thing inside the success function, like this:
jQuery.ajax({
type: "POST",
url: "index.php",
data: {
request: "getvideo_Action"
},
success: function (response) {
$('body').videoBG({
position: "fixed",
zIndex: 0,
mp4: response,
opacity: 1
});
}
});

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

Categories