Access another file using ajax - javascript

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

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

PHP session not persistent with AJAX

I'm working on making a website (developing locally) that requires a login for users; I've used php-login.net framework as my starting point and have my code talking to MySQL and creating sessions just fine.
I've gone through most every SO question regarding php sessions and ajax; but I still can't get my code to work how I want.
Now, I'm using ajax to call some other php scripts after the user successfully logs in, however it's not working properly. In firefox, with all the cookies, history, etc cleared, it looks like the session variables aren't maintained with the ajax call. However, if I log-out and then log back in, the session variables seem to be passed properly across ajax.
For example:
In my logged_in.php script, I'm using ajax to call another script: view_samples.php.
logged_in.php
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButtons.js
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
url: "view_samples.php",
cache: false,
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
When I log in with a browser that hasn't logged in before, I see it sets a session ID X; however when the button is pressed and the ajax call is made, I see a new session ID Y. I then log-out and log back in and see that my session ID is Y (before ajax) and that my session ID is Y when I click the button (after ajax).
I've also noticed that if I keep logging-in & out without pressing the view samples button, a new session id generated each time. However, as soon as I press the button, a whole new session id is created which seems to always be the one that is set if I log-out and then back in.
What am I missing? What's the proper way to go about ensuring the first session that is created is maintained throughout ajax calls? Should I POST the session id to the called script?
This is how I solved things (as Freaktor's comment above didn't resolve the issue) - I'm manually passing the session ID through AJAX and then setting it in the new PHP script. I'm wondering if anyone could comment on the security of this (as I'm not entirely sure how this all works)?
This and this post were helpful.
logged_in.php
<script>var session_id = '<?php echo session_id();?>';</script> <!-- store our session ID so that we can pass it through ajax -->
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButton.js
var data = {func:'getData1',session_id:session_id}; // manually send the session ID through ajax
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
type: "POST",
data: data,
url: "view_samples.php",
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_id($_POST['session_id']); // get the session ID sent by AJAX and set it
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>

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

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