I am having a problem with seeing one of my variables on a webpage. Here is what I have so far.
$(document).ready(function() {
$(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = '$("#ID").val()'
$.ajax({
type: "POST",
url: "test_wID.php",
data: "id",
success: function(data) {
$('#rightselection').html(data)
}
});
});
});
});
This is the jquery function I am using to take an ID entered into a form and use that ID with a bash script.
Here is the php.
<?php
//Get the ID from the HTML form and use it with the check chunk script.
$id = $_POST['ID'];
if (is_null($id)){
echo "$id is null";
}
echo "Selected test Game ID: ".$id;
//print shell_exec('/opt/bin/tester $id');
?>
I commented out the script because the variable is returning null, at this point I am just trying to make sure that I get the ID.
For completeness here is the form I'm using.
print "<p><h3>ID: <input type=\"text\" id=\"ID\" /></h3></p>";
#print "<br>";
print "<p><button id=\"CheckID\">Check ID</button></p>";
When i click the button I get the message in my div that the variable is null. So my question is am I missing something in the declaration? How is it that the var id is null?
Thanks for any help provided.
You should consider changing your jQuery code to:
$.ajax({
type: "POST",
url: "test_wID.php",
data: {id: $("#ID").val()},
success: function(data) {
$('#rightselection').html(data)
}
});
You mixed up strings and variable references at two points.
First, the statement var id = '$("#ID").val()' assigns just a string to your if variable and not the return value of the jQuery call. So just remove the ' here.
Second, the data parameter you're giving to the ajax() call again consists just of a string "id" and not the respective value. Here you need to change to {'id': id}.
So after correcting everything, your code should look like this:
$(document).ready(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = $("#ID").val();
$.ajax({
type: "POST",
url: "test_wID.php",
data: {'id': id},
success: function(data) {
$('#rightselection').html(data);
}
});
});
});
Sidenote: Try to put all ;, where they belong. This prevents some errors, which can be hard to track!
EDIT
As pointed out in the comment by #FlorianMargaine you only need one wrapper not two around your code.
Firstly, the two following snippets are equivalent:
$(document).ready(function() {
});
// Is equivalent to:
$(function() {
});
So your code does the same as:
$(document).ready(function() {
$(document).ready(function() {
});
});
Plain useless, right?
Secondly, this line is plain wrong:
var id = '$("#ID").val()';
You're passing a string to the id variable. $('#ID').val() is not evaluated. This is the equivalent of doing this in PHP:
$id = '$_POST["id"]';
Which is just wrong, right?
You want this:
var id = $('#ID').val();
By the way, this variable naming could be improved, the same goes for the HTML ID.
Thirdly, you're doing the same mistake in the data option of $.ajax:
data: 'id'
You're just passing a string to the data option. You want the value of the id variable.
Then, if you absolutely want a string, I don't recommend it. jQuery expects a special kind of string. You better pass an object. Like this:
data: {
id: id
}
Do you see why the variable naming is wrong? You can't differentiate the property from the value. If you had done the following:
var idValue = $('#ID').val();
You could use this:
data: {
id: idValue
}
Which is way more readable.
In your $.ajax call you need to do:
data : { id: id }
If you want to pass parameters in an AJAX call you need to pass a string similar to the GET string you see in urls. So something like: d=123&name=test
Change the line
var id = '$("#ID").val()'
To
var id = 'id=' + $("#ID").val();
Related
I am attempting to use AJAX to generate PHP to be displayed inside of a div based on the ID of the link clicked. (I haven't dealt with HTML formatting yet, just want to figure this out first)
My Code:
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {ProductIDNumber: clickID},
success: function(html) {
$('#container').append(html);
}
});
});
});
</script>
I have dealt with getting the PHP to run when the url is landingPage.php?ProductIDNumber=1 and that all works properly, I just don't quite grasp how to return the resultant HTML.
Edits made and commented on.
You need to include success, which is run once the response is received, similar to;
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {
ProductIDNumber : clickID
},
success: function(html) {
// Do what you need to here with 'html'
$('#container').append(html);
}
});
});
</script>
As Alvaro said the structure of the data was also incorrect
Here's a link to the jQuery docs where you can find out more about the parameters and options you have (such as handling fails etc)
the data is wrong,
it is like this:
data: {varname: value, varname1: value},
I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: text,
dataType: "text"
});
insertGroupData.done(function(msg){
alert(msg);
});
This is the first half, I'm stuck in the 1st line of my backend.php
I think it should be catch the POST value, but what should I catch?
<?php
if(isset($_POST["_____??_____"])){
echo "test";
}
Jquery: if your data should be like
data: {test:text},
Then in PHP you can use to get like below,
if(isset($_POST["test"])){
echo "test";
}
Explanation about data:
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting .
Ref: http://api.jquery.com/jQuery.ajax/
change your code to this
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: {text:text},
dataType: "text"
});
in backend page you can check it like
echo $_REQUEST['text];
or
echo $_POST['text];
A lesson in jQuery
$(function () {
var
url = 'your/target/script.php',
data,
fn = function (text) {alert(text);},
// fn will expect text, so set return as text
dataType = 'text';
// this POST data will populate $_POST as $_POST[key] = 'value'
data = {
ajax : 1,
key : 'value',
key2 : 'another value'
};
// shorthand notation is convenient sometimes
$.post(url,data,fn,dataType);
});
Your php now has access to your key value pairs
<?php
// in my example the 3 are set
if (isset($_POST['ajax'])) {
$_POST['key'];
$_POST['key2'];
}
Happy coding
I have a table with dynamic data from database, each row consist of a text filed and 2 link (accept or reject). then if user clicks on any of these link, the row will disappear and the rest of the rows are only visible in table.
I get ID of each row with ajax by clicking on each link, however I also need to get the text-field value.
how can I get it?
I need to have in ajax cause after getting value I need to insert in database with php+sql.
this is my ajax part for link:
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'Test.php',
data: 'ajax=1&accept=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
how can I include text filed value in it?
please comment me which I'm really in need to solve it,
Thanks
You can add manually your text to the GET request.
(snippet)
data: 'ajax=1&accept=' + parent.attr('id').replace('record-','') + '&text=VALUE',
Substitute text with the name you want to be received in PHP. Substitute VALUE with the text entered on the page that you want to grab - and don't forget to encode the value.
You will need the name of id of the textfield first. Then you could do something like this:
var textboxvalue = $('name or id of textfield').val();
Then you will need to append this value to your data string:
data: 'ajax=1&textvalue='+textboxvalue+'accept=' + parent.attr('id').replace('record-',''),
Then you can use $_GET['textvalue']; to get the value of textbox.
Use following and you're good to go. Also you had extra '});' at the end line of JS fragment. I had it removed. But make sure you give id to text fields in following pattern : text-fld-RECORD_ID where RECORD_ID is the ID of the record.
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
var id = parent.attr('id').replace('record-','');
//make sure that text field has ID in pattern 'text-fld-RECORD_ID'
var text_fld = $('#text-fld-'+id).val();
$.ajax({
type: 'post', // I suggest using post; get will be harmful in such occasions
url: 'Test.php',
data: {ajax:1,accept:id,text:text_fld},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.