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

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.

Related

Unable to show table after POST on same form PHP jQuery

I have this code below that gets the data from the POST and return the data as a table. When the code runs I put Console Log to see what is happening once the SUBMIT button is pressed. When the console log shows as "done" I want to show the table instead, but can't see why it's not happening.
<script type="text/javascript">
$(function(){
$('#searchform').on('submit', function(e){
e.preventDefault();
//alert($('#searchpostcode').val())
$.post('includes/jobdetailssearch.php',
$('#searchform').serialize(),
function(data, status){
$('.table-responsive #displayadd').html(data.Display);
//$("#table-responsive td").last().append(data);
console.log("done");
}).fail(function () {
console.log("fail");
});
});
});
</script>
Why would this be?
Make sure your php script returns a serialized json structure, which can be parsed by javascript.
Try to console.log(data) in your callback function to see what is returned from PHP.
Try This:
<script type="text/javascript">
$(function(){
// Submit Button Pressed
$(document).on('submit','#searchform', function(e){
// Prevent Default Click
e.preventDefault();
//The first parameter of $.post() is the URL we wish to request
$.post("includes/jobdetailssearch.php",
{
//Then we pass in some data to send along with the request
searchval:$('#searchform').val()
},
//The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
Note:
$('#searchform').on('submit' work same as $('#searchform').submit( but when you use $(document).on('submit','#searchform' then it will also work for the DOM added later.

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
}

Unable to post variables with jquery post()

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.

Get Session value based on ajax success

I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>
You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});​

Run PHP code when user clicks link and pass variables

I need to run a PHP code from external server when user clicks a link. Link can't lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?
Something like this?
<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?
use something like this in you page with link
Some text
in the same page put this somewhere on top
<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";
$.ajax({
url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
alert('success');//do something
}
});
return false;
});
});
</script>
on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple
<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>
hope that helps
You can do this with an ajax request too. The basic idea is:
Send ajax request to runcode.html
Configure another AJAX to trigger from that page
Considering, this as the markup
<a id="link" href="runcode.html'">Test</a>
JS
$("#link").on("click", function() {
$.get("runcode.html", { "id" : ID }, function(data) {
//on success
});
return false; //stop the navigation
});

Categories