How do I pass jQuery value to php? - php

I have this little piece of code and I would like to pass the value to PHP.
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
Is there a way to do this? (new at jQuery)
Many thanks!

check this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
$.ajax({
type: "POST",
url: 'edit.php',
data: "window_size=" + size,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
alert(result)
}
});
</script>
then create edit.php
<?php
print_r($_REQUEST);
?>
if you want to save this value then use this code
<?php
session_start();
echo $_SESSION['php_value'];
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
$.ajax({
type: "POST",
url: 'edit.php',
data: "window_size=" + size,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
alert(result);
//window.location.reload();
}
});
</script>
and update edit.php as like
<?php
session_start();
$_SESSION['php_value'] = $_REQUEST['window_size'];
echo $_SESSION['php_value'];
?>
you want to see this value or use then refresh this page
if you want to use this variable in other page then use this
//first page first set it
$_SESSION['php_value'] = $_REQUEST['window_size'];
//second page or other page and use it
$var_value = $_SESSION['php_value'];

No you cannot. JQuery plays on client and php on backend.
If you want to pass some values from Client (Jquery/Js) to Backend (PHP), you need to either submit a form or make an AJax call to server.

You should research about jQuery ajax. This can be your solution for sending data to server from client.

Yes. Use the code below to send the value of size to your php script:
var ajax_call = $.ajax({url: '/your_php_script.php', data: 'size='+size, success: function(data) {
}});

Related

Get results and fade

Don't know what is wrong, I've tried everything. The code should take simple info from PHP file and for each should fade in delay and out. I was successful with getting all the data at once but it is not good.
<script type="text/javascript">
$('button').fadeOut('slow')
var progressBar = $('.progress-bar');
var percentVal = 0;
window.setInterval(function(){
percentVal += 10;
progressBar.css("width", percentVal+ '%').attr("aria-valuenow", percentVal+ '%').text(percentVal+ '%');
if (percentVal == 100)
{
percentVal = 0;
}
}, 500);
$(document).ready(function() {
$("button").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "submit.php",
data: 'html', //expect html to be returned
success: function(data){
for(var i=0;i<6;i++){
$('.input-group').html(data).fadeIn(500).delay(1000).fadeOut(500);
}
}
});
});
});
</script>
PHP CODE:
$array= ['apple','orange','grapes','avocado','banana'];
$indexedOnly = array();
foreach ($array as $row) {
$indexedOnly[] = array_values($row);
}
echo json_encode($indexedOnly);
I think you need to abandon the loops, they wont allow you to pause to wait for the animation to finish. You can try something like this where you handle each element in data then using the callback functions of .fadeIn and .fadeOut to call the next one
function disp_next() {
$('.input-group').text(data.shift()).hide();
$('.input-group').fadeIn()
.delay(1000)
.fadeOut(function(){
if(data.length !== 0) {
disp_next();
}
})
}
disp_next();
You also need to change your dataType to json as you are expecting json from the server. Here is your jquery updated
$(document).ready(function() {
$("button").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "submit.php",
datatype: 'json', //expect html to be returned
success: function(data){
data = Object.values(data);
function disp_next() {
$('.input-group').text(data.shift()).hide();
$('.input-group').fadeIn()
.delay(1000)
.fadeOut(function(){
if(data.length !== 0) {
disp_next();
}
})
}
disp_next();
}
});
});
});
Try something like this, but if you want the animation of each element to wait for the previous one to finish you need to change the approach.
$.each(data, function(i, value) {
$('.input-group').html(data).fadeIn(500).delay(1000).fadeOut(500);
});

Using Jquery AJAX to POST variable in PHP

I believe I have the right syntax but am missing something important. Been searching on here for a while but can't figure out why the POST variable is not being detected. Basically my .ajax is firing because my test statement has been changing due to the value but some reason can't receive variable via $_POST (i.e. my echo in php echo that it is not firing) Also the native file and php that I am sending it to are the same file blankFormTemplate.php but don't think that should be an issue.
$(document).ready(function()
{
var $selectedContexts = [];
$('.allContextField').change(function(){
//alert($(this).val());
hideField = $(this).val();
$('#'+hideField).remove();
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: addedContext=hideField,
cache: false,
success: function(addedContext)
{
$('#test').html($('#test').html()+hideField);
}
});
});
});
in my PHP blankFormTemplate.php:
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
Any help would be greatly appreciated.
Thanks,
Your javascript
$(document).ready(function()
{
$('.allContextField').change(function(){
hideField = $(this).val();
$('#'+hideField).remove();
});
if (hideField.trim()) {
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: (addedContext:hideField},
cache: false,
success: function(msg)
{
$('#test').html(msg);
}
});
}
});
Your PHP
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>

