Unable to post variables with jquery post() - php

I am trying to pass variables from a modal form to another page. I declare the variables from the form with the id tags in each selection.
Page reloads to test.php, however no variable can be echoed.
javascript
var id = $( "#id" ),
name = $( "#name" )
$.post("jqtest/test.php", { device_id: "id", device_name: "name" });
load('jqtest/test.php');
test.php
echo $_POST['device_name'];
echo $_POST['device_id'];

It's not clear how are you planning to use this code to pass values from your modal form but there are several problems with your current code:
; is missing at the end of variable assignment
read values from input fields using val() instead of getting jquery objects of them
use variable names in data object of post method instead of literals ("id", "name")
Try this to see that variables are passed and echoed in a callback function
var id = $( "#id" ).val(),
name = $( "#name" ).val();
$.post("jqtest/test.php",
{ device_id: id, device_name: name },
function(data){
alert(data);
}
);

It looks like there's a lot wrong with this... It looks like you are using echo $_POST['device_name']; and echo $_POST['device_id']; just to ensure that your AJAX is working. If that's the case, you don't need to be using .load();. You are also sending the jQuery object of $( "#id" ) and $( "#name" ) instead of the values within those form elements. Later, in your .post request, you have those same variables in quotes, which is sending the strings "id" and "name". Again - likely not what you're looking for.
Your question is a bit convoluted but I'll do my best to answer. Try this JS:
var id = $("#id").val(),
name = $("#name").val();
$.post("jqtest/test.php", { device_id: id, device_name: name }, function(response) {
console.log(response);
});
In your PHP file, use this code:
echo $_POST['device_name'];
echo $_POST['device_id'];
You will see your variables show up in the JS console of your browser. With this script, you've sent your two variables to test.php via POST and test.php will echo the results. The callback function added to the $.post request will display the output from test.php in the javascript console. Learn more about .$post() on the jQuery docs.

Related

jquery ajax form sended, but var_dump($_POST) empty

everyone, i got a very simple problem, but i am really confused... for un hour
in a php page, i have the code:
<script>
$( document ).ready(function() {
$("#date_avant").click(function(){
$.post( "_corps_medecin_changedate.php", { name: 'test', id: '1' } );
$("#consultations_jour").load("_corps_medecin_changedate.php");
});
});
</script>
And in the page _corps_medecin_changedate.php, just at the beginning, i have the code:
<?php
var_dump($_POST);
$date_debut = $_POST['name'];
?>
And i got msg:
array (size=0)
empty
Notice: Undefined index: name
I checked the firebug, the parameters are correct in the post list, so i thinked it is sended correctly, but just canot receive in the action page.
Server info : Apache/2.2.11 (Win32) PHP/5.4.4
And in local envirment.
Can anyone help me?
Your returned data from your $.post call is not automatically made available to your .load() call. They are two separate functions which means your call to load essentially send no POST data to the PHP script.
You can pass the post parameters as part of your call to load
<script>
$( document ).ready(function() {
$("#date_avant").click(function(){
$("#consultations_jour").load("_corps_medecin_changedate.php", { name: 'test', id: '1' });
});
});
</script>
You have to handle result of post request in callback function, like this:
<script>
$( document ).ready(function() {
$("#date_avant").click(function(){
$.post( "_corps_medecin_changedate.php", { name: 'test', id: '1' },
function(result) { $("#consultations_jour").html(result);} );
});
});
</script>
In your code you make 2 different requests (first is in .post function, and second is in .load).
that is because your are calling the _corps_medecin_changedate.php again right (.load()), after the post is made with no posted datas.. and you are not using callbacks..
$("#consultations_jour").load("_corps_medecin_changedate.php"); //here
Since post is async... the .load() function (which isn't inside a post's callback) is called right after you call post and does not waits for it
i have no idea why are you loading the same php page again after post it made which i don't think is needed...but as an example ...you can use callback... to check the datas that you have posted
$.post( "_corps_medecin_changedate.php", { name: 'test', id: '1' },function(data){
alert('done');
});
//$("#consultations_jour").load("_corps_medecin_changedate.php");
try this and you should get the posted values in your PHP page.

how to use jquery variable in php to insert into database

hello in the following code variable checked_num contains the integer value like 1,2,.
now i want this value in database using php code using mysql insert query..
the jquery code i have is:
<script type="text/javascript">
// function for counting check boxes
$(document).ready(function (){
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
});
});
now i want that variable "checked_num" is accessed in php code so i can insert this variable value into database
Have you readed the jQuery ajax/post/get ?
You can use ajax to update your database.
EG:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.ajax({
type: 'POST',
url: 'yourpage.php', //this page inserts your data in database
data: {'checked_num': checked_num},
success: function(response){
//do whatever you want on success
},
error: function(xhr, status, errorThrown){
//handle ajax error
}
});
});
You can also use $.get() or $.post() instead of $.ajax().
You can use jQuery's $.post() method:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.post('myPHPScript.php', { checked : checked_num }, function(data) {
/* data is the response you receive from the server. */
});
});
Here "checked" is the name of the post variable you're sending over. If you wanted to post a string named "myString" containing the text "Hello, world!", for example, you'd use { myString : "Hello, world!" }. This is an object, meaning multiple variables can be sent over by separating each with a comma.
In PHP you'd then retrieve this using $_POST:
<?php
$checked = $_POST['checked'];
?>
You'd probably want to encode this post data however before inserting it into your database.
As for how to insert the data into your database, check out PDO or mysqli.
You are using javascript to set a flag if one or more of the HTML checkboxs in your form are checked.
So you already have a <form> on the page.
When you submit the form you can access that information directly using PHP
All you have to remember is that checkboxes are only submitted back to the server PHP code if they ARE checked. So all you need to do is test for their existance.
if ( array_key_exists( 'checkbox_name', $_POST ) ) {
// this check box is checked
} else {
// this checkbox is not checked
}

