Update img with jquery and php - javascript

i'm trying to update img cover without refresh the page using ajax and php but it does not work at all
HTML
<div class="cover" >
<img id="b1" src="<?php echo $user->picture_path();>"class="cover"/>
<div id="modal-cover" class="cov-lo"> </div>
</div>
js
$('#b2').on({
'click': function(){
$('#b1').attr('src', <?php echo $user->picture_path();?> + '?' + new Date().getTime());}
});
the input and form
<form action="profile.php" method="POST" enctype="multipart/form-data" >
<div class="hio">
Upload <input type="file" onchange="this.form.submit()" name="cover" id="bla2"class="custom-file-input" />
</div>
</form>

Ajax would look more like this:
js/jQuery:
$(document).on({'click', '#b2', function(){
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: '',
success: function(data){
$('#b1').attr('src', data);
}
}); //END ajax
}); //END #b2.click
my_ajax_processor_file.php:
<?php
$dt = new Date().getTime();
$pp = 'get user picture path here';
echo $pp .' - '. $pp;
Note that you need to have an external PHP file, which I've called my_ajax_processor_file.php, that does some additional PHP processing and ECHOs back a value.
This value is received in the AJAX code block's success function, and called data (call it what you like - the name is set here: function(data).
Note that the contents of data variable are only available within that success function.
Here are some more basic examples of what AJAX looks like:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

I think you have a fundamental misunderstanding of where the PHP and HTML are interpreted:
PHP is a server-side scripting language designed for web development (see this Wikipedia article). That means that the PHP code is executed on the server before arriving in the browser.
HTML is interpreted as plain text by the browser. No PHP is executed in the browser.
Therefore, once the JS gets to the browser, echo $user->picture_path(); has already been executed and is interpreted as plain text by the browser.
Your JS will look like this once it hits the browser:
$('#b2').on({
'click': function() {
$('#b1').attr('src', '/the/path/to/the/picture' + '?' + new Date().getTime());
}
});

Related

Place Javascript variable into a PHP Variable

I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file

Access another file using ajax

4 weeks ago I wrote a php script which adds products to a cart. As I am new to javascript, I decided to make it better by page loading using ajax.
My work looks like this:
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php
if(isset($_SESSION["products"])){
echo count($_SESSION["products"]);
}else{
echo 0;
}
?>
</a>
<form class="form-item">
<div class="cart">
<input type="submit" value="Add to Cart" class="button" />
</div>
</form>
<script>
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
$("input[type=submit]").val('Adding...'); //Loading button text
$.ajax({ //make ajax request to cart_process.php
url: "test2.php",
type: "POST",
dataType:"json", //expect json value from server
data: form_data
}).done(function(data){ //on Ajax success
$("#cart-info").html(data.items); //total items in cart-info element
$("input[type=submit]").val('Add to Cart'); //reset button text to original text
alert("Item added to Cart!"); //alert user
})
e.preventDefault();
});
});
</script>
It seems like the code stops working when I start making the ajax request to test2.php because I can't access the file test2.php and I do not really know where the error is coming from.
Thanks for helping
Yeah, debugging AJAX can be a bother . . . unless you find a way to "see" what's going on over there.
Two ideas:
(1) In PHP file, create a new file, write log entries to the file, close file when done. You can run the routine and check the file you created.
$fq=fopen('_myeyes.log','a');
fwrite($fq, '***** Created by uploader.php *****' . "\r\n" );
fwrite($fq, '$fname: ' .$fname . "\r\n" );
fwrite($fq, '$pathToImages: ' .$pathToImages. "\r\n" );
fwrite($fq, '$pathToThumbs: ' .$pathToThumbs. "\r\n" );
fwrite($fq, '$thumbWidth: ' .$thumbWidth. "\r\n" );
fclose($fq);
It works, but there's a better way.
(2) Install the Firefox extension (there's also one for Chrome, but the ff one is more reliable -- so if you're a Chrome addict like I am then use both:
firePHP
FirePHP for Chrome
Get the FFox one working first, because sometimes the Chrome one is glitchy - which is fine when you know it works, but is intimidating when you're just trying it out. You think your code is problematic, but it's the extension...
A Guide To Using FirePHP
Debugging PHP Code With FirePHP
Basically, after downloading FirePHP:
(1) Upload these files into a folder called public_html\FirePHPCore (where public_html is your webroot, as is common on most web hosting)
fb.php
fb.php4
FirePHP.class.php
FirePHP.class.php4
(2) At top of PHP file, these lines:
<?php
if (file_exists('../FirePHPCore/fb.php')) {
require_once('../FirePHPCore/fb.php');
}else{
if (file_exists('FirePHPCore/fb.php')) {
require_once('FirePHPCore/fb.php');
}else{
$fpLog = fopen('__fph_log.log', 'w');
fwrite($fpLog, '***** FirePHP did not load - FirePHPCore/fb.php NOT FOUND *****' . "\n\r");
}
}
ob_start();
$console = FirePHP::getInstance(true);
$console->registerErrorHandler();
$console->registerExceptionHandler();
Then, inside any function where you wish to use FirePHP:
function somefunction(){
global $console;
//a bunch of PHP goes here
$console->log('role: '.$fr);
//a bunch of PHP goes here
}
In Chrome/Firefox DevTools (F12), you will see these messages appear in the Console tab, same as if you issued a console.log("Hello there") in javascript.
You have eyes!
Ajax request php script must be in the same server-side, I think your ajax request has been cross-domain, try to change your url as 'localhost/test2.php'.
jQuery AJAX cross domain

How to load PHP page with variables passed from javascript

I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.
You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>
You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>
dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}
There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable

