php variables won't save properly - php

I'm posting to a php script, and I want to update some already existing variables in the script. My javascript is this :
$('.submit_html').click( function(e) {
e.preventDefault();
var requested = $('.page_select').val();
var text = new Array($('.edit_html').val(), $('.header_val').val());
$.post('data_handlers/get_content.php', {page: requested, action: 'update', text: text}, function(data) {
alert(data);
});
})
There really isn't anything complicated about the post, just a couple variables to tell the script what to do, and then a text variable, with the data in the first two spots of the array.
On the php side, I know it is getting the data correctly, but when I try to overwrite the current variable in the script, it doesnt stay saved after the php script completes.
php code:
if ($page == 'home') {
$home = $text[0];
$home_head = $text[1];
return;
}
So obviously, it is changing the variables during the execution, but reverting to the values that were manually saved in the script before. Is there anyway to actually have the values stay changed after the script ends?

It sounds like the session module is ideal for what you are trying to do.

Related

ajax data passing to php not working

Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});

How can I use Ajax to delay a PHP for loop and echo out PHP on screen?

i'm not sure whether Ajax is what I need as i'm rather stumped on where to start, but I'll describe what I would like to happen.
I have a PHP file (lets call it scan.php) that contains a For loop that iterates along an array, which holds details of local files stored in a directory on a PHP. For each item in the array (a path to a file), I would like it (presumably an ajax script?) to call another php file (lets call it info.php) and display whatever that PHP file outputs on screen, with info.php taking the filepath in that index of the array as an argument.
Within that info.php file are various (dynamically generated) divs which inserts a different value into the database depending on which div the user clicks on. When that user clicks on a div, it inserts a value into the database (via an ajax call that i've already got working) and then displays a message (i'm using a javascript window.alert). If that message is a success then the info.php function ends, an we return back to scan.php. Whatever echoed out by info.php is cleared and then the loop iterates round again.
Sorry it's a bit complex but I have no idea where to start. Could anybody give me any hints on how to get started? I've had a look at ajax but frankly I have no idea where to start and whether it's even possible to use ajax to delay the PHP for loop.
This was my script that I thought would display info.php, but it's not echoing anything into the "show" div - or anything at all:
function Search_file(path) {
$( "#show" ).empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
$("#show").html(result);
request.done(function(data) {
alert("Next file");
});
}
AJAX is asynchronous, so you haven't received your result when you are setting your html. You need to move your 'show' code inside the done handler like so:
function Search_file(path) {
$("#show").empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("#show").append(result);
alert("Next file");
});
}

How to display a response from jQuery/ajax call in PHP

So I have the following code that someone else helped me get:
function updateEpisodeSeen() {
var anime_id = <? php echo $anime_id; ?> ;
var anime_list_entry_id = <? php echo $anime_list_entry_id; ?> ;
jQuery.post("/path_to_it/my_php_file.php", {
firstParam: anime_id,
secondParam: anime_list_entry_id
}, function (data) {
//this is your response data from serv
console.log(data);
});
return false;
}
Now the .php file that is ran, I update some information and echo two variables out.
So in the console.log(data); those two variable values are shown properly. I am just wondering how I can show these values in my actual php code? Since these values are updated on the backend, I want to show the users their updated values on the front end as well. So if I could possibly set a php variable to those responses and then echo those instead, but php code isn't ran until a page refreshes so that might not be the way to go since I want the values to update without the page refreshing.
if you want to assign the response to some PHP variable you can follow this
jQuery Ajax response variable from php
if you want assign to a html variable you can do that using Jquery
$('#ID OF FIELD').val(data.text);
or
$('#ID OF FIELD').html(data.text);

Refresh a div automatically when a PHP variable is updated

I have a div that calls a variable. When that variable changes, users need to refresh the page to see the new value. The variable is pulled from a separate PHP file.
I'm wondering if there's a way to use ajax to automatically update the div without the user refreshing the browser when it sees the PHP variable has been updated.
You could periodically check if there have been any change to the variable using ajax and if that is the case you could update the div.
var previousValue = null;
function checkForChange() {
$.ajax({
url: 'http://example.com/getVariableValue.php',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
I havn't tested the code, but it should be something like that. Will get data from http://example.com/getVariableValue.php, you'll have to fill in some information about the AJAX request. I'm assuming you know how to modify the code for your specific data format, be it XML, JSON or text.

Image wont change

I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';

Categories