Merging localstorage with ajax

How would I merge these two bits of code and can someone explain what the key and value would be.
I'm building a notifications system and I'm wanting to store the last new notification_id but not have it inserted into the div over and over again if its the same one, so then the ajax searches for anything else within my server that maybe new.
Ajax
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(dataHandler){
}
});
}
setInterval(loadIt, 10000);
</script>
Localstrorage
window.localStorage.setItem('key', 'value');
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
You've confused oldschool Ajax by hand with jQuery. The parameter to the success function in jQuery is not a function name or handler. Its a variable name that will contain the response from the server. The success function itself is equivalent to the handler functions you would have created doing it the old way.
So not:
success: function(dataHandler){ }
...
...
var dataHandler = function (response){
But rather:
success: function(response) { doCallsToSaveToLocalStorage(response); }

jquery-ajax not posting data

Refer to the following code, this script doesn't post the "limit" variable to the next page
MY JS Code:
$(document).ready(function(){
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
var dataString="2";
$.ajax({
type:"POST",
url: "load_data.php",
data: { 'limit': dataString },
success:function(data) {
$('#leftNews').load('load_data.php');
}
});
}
});
});
PHP CODE
<?php
if(isset($_POST['limit'])) {
echo $_POST['limit'];
}
else echo 'asd';
?>
Everytim i run this i get "asd" printed
That's because you're loading the PHP page, instead of loading the result.
$(document).ready(function() {
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
var dataString = "2";
$.ajax({
type: "POST",
url: "load_data.php",
data: {'limit': dataString},
success: function(data) {
$('#leftNews').html(data);
}
});
}
});
});
You make two different ajax requests. The first one is a POST-request with limit-variable set. The more important one is the second one, it is a load-requests (which is a get-requests without any parameters). Of course, your last request which shall print out the result does not containt any parameters, thats why "asd" is printed - the limit is NOT set!
In order to get the wanted result, you should change it to:
success:function(data) {
$('#leftNews').html(data);
}

Javascript posting multiple times

I have a javascript coding that pulls a PHP file, and if it updates the database, it will echo Success: Age Updated! It works and all, But When I click it multiple times it will start to do this.. Sucsess: Age Changed! Sucsess: Age Changed! Sucsess: Age Changed! .. Here's the Javascript.
function UpdateAge(Age) {
var newage = $("#NewAge").val();
var dataString = 'newage=' + newage;
if (newage.length < 2) {
$('#Required').fadeIn(300);
$('#Mask').fadeIn(300);
} else {
$.ajax({
type: "POST",
url: "update_age.php",
data: dataString,
cache: false,
success: function (updateage) {
$("#UpdatedAge").append(updateage);
$("#UpdatedAge").show().fadeOut(1200);
}
});
}
}
How would I get it to just display Success: Age Updated! once, instead of it just multiplying everytime I click?
Here's the Button for the onClick
<input type="submit" value="Update" onClick="UpdateAge(<?php echo $age ?>)" />
Looks like you just need to empty your #UpdatedAge Element each time.
function UpdateAge(Age) {
var newage = $("#NewAge").val();
var dataString = 'newage=' + newage;
if (newage.length < 2) {
$('#Required').fadeIn(300);
$('#Mask').fadeIn(300);
} else {
$.ajax({
type: "POST",
url: "update_age.php",
data: dataString,
cache: false,
success: function (updateage) {
$("#UpdatedAge").empty();
$("#UpdatedAge").append(updateage);
$("#UpdatedAge").show().fadeOut(1200);
}
});
}
}
the problem is you keep appending, change the content instead (just change append to html)
$("#UpdatedAge").html(updateage);
Just use something as
function UpdateAge(Age) {
var newage = $("#NewAge").val();
var dataString = 'newage=' + newage;
if (newage.length < 2) {
$('#Required').fadeIn(300);
$('#Mask').fadeIn(300);
} else {
$.ajax({
type: "POST",
url: "update_age.php",
data: dataString,
cache: false,
success: function (updateage) {
$("#UpdatedAge").html(updateage);
$("#UpdatedAge").show().fadeOut(1200);
}
});
}
}
As .html replaces the content of #UpdatedAge and don't append it to the content, as .append does.

Categories