I ran simple ajax too post values in the same page which I saves into session variables, which works fine but whenever i print those session variables in console it don't shows the latest values.
<script>
$(function(){
function showValues() {
jQuery.ajax({
type: "POST",
data: $( "form" ).serialize(),
success: function(data){
var x = <?php echo json_encode($_SESSION['q10']); ?>;
console.log(x);
}
});
}
$( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
});
</script>
Above script serialize the values from radio, checkbox and select inputs later i saved those on the following variables
<?php
if(isset($_POST['q10']))
{
if($_POST['q10'] == 2){
$_SESSION['q10']=1;
}else{
$_SESSION['q10']=0;
}
}
Initially I set $_SESSION['q10'] = 0 and console shows this value but whenever i changed the value it shows the previous value. It didn't update
P.s I get the changed values after refreshing the page. shouldn't i get the updated values in the console
<nav class="segmented l3_seg">
<input type="radio" name="q10" value="1" id="10a">
<label for="10a">Richtig</label>
<input type="radio" name="q10" value="2" id="10b">
<label for="10b">Falsch</label>
</nav>
Many comments and article you will found regarding php is running in server side and Javascript is running in client side. PHP run one time and rendered data to browser one time if you want to reconnect with server/php again you need to use ajax that you are doing.
In short , you need to use js variable which containing ajax returned response.
Return response from php
if(isset($_POST['q10']))
{
....
return $_SESSION['q10'];
}
And display in console as
success: function(data){
console.log(data);
}
Read about ajax dataType
Related
I'm trying to load a html table created by a php code. The table should be generated by an sql query that depends on a variable from a radio input selector, but somehow i can't pass that variable via jQuery.post(). I made a simple version that has the same issue so I hope someone can help me with that:
test.php:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$("input[name$='selectOP']").on("change", function() {
var op = $(this).val();
$.post('ajax.php', {varphp: op});
$("#div1").load('ajax.php', function(){
});
});
});
</script>
<body>
<label class="radio-inline"><input type="radio" value="110" name="selectOP" id="selectOP">110 </label>
<label class="radio-inline"><input type="radio" value="115" name="selectOP" id="selectOP">115 </label>
<div id="div1">
</div>
</body>
</html>
ajax.php:
<?php
$var= "Something";
echo $var;
//$varphp = $_POST['varphp'];
//echo $varphp;
?>
So, with the two last lines of ajax.php commented, code successfully runs and the var $var loads inside div1. But if i uncomment those lines, apparently the code stops, and nothing is loaded on div1. What am I doing wrong?
You are calling $.post where you pass the argument and then calling load with no arguments. Of course you can't get $_POST['varphp'] when you call 'load' because you are not passing this variable.
you must use one of them.
you can do with this:
$.post('ajax.php', {varphp: op}, function(data){ $("#div1").html(data); }, 'html' );
or
$("#div1").load('ajax.php', {varphp: op});
but not both
thus, your code can be
$(document).ready(function(){
$("input[name$='selectOP']").on("change", function() {
var op = $(this).val();
$.post('ajax.php', {varphp: op}, function(data){ $("#div1").html(data); }, 'html' );
});
});
or
$(document).ready(function(){
$("input[name$='selectOP']").on("change", function() {
var op = $(this).val();
$("#div1").load('ajax.php', {varphp: op});
});
});
$.post('ajax.php', {varphp: op});
$("#div1").load('ajax.php', function(){
$});
These two lines are actually making two separate ajax requests, which means the server will pick them up separately. Only the first one has a POST parameter, and only the second one sets the content of the DOM object.
Try something like this:
$("#div1").load('ajax.php', {
varphp: op
});
A good practice I like is to use AJAX w/ deferred promises. You can try converting your code to the following:
$.ajax({
type: 'post', // you can switch to GET, POST, etc.
url: 'ajax.php',
data: {varphp: op},
})
.done(function(data) {
$('#div1').html(data);
})
.fail(function(data) {
// if your code fails, you can see the errors here in the console
console.log(data);
})
.always(function(data) {
// do something every time
});
The codes within the done, fail, or always callback functions will run depending on whether the AJAX call is a success, fail, or neither respectively. With this, you can troubleshoot your code easily as well, especially when the AJAX call error'd out (look inside the fail function).
Here I want to get a value from JavaScript to PHP variable without using any POST or GET method.
Here I'm giving HTML code:
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" onclick="GetValue()" class="btn btn-danger">Generate</button>
Javascript Code
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $('#base').val();
$.ajax({
type: 'post',
url: base_url,
data: {'days' : days, 'night': night},
success: function( data ) {
console.log(data);
}
});
});
});
</script>
php code
<?php
$days = $_POST['days'];
$night = $_POST['night'];
echo $days . " " . $night;
?>
Variable value not working.
You can not directly assign javascript variable to PHP variable, that's why ajax is used.
If you want to perform operations on client side variables to server-side without page refresh and using the same page then you have to write the PHP code on the top of the page before anything start of client-side and the use exit to break after the PHP response is completed. and in jquery ajax forget the URL part as you are using the same page for request and response.
Note: Make sure to include jQuery
Cover all the element in form tag so we can simply send data using serialize method.
index.php
<?php
if(isset($_POST) && !empty($_POST['days'])){
$days = $_POST['days']; // you can write the variable name same as input in form element.
$night = $_POST['night'];
//Perform any operations on this variable and send in response whatever you want it will send the response to success function of jquery ajax and you can check response in `data`
echo $days . " " . $night;
exit();
}
?>
<!--<form id='frmsbmt' method='post' action='#'>-->
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" class="btn btn-danger">Generate</button>
<!--</form>-->
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $("#base").val();
$.ajax({
type: 'post',
//url: base_url,
data: {'days' : days, 'night': night}, //$("#frmsbmt").serialize(), //form serialize will send all the data to the server side in json formate, so there is no need to send data seperately.
success: function( data ) {
console.log(data);
//alert(data);
// It will write the response in developer tools console tab or you can alert it.
}
});
});
});
</script>
You can use an AJAX call for this.
function GetValue() {
var str = document.getElementById('days').value;
$.ajax({
type: 'post',
url: 'text.php',
data: {
someValue: str
},
success: function( data ) {
console.log( data );
}
});
}
To answer your question without using any post or get method to retrieve the variable is impossible. One language is a server side language, one language is a client side language, if the two languages never communicate through an established standard and protocol passing a variable between the two are impossible. PHP is translated server side which means the client side interface doesn't really know it exists unless there is an action that is tied to a method namely get or post. An Ajax request uses either POST or GET or one of the other established methods to communicate.
i'm working with an old codeigniter. i'm calling a onchange function. i want to get data from controller and show it to a input filed which is an array.
view page code:
<select name='feed_id[]' style='width:95px;'onchange="getfeedstock(0,this.value)"><?=$this->mod_feed->get_feeds()?></select>
<span><input type='text' name='stock[]' readonly value='' class='num_txt stock<?=$inc?>' /></span>
javascript:
<script >
function getfeedstock(i,obj){
//alert(obj);
$.ajax({
url:base_url+'feed_sale/get_feed_stock',
type:'post',
data:{
feed_id:feed_id
},
success:function(data){
//alert(data);
//var stock=5;
//$('.stock').val(stock);
},
error:function(error,msg){
alert(error+msg);
}
});
}
</script>
Use Output class of Codeigniter
https://www.codeigniter.com/userguide2/libraries/output.html
it will set page header to JSON type. And pass array using json_encode();
all array of PHP will get in JSON object format in success callback of Ajax
success: function(data) {
alert(data.msg); // showing [Object][object]
//all array visible in console log Ctrl+Shift+I (in chrome)
console.log(data);
}
I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
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.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded
I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});