To sum up what I'm trying to achieve here:
Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>
This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data
The PHP page is displayed inside a div on the page
Here is the function, using jQuery:
function displayData(str){
$.ajax({
url: "target.php",
type: "POST",
data: {"value": str.value},
success: function(data){
console.log(data);
}
});
$('#my-div').load('target.php');
}
To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>
When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:
Notice: Undefined index: value
Sorry if it seems kind of dumb, but I can't figure out what I'm doing wrong... So I thought of asking the community. Thank you for your help guys! Cheers.
Please try this.
and you need to return the result from target.php page
function displayData(str){
$.ajax({
url: "target.php",
type: "POST",
data: {"value": str.value},
success: function(data){
$('#my-div').html(data);
}
});
}
If you use .load() your browser will make another GET request to target.php and display it, so your $_POST will be empty.
You can use $('#my-div').html(data) inside success: of ajax or you can use $_GET instead of $_POST in your php and pass variable in url like this
$('#my-div').load('target.php?value='str.value);
hey the problem is quite simple, if you are posting the data value getting from ajax to target.php then the $('#my-div').load('target.php') should be inside the ajax success function and you have to put the data using html function like this $("#my-div").html(data). it will directly load the data in html format inside the div.
Related
I know there are a few topics on this subject, but after I spent 2 or 3 hours trying to get something good out of them, I just decided to ask this question on a specific point.
So here is my problem : I have got a table and I am using a jQuery function to select a row of this table. Now what i actually want to do is getting the text content of the div contained in the first td of the row.
I already used a getter on it and I am checking the getted value with an alert as you can see in th following code :
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
});
So now, what I am trying to do is to send the myValue variable through an ajax request by replacing my alert by this piece of code :
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(rs)
{
alert(myValue);
}
});
Then, back to my php code, I am tring to observe the obtained variable by using an echo, just like this :
<?php echo $_GET['myValue']; ?>
But there is just no way for me to know if my page got it beacause the echo just prints nothing... So i was wondering if someone could do something for me. Thanks.
PS : Oh, by the way ; I don't really know if this can matter, but my page index.php already receives data by a post.
You can't, but read this, php is on the server, while js usually runs on the client, but your ajax trick can work. Just do some processing in the recieving php.
I usually put my ajax recieving end in a different file, and process the rest by the variables posted.
Just try to put the $_GET['myValue']; into an if, or a switch.
Do a var dump of the request var to see if anything is coming through:
<?php
var_dump($_REQUEST);
If not, do a console.log() on 'myValue' to make sure it exists before sending the ajax request - the issue may lie in your js rather than you php.
If you are POSTing data then adjust accordingly - e.g.
$.ajax({
type: 'post',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('successfuly posted:');
console.log(data);
}
});
then:
<?php echo $_POST['myValue']; ?>
If you were using GET your data would be in the url, e.g:
index.php?myValue=something
I'm not sure if you are aware of that, but you should wrap you function in document ready statement as below.
Next, call the AJAX request on some action, in this case we can use a click on the row in table.
$(document).ready(function () {
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('you have posted:' + data.myValue);
}
});
});
});
Okay so it seems that i totally misunderstanded on the way that the $.ajax function works.
I now do use the $.post function (which is actually the same), this way :
$.post('pageElement.php', { myValue : $(".selectedRow .firstTd div").text() },
function(data) { $("#test").html(data); }
);
The url "pageElement.php" refers to a page containing this code :
<div><?php echo $_POST['myValue']; ?></div>
The function called at the end of the process just puts this code into a div of my original page, so i can use it as a php variable now and then send it to another page through a form.
I found many examples but I can't figure out how to apply it to my code. I'm adding a wish list button and want users to click it, get an alert that it was added to their member page and continue scrolling through content. I know I need to use ajax to send the variables from the url to javascript and then to php with ajax. But I'm stuck on getting those variables passed to ajax...probably because I'm still learning it. Using the GET in php is easy to get multiple variables but I can't figure out how to do it in javascript. And of course I don't want the page to reload. This is what I'm passing:
<div><a href='wish_list.php?title=".urlencode($title)."&link=".urlencode($link)."'
onClick='wish(this.href); return false;'>Add to Wish List</a></div>
How can I set these variables in javascript? Ajax I would use is:
$(function (){
set variables from url
$.ajax({
type: "POST",
url: "wish_list.php",
data: "$link and $title" //Need help with this here
success: function()...
});
});
I need the link variable to remain encoded because well it's a link. So how do I pull the title and link out of url and pass it to the php file?
js can't access php variables. You could store those values in a hidden html input field and then get it with jquery.
link = $(#IdHiddenField).val();
and then in the ajax function:
data: { link: link}
You'll need at least the basics of javascript and jquery to deal with the ajax functions.
You pass the parameters in the data attribute witch is an javascript object. It would look like this:
data: {"link":"value of link", "title":"value of title", "numbers_too":1},
You have to replace the values of those attributes above with your server side values.
You could put this data into the tag using data attributes:
<div<a class="sender" data-link="<?= $link; ?>" data-title="<?= $title; ?> href="wish_list.php" ... etc.
Then:
$(".data").click(function(e){
type: "POST",
url: $(e).attr("href"),
data: $(e).data()
});
You can add in the ajax function to use directy the "href" from link.
function wish(link){
$.ajax({
type: "POST",
url: link,
data: '',
success: function()...
});
}
With your link:
<div><a href='wish_list.php?title=".urlencode($title)."&link=".urlencode($link)."'
onClick='wish(this.href); return false;'>Add to Wish List</a></div>
Then, you get data from url with $_GET.
<div><a onClick=wish(urlencode($title),urlencode($link));>Add to Wish List</a></div>
function wish(title,link) {
$.post("wish_list.php", { title: title, link: link }).done(function() {
alert("Added to your member page");
});
}
I have this JavaScript code:
$(document).ready(function(){
$('#sel').change(function(){
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+$(this).val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
On status change i need to refresh a div without page reload. But it returns blank page. If i try alert the result on success, i get the response, also i checked with inspect element, its ok. The problem is that it returns blank page.
The file i'm working on, is the same( modules.php?name=TransProject_Management&file=index ) i called in ajax.
the html:
<body>
//...
<div id="ajax_results">
//.....
//somewhere here is the select option <select id="sel">......</select>
//.....
</div>
</body>
Any help, would be very appreciated.
use the following code to return your response html:
echo json_encode(array($your_response));
Then in your javascript, you will need to reference the data as:
success: function(data) {
$("#ajax_results").html(data[0]);
}
since it is now an array.
this in your ajax function refers to the jQuery XHR object, NOT the $('#sel') object. Just assign it to a variable before the ajax function like var sel = $(this) then use it later inside the function. Try this:
$('#sel').change(function(){
var sel = $(this);
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+sel.val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
Hmm, first glance the code looks good. Have you tried using Chrome debug tools? Hit F12 and check the Network tab, this will show you what is being returned. You can also debug without using an alert so you can step through to see what exactly the properties are.
Just thought, you might need to add 'd' to the data returned. Anyway, if you do what I suggested above, put a pause break on the line and run the code you will see what you need.
Based on your comments below the question, it seems that you are using the same script to display your page and to call in the javascript. This script seems to return a complete html page, starting with the <html> tag.
A page can only have one <html> tag and when you try to dump a complete html page inside an element in another page, that will lead to invalid html and unpredictable results.
The solution is to have your ajax script only return the necessary elements / html that needs to be inserted in #ajax_results, nothing more.
I have a table which has user names. When I click a user I need to retrieve their information from mysql database and this information will be populated into the relevent textboxes. I am totally stumped on how I go about doing this? Can someone please help
You can use jquery to achieve this in ajaxed way. In test.php write your php mysql code.
The below code a javascript code used to get data from a different page where you can process and get the information about any particular user. Read about ajax.
$.ajax({
url: 'ajax/test.php',
data: 'id=<?php echo $id?>',
type: 'POST',
success: function(data) {
//you can get data as an array and parse it to get fields and you can put them whever you want.
$('.result').html(data);
alert('Load was performed.');
}
});
Here is the jquery code which will solve your issue. Write this code in a javascript function. onclick event of that button should call this function. Write all your db coding in yourpage.php.
url = "yourpage.php";
$.get
(
url,
{
'act' :'getdata'
},
function(responseText)
{
strData = responseText;
$('#div_id').html(strData);
},
"html"
);
Place all your html code inside DIV and call the div in jquery code. It will work.
I need a jQuery popup to ask the user for some required data before loading the same page it's on.
The data entered will become a php variable that I'll use to query a mysql table and pre-populate some form fields.
Any advice?
Thanks!!
you can make an AJAX call to the PHP and load it to div that you want. For the ajax calls you can use jquery it really makes you job easy.
eg:
$.ajax({
url: 'getitems.php',
success: function(data) {
$('#manage_inventory').html(data);
//alert('Load was performed.');
}
});
like in the example it is calling getitems.php and getting the list and loading it into #manage_inventory. The data being returned can be XMl or other type which can be parsed and be used according to your needs.
Your solution could be as simple as using a prompt() box in javascript and then passing the information via ajax
var stuff = prompt('Gimme Stuff');
$.ajax({
url: 'dostuff.php',
data: 'stuff=' + stuff,
success: function(data) {
//process stuff
}
});