Passing PHP variable ID to create and fetch dynamic Modal content - javascript

I tried several answers here but I think I am completely lost about figuring my issue.
So, I am creating post list of different post for Book article which each of the article have different contents to pull-out from the backend. To ease the multiple-click-page, I chose to use Modal. Got some info red from some Bootstrap Modal answers comparing/using it to my UIKit Modal, but it seems not working correctly.
This is mixed of WordPress and Core Function of UIKit Modal
Code Fig.1
<?php echo $book_button; ?>
- Modal Trigger
<div id="book-info" class="uk-modal">
<div class="uk-modal-dialog">
<a class="uk-modal-close uk-close"></a>
<div class="fetched-data">
<!-- Content To Fetch -->
</div>
</div>
</div>
- Modal Container
Code Fig.2
$(document).ready(function(){
$('.uk-modal').on({
'show.uk.modal': function(){
var postID = $(e.relatedTarget).data('content');
$.ajax({
type: 'post',
url: 'wp-content/themes/mytheme/inc/structures/modal/modal-book.php',
data: 'data='+ postID,
success: function(data) {
$('.fetched-data').html(data);
}
});
}
});
});
- Ajax Script
Code Fig.3
<?php
$postID = $_GET['data'];
$postname = new WP_Query([ 'post_type' => 'causes', 'posts_per_page' => 1, 'p' => $postID ]);
while ( $postname->have_posts() ) : $postname->the_post();
the_field('content_modal_box');
echo '<br>';
echo $post->post_name;
endwhile;
wp_reset_postdata();
- modal-book.php file
Code Issue 1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is my message from the console, reflecting to my path: wp-content/themes/mytheme/inc/structures/modal/modal-book.php
Conclusion
On the first thought, I don't know if the code was technically passing my variable through the Ajax and I am not sure why it was responding as 500 (Internal Server Error). Hope you can help me figure out the it.

Ok, after sometime to debug my whole codes and did some more research. Here's the working solution to my issue.
First, I did realized that the data I am passing is "Empty" which is cause to my modal resulting "500 (Internal Server Error)". Second, My Ajax "Data" also don't know my variable value which resulting error because it is empty. And while triggering the modal to open, there is no data-content passing to any of my script.
Solution
<?php echo $book_button; ?>
- Revised Modal Trigger
$('.open-modal').on('click', function(){
var postID = $(this).attr('data-content');
var modal = UIkit.modal(".uk-modal", {center: true, bgclose: false});
if ( modal.isActive() ) {
modal.hide();
} else {
modal.show();
$.ajax({
type: 'GET',
dataType: 'json',
url: 'wp-content/themes/mytheme/inc/structures/modal/modal-donate.php',
data: 'data='+postID,
success: function(data) {
$('.fetched-data').html(data);
}
});
}
});
- Revised Ajax Script
After realized all things here. It went fine and working correctly. I revised the Ajax script and match the type function i am using over the "modal-book.php" file and add change the event modal to raw js script of the modal since I am having difficulties to clear the content when closing the modal.

Related

I want to show data which got from a php file to all tab pages by using ‘storage event’

I want that when I click on logout, ck() function will be fired and there is an ajax method. By ajax method I have send some data to object.php file. After success all process I will get I got It string. Now I want that when this data I will get, 'storage' event will execute and I got It will show all index.php tab pages at a times without any refresh or click again logout. I am very very sorry for my poor English. It is my first question.
index.php:
<script>
function ck(){
var ok="thx";
$.ajax({
type:"GET",
data:{mt:ok},
url:"object.php",
success:function(html){
if(html!=""){
localStorage.setItem('store-it', html);
window.addEventListener('storage', function (event){
if(event.key=='store-it'){
$(".show").text(event.newValue);
}
})
}
},
});
}
</script>
<p onclick="ck()">logout</p>
<p class="show"></p>
object.php
<?php
if(isset($_GET['mt']) && $_GET['mt']=="thx"){
echo "I got It";
}
?>

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

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

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.

Link to a page and trigger ajax via the same button

I'm trying to make a div button which triggers ajax and links to a page which the ajax is posting data to. I have the ajax working on click, but can't seem to get the link to work at all with it, all the ways I've tried to get the link working do nothing.
I have a div button:
<div class="cman shadow1" id="search_button" value="carSearch"/>
Start Search
</div>
Which triggers:
function carSearch()
{
$.ajax({
type: "POST",
url: 'searchpost.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val());
}
});
}
Edit:
Feel I should mention that the page I wish to link to is atm:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$mpg = (int)($_POST["mpg"]);
header("Location: home.php");
exit;
}
?>
I wish to use this to gather all of the search fields the user enters to then load the search results page. The above code for it is just for testing right now.
I mention this as user #Doge suggested doing document.location.href = "searchpost.php" in the success handler of the ajax, this did cause the page to change but the page didn't run the isset and the redirect, so the js variable wasn't posted, or it was but this instance of the page didn't get it.
The isset and redirect do work as using the XHR Network tab on my page the page it is to redirect to appears.
If you must do this via js then create a hidden form, populate it and submit it:
html:
<form method="post" id="hiddenform" action="searchpost.php">
<input type="hidden" name="mpg" id="mpg"/>
</form>
js:
function carSearch()
{
$('#mpg').val(yourjsvariable);
$('#hiddenform').submit();
}

Categories