I'm trying to add through ajax/jquery a script into a div seconds after the page has loaded. The script itself is from a CPM network and loads a banner.
When I load it right when the page loads, the script is loaded, but if I add it through ajax, the script stays like this:
<script>content here...<script>
I get the following information after loading it by ajax: "Resource interpreted as Script but transferred with MIME type text/html"
I searched for some solutions but can't find one that works.
Here is the ajax call:
function showAds(){
$.ajax({
url:"pub-horizontal.php",
type:"POST",
async: false,
data: {link:link},
success:function(result){
$("#p1").html(result);
}
});
}
Here is pub-horizontal.php file
<div class="col-xs-12">
<div id="pub-horizontal" class="pub-horizontal">
<?php
$url = $_POST['link'];
if(!strpos($url,"article")){
include("****-horizontal.php");
}else{
include("cpmfun-horizontal.php");
}
?>
</div>
</div>
I tried to output something into the console using the script and it worked! Seems like that the problem is with the script of the CPM network that does not load after the document has loaded...
Thanks in advance.
Try adding header("content-type: application/javascript");
at the top of the php file
Related
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.
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
Here the situation:
In my html page I have a link, which onclick runs a PHP script.
<iframe style="display:none;" name="target"></iframe>
Load new tasks
I use an invisible iframe to execute the script but I stay on the same page.
This link executes script.php which updates mysql database, but in order to see new content the page must be reloaded.
Of course I can always create a separate button/link that reloads current page.
But I wonder if there is a way to execute the PHP script and reload current page with one html button.
Better use it this way:
1: Use a common Javascript Framework, for example JQuery
2: Create your Link and a Div for your Content:
Update my Data and reload my new Content
<div id="result"></div>
3: Use Jquery to add the click event to your link:
$('#reload').click(function(e) {
// Prevent from going to the link provided in href
e.preventDefault();
// make POST Request to script
$.post( "myScriptHandler.php", { value1: "1", value2: "2" })
.done(function( data ) {
// if done, refresh my Div with html content from your PHP Script
$('#result').html('')
$('#result').load('mydata.php');
});
}
You don't need AJAx - just return a script into the iframe which updates the toplevel page...
<?php
....
$new=run_updates();
print "<div id='newcontent'>$new</div>\n";
?>
<script>
var dest=parent.document.getElementById('oldcontent');
var src=document.getElementById('newcontent');
dest.innerHTML=src.innerHTML;
</script>
(not tested, YMMV)
I show you how to use Ajax in this case:
here is your html and js code:
<script type="text/javascript">
$(".link").on("click", function() {
$.ajax({
url: "your_php_script.php",
dataType: "json",
cache: false,
success: function(data) {
location.reload(true);
}
});
});
</script>
<html>
<body>
<a class="link" target="target">Load new tasks</a>
</body>
</html>
When you click the 'a' tag, the jQuery Ajax script call your php script, and when it return with success, then your page will be refresh.
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.
The following code fetch all data (by clicking a.info link) from a php file "info.php" and prints in the #content div. The problem is that it prints everything from info.php file. Can I possibly select only some part of data from info.php file to load in #content?
The reason to ask this question is that, I want to load different data from the same php file for the different links.
$("a.info").click(function(){
var id=$(this).attr("id");
$("#box").slideDown("slow");
$.ajax({
type: "POST",
data: "id="+$(this).attr("id"),
url: "info.php",
success: function(html){
$("#content").html(html);
}
});
});
Html where content is loading:
<div id="box">
<div id="content"></div>
</div>
info.php
paragraph1.
paragraph2.
For example, In the above info.php file, i only want to load paragraph1 in the #content.
I hope my question is clear. Any help will be appreciated.
Assuming paragraph1 is a div element, change accordingly:
success: function(html){
var p1 = $(html).find("div#paragraph1");
$("#content").html(p1);
}