Change PHP Function Argument with AJAX - php

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)

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

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

PHP / JQuery / AJAX for Updating Database if Div is not visible

I have a complex website setup so I'll just make an example a simple one.
Current Setup
I have two buttons.
<a id="one" href="#">Link 1</a>
<a id="two" href="#">Link 2</a>
And I have two divs
<div id="showOne" style="display:none">1</div>
<div id="showTwo" style="display:none">2</div>
This is my JQuery code
$('#one').click(function (e) {
$('#showOne').show();
});
$('#two').click(function (e) {
$('#showTwo').show();
});
What I'm Trying to Accomplish
Basically, I have a database table setup that has a row to count how many times was div(showOne) and div(showTwo) shown.
How would I work with AJAX to add one to the database row aka counter if display = block?
My Attempt
$('#one').is(":visible")
{
$.ajax({
type:"POST"
url: update.php
data: {type:link_one_shown}
success: function(data){
alert("Test");
}
})
When I do this, the rest of my JQuery code crashes. Not sure if this doesn't make sense or I just wrote something wrong.
Thank you in advance!
Three problems that I can see:
As Akam notes, you've mangled the if statement.
The data isn't correct -- link_one_shown should be either a variable (which you haven't defined?) or a string literal.
You're missing commas between the ajax function parameters.
Here's the modified code:
if ($('#showOne').is(":visible")) {
$.ajax({
type:"POST",
url: update.php,
data: { type: "link_one_shown" },
success: function(data){
alert("Test");
}
});
}
why not just move ajax call to function and invoke it when show the div, this avoids code repetition and makes it simpler.
$('#one').click(function (e) {
$('#showOne').show();
updateDB('link_one');
});
$('#two').click(function (e) {
$('#showTwo').show();
updateDB('link_two');
});
function updateDB(link)
{
$.ajax({
type:"POST"
url: update.php
data: {type:link}
success: function(data){
alert("Test");
}
});
}

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.

jQuery (this) as succession of jQuery Ajax?

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.

Categories