need javascript or jquery function to wrap php code (window.setInterval bootstrap list group)

Thanks for all the answers, seems like AJAX is the solution, I'll give it a try. But what about JSON? Isn't JSON an even better solution? If it is, why is AJAX more preferable?
I'm looking for a way to update this part of php code every 5 seconds, which would regenerate this bootstrap list group. what would be a good way to do it? I figure I couldn't just wrap it in window.setInterval, and refreshing the entire page is not an option. Thanks in advance.
<?php
$i=0;
// Display all room
foreach ($rooms as $room) {
$room_num = $room['room_num'];
$room_type = $room['room_type'];
$note = $room['note'];
echo '
<a class="list-group-item" >
<h4 class="list-group-item-heading" id="room_num' .$i. '" ><p>'.$room_num." - " .$room_type.'</p></h4>
<p class="list-group-item-text" id="note' .$i. '" ><p>'.$note.'</p></p>
</a>
';
$i++;
}
$rooms = "";
getList();
?>
All on the same 'page.php'
php part:
<?
if ($_POST["whatever"])
{
echo 'your shizzle here'
exit;
}
?>
Javascript part: (with jquery)
<script>
setInterval(function()
{
$.post( "page.php", { whatever: 1}, function( data ) {
document.getElementById('someid').innerHTML = data;
});
},5000);
</script>
html part
<div id = "someid"></div>
Another way to do it could be using an iframe :) But iframes won't be used in the future I think.
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
In your case, Save the PHP code which ever you want to execute in a file say php_temp.php
Now just do
setInterval(function(){
$.get("php_temp.php", function(data){
console.log(data) // data stores whatever php_temp.php echoes
});
},5000);
more on Ajax: Ajax Basics

Passing HTML content through jQuery AJAX and PHP

I want to display the content of Division in one page to another.
<div id="box-cont" class="box-content">
<?php
echo $stat;// Contains multiple images with strings
?>
</div>
Here $stat will display multiple images with few contents. And i am using jQuery AJAX to display this html in another page.
var bcont = $('#box-cont').html();
$.ajax({
type:"POST",
url:"abc.php",
success: function(data) {
document.location.href='def.php?bcont='+bcont;
}
});
And i am getting this html in def.php as
$_GET['bcont'];
This is not working for me..
Thanks in advance
A shortcut method would be to use sessions to pass the html from one page to another.
<div id="box-cont" class="box-content">
<?php
echo $stat;
$_SESSION['stat'] = $stat; // make sure session_start(); is present on this page
?>
</div>
Then, in the success handler of your ajax call
$.ajax({
type:"POST",
url:"abc.php",
success: function(data) {
window.location.href='def.php';
}
});
Finally, in def.php
session_start();
echo $_SESSION['stat'];
Note: This is not an ideal approach but will do the job for you
Ok, you want to pass the html of #box-cont to def.php, right?
You're mixing post and get. Read: http://api.jquery.com/jquery.post/
and you'll find you need to use the data-parameter.
There's something odd with the success-part. You don't reload the frame/div
where def.php is sitting. What you've done is passing data to the server
but not getting anything back, (if I read your attempts correctly).
In fact there's currently little use for a server-via here, from what you
describe it can all be done at client / JS.

Categories