How can I use a jQuery var in some php code? - php

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.

Related

AJAX data not displayed in page

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.

Update php generated content without page refresh

I've created a php function (called "category_page" in "category-page.php") which reads data from a file into an associative array and then generates some html to display the information on products.php (the page calling the "category_page" function)
My aim is to allow the user to select from a drop down in order to sort the displayed information without refreshing the page.
I have so far managed to achieve this using document.formname.submit on change of the dropdown and then using $_GET to choose which key in the array to sort by, however, this causes the page to reload.
I have a little knowledge of php, javascript/jquery and have done a fair bit of searching/reading on AJAX to enable an update without refresh/reload, but can't seem to put all the pieces together.
So, in products.php, I have the following javascript/jquery:
function sort_products() {
queryString = "?sort_list="+$("#sort_list").val();
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
}
$("#sort_list").on("change", function() { sort_products() });
and then in category-page.php:
if(isset($_GET['sort_list'])) {
$sort = $_GET['sort_list'];
}
else {
// set default sort order
}
I've verified in Chrome's network panel that a request for category-page.php?sort_list=price is being sent, but the page isn't updating. Any help would be appreciated!
Change this line of code:
$("#sort_list").on("change", function(e) { sort_products(); e.preventDefault(); e.stopPropagation(); });
Once the query is sent, you need to make something with what is returned.
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
.done(function(data) {
// if your php code returns the html you can make something like this
// the var data will be the html code
$('#your-container').html(data)
})

Ajax jquery returns blank 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.

Can't send array to php via ajax and back

i am trying to get a button on my page which will eventually be a delete button to work. However because it is a <li> element and not your average submit button with a form etc... i have to use ajax to send all the variables to be processed, at the moment i just want them to be in a state where they can be processed, but at the moment my script doesn't seem to return any value like i want it to and output them.
Hopefully from the code below you will see what i mean, all i need it to do at the moment is just select all the values from the checkboxes which are cehcked and send it to the mail_trash.php, and then just send it back and output the array, just so i can see it is selecting the proper values etc... The actual delete php code is already written and working, this is just to check the Ajax.
Here is the javascript and ajax
<script>
$("document").ready(function (){
$("li.trash").click(function(e){
var db = $(':checkbox:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
if(db.length == 0) {
db = "none";
}
$.ajax({
type: "GET",
url: "mail_trash.php",
data: {'db[]':db },
dataType: "json",
statusCode: {
200: function (response) {
$("#mail_header_name").html(response.mess_id);
}
}
});
});
});
</script>
And here is the script for the mail_trash.php
<?php
include 'connect_to_mysql.php';
$mess_id = $_GET["db"];
echo json_encode($mess_id);
?>
And just to check things the button
<li><a class="trash" href=""> </a></li>
Thank you so much for your help, this has been bugging me for the last couple of hours.
It's not li.trash. It's a.trash because trash is a class of the a element. As such the first three lines of the js should be:
<script>
$("document").ready(function (){
$("a.trash").click(function(e){
and then so on with the rest of you code. I haven't checked the rest of your code necessarily, although I am pretty iffy about $(':checkbox:checked') as I don't think that's correct jquery.... To start off, I'd suggest fixing the first selector I mentioned, checking the second with jquery docs and then jshinting/jslinting your code. (Javascript only)
I don't know if its a typo in the question itself or the issue with your script but name of th e parameter while passing is "db" but on the server side you are expecting "mess_id"

Ajax Post PHP Div Refreshing

It is me again. I am getting so frustrated with this code it is not even funny. It's not that I am wanting to post it again. It is just that now I understand the where the problem was in the code and wanted to see if you guys can help me figure the last part out.
Basically I am trying to refresh a div without reloading the entire page. It's killing me. Here is some more information on it:
here is my js file first
$(function() {
$(".button").click(function() {
// validate and process form
// first hide any error messages
var email = $("input#email").val();
//var dataString = '&email=' + email; commented out
var dataString = email;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: {email:dataString},
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function() {
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
$("#email").val('');
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
Now the problem that I am running into with this code is on the Ajax part. After placing the alert(), I have relized that if I use the function() like this:
success: function(data)
Then the alert came out blank. The reason behind it is that my URL is going to my php file, but my div that I am trying to refresh is on my html file. Meaning if I do this:
success: function(data) {
$("#div").html(data)}
I am sending blank data because it's trying to get the div from my php file instead of my html file.
Now if I do this:
$("#div").html()
Then that gives me the div that is in my html file.
By knowing what is going on now, Can you guys please help me???
My dear you should generate some sort of html in your php file that you want to generate in your div. Then you will see that you are having some content in data in the success function. This is an easy approach.
But there is also some other approach that is more efficient but it needs some sort of search. This is the implementation of Client Side Scripting. You can do this with the help of a jquery plugin jquote2. I hope it will work for you.
You're using
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
Both are wrong, jQuery .fadeIn() and .fadeOut() arguments are either [duration,] [callback] or [duration,] [easing,] [callback]. None take HTML as input.
Try changing
$("#div").fadeOut($("#div").html());
to
$("#div").fadeOut();
and moving it outside the $.ajax call to hide the previously showed (if any) results before the post and also change
$("#div").fadeIn($("#div").html());
to
$("#div").html(result).fadeIn();
Also change
success: function()
to
success: function(result)
Hope it helps.
This might be a problem relating to the response from the php script. Jquery doesn't always correctly render the Ajax response as html.
Setting dataType: html in the $.ajax({ ... }) call can help. Also setting header("Content-Type: text/html"); at the top of your php ajax script.

Categories