Jquery load dymanic content with parameter

I'm trying to load div content based on the a href being clicked and pass in a parameter. For example, Link 1
Clicking on Link 1 will pass value "3" to process.php, and return back the value "apple is good for you".
However, I can't seem to be able to pass the value without having a submit button. Anyway I can pass the parameter to another php file to process, and return the value?
$(document).ready(function(){
$("#testing a").live("click", function(evt){
var id= $(this).attr('id');
$.post("process.php", { id: id },
function(data) {
alert(data);
$('#result').load(data);
});
})
});
Below is my HTML
<div id="testing">
hello
</div>
<div id="result"></div>
Appreciate your help, thanks a lot!
You shouldn't be using numbers for id values. Instead, prefix them with a letter, or consider adding them to a data- atribute on the element.
Additionally, $.live() is deprecated, and we are encouraged to use $.on() from here on out for event delegation. I've gone ahead and handled this in the code below, but the id issue remains.
Lastly, $.load() and $.html() aren't the same. If you want to load data into an element, you don't call the load method (though the name could lead to that confusion).
// Short-hand version of $(document).ready();
$(function(){
// Handle anchor clicks on #testing
$("#testing").on("click", "a", function(e){
// Prevent links from sending us away
e.preventDefault();
// POST our anchor ID to process.php, and handle the response
$.post("process.php", { 'id': $(this).attr("id") }, function(data){
// Set the response as the HTML content of #result
$("#result").html(data);
});
});
});
From your process.php file, you might have something like the following:
$msg = array(
"...chirp chirp...",
"This is response number 1",
"And I am the second guy you'll see!",
"Apples are good for you!"
);
$num = $_POST["id"] || 0;
echo $msg[ $num ];

Passing HTML INPUT field ID to PHP completion program in jQuery Autocomplete

I want to pass the id of the INPUT field to the PHP file providing options. Here's my HTML & jQuery code. But the PHP program gets the id as undefined. Thanks for helping.
jQuery :
$('.classfield').autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+$(this).attr('id')+"&callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.name);
});
//pass array to callback
add(suggestions);
});
},
//define select handler
change: function(e) {
$("#spill").html("change "+$(this).val()+e.type);
}
}); // autocomplete
HTML:
<input type="text" class="classfield" id="hello" value="there"></input><br>
the value of $(this).attr('id') is undefined because this is the object that is put in the parameter of autocomplete (the parameter of autocomplete accepts an object, so if you use $(this).attr('id'), you are referencing the object that was passed in the parameter on the autocomplete)
therefore you cannot use $(this).attr('id').
You have to store the id of the text field, may be as a global variable... Hope this helps a little bit
Try getting the id from this.element:
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+this.element.attr('id')+"&callback=?", req, function(data) {
Also see this example.

Binding a php variable with Jquery slider

I have two JQuery sliders, value of "Second_Slider" gets updated and a div named
"amount2" as well as it should.
Now i want to update an php variable to the value of "Second_Slider" also. how can i achieve this?
$( "#Slider" ).bind( "slide", function(event, ui) {
$("#Second_Slider").slider({ value:300 });
$( "#amount2" ).val( "$" + $( "#Second_Slider" ).slider( "value" ) );
<?php $Php_Var_I_Want_to_Change = "what-do-i-put-here? ?> };
updated
you could try something like this
var slideXHR;
function setSlideSession(slideValue){
if( slideXHR == 'XMLHttpRequest'){
//stop previous ajax request
slideXHR.abort();
}
slideXHR = $.get('url/file.php', { item : slideValue });
}
$( "#Slider" ).bind( "slidestop", function(event, ui) {
$("#Second_Slider").slider({ value:300 });
var slideValue = $( "#Second_Slider" ).slider( "value" );
$( "#amount2" ).val( "$" + slideValue );
//set session variable on php via ajax
setSlideSession( slideValue );
};
php file
<?php
session_start();
$_SESSION['variable'] = $_GET['item'];
?>
You can't "bind" php variables to javascript variables.
Javascript is run client side, the only way you can get the values into PHP is by making a request from the client side.
e.g.
Submitting a form
Clicking a link
Sending an ajax request
I wouldn't suggest an approach to take without understanding why you want to bind it in the first place.
I can't really get your question but if i am following right you want to update a PHP variable through a jQuery slider's slideevent?
That's absolutely impossible once php is processed on server-side and then passed into the client as javascripts are processed on the client, after PHP has done its job!
If you want to send data to the server, use AJAX!
you are mixing JavaScript (client-site) with PHP (server-site) - will not work.
in your case you may consider sending an ajax request on change of slider - what could be overkill - every thing depends what it is for

Categories