Passing HTML content through jQuery AJAX and PHP - javascript

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.

Related

Update img with jquery and php

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());
}
});

Getting Javascript/jQuery and PHP To work together

UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.

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

PHP Script in OnClick Event

This IS a duplicate from Calling a php function by onclick event, but I have a question on it. The answer I had a question on is by timpanix, and basically it won't work.
He said to execute some PHP code in a On Click event do this:
onclick="document.write('<?php //call a PHP function here ?>');"
and call the PHP function. Yet whenever I try it:
<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>
it prints out ');" > Update Profile, yet I have no clue why. It is inside of a form, and the PHP function looks like this:
<?php
function profileupdated() {
?>
<div id="profileupdated"> Profile Updated </div>
<?php
}
?>
Why would the code be displaying this? Please help! :) Thank You.
EDIT
The code does not seem to be writing Profile Updated to the page, any idea why?
function profileupdated() {
echo "<div id='profileupdated'> Profile Updated </div>";
}
Also if you only want to print this value to your tag why you're using function? Assign it to a variable.
like
$myVar = '<div id="profileupdated"> Profile Updated </div>';
Then use this variable where you want?
you should echo or return your function body. Carefull! I changed quotes!
Your PHP function is writing to the page already, rendering the document.write (javascript) useless. Try this:
<?php
function profileupdated() {
return "<div id='profileupdated'>Profile updated</div>";
}
?>
I do want to note though that you might want to consider a cleaner way of doing this: If you just want to display a fixed text ("Profile updated"), stick to pure client-side Javascript.
Otherwise (if there's logic to be done server-side), you might want to decouple server and client and use an AJAX call and JSON to transfer your data.
PHP is a server side programming language, you are executing the JavaScript on the client side.
If you want to call a PHP script from your JavaScript you need Ajax, f.e. jQuery.

How to use .load() for refresh div in same page?

I am trying to make an on-line user content which refresh it self and calls every time php function.
I used
<div class="onlineFriends">
<?php
$members = find_online_friends($_SESSION['id']);
foreach($members as $member):?>
<div class="user" href=<?php echo ($member['f_id']); ?> rel="popup_name" >
<img src=<?php
$avatars = find_avatar($member['f_id']);
foreach($avatars as $avatar)
echo ($avatar['src']) ?>
/>
</div>
<?php endforeach; ?>
</div>
<script>
$(function(){
var refreshId = setInterval(function() {
$('.onlineFriends ').load("# .onlineFriends ").fadeOut("slow", function () {
$(this).fadeIn("slow");
});
}, 50000);
});
</script>
This works good. But .load() function I think loads first all entire page and then calls .onlineFriends. I can see it with firebug on console. it returns all page source code as GET answer. My question is it will make slow down ? Because I will use this method 5 times for other div contents and each time each functions will load full page.
Also I tried to create separate .php file but I have in php code some dependences and I cant run this function in another file.
Any request to your page will result to it's full code. You can specify in php to send back only wanted part of page when specific GET or POST data is present and use $.get() or $.post() to get them.
Because I will use this method 5 times
On the same page? Then it's better to replace them from the one of $.get() and $.post() data during callback function.
Create other page friends.php
and in page index use cod java/ajax and use jquery-min
<script src="js/jquery-1.10.1.min.js"></script>
$(document).ready(function() {
$("#center").load("friends.php?var=<?php echo $member['f_id']; ?>");
var refreshId = setInterval(function() {
$("#center").load('friends.php?var=<?php echo $member['f_id']; ?>');}, 9000);
$.ajaxSetup({ cache: false });
your div html use
<div class="center"></div>
your friends.php use
<?php include"your bd here" $jab = $_GET['var'];
'select bd'
echo $resultyourneed['f_id'] ?>

Categories