javascript(ajax) and php working together? - javascript

I have a problem that my Js file is not recognizing a php variable built by ajax.
Here is an example:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
So, I'll try to explain this in the easiest way. My index.php includes a build.php which as you can see calls ajax to retrieve data from another server. This data is located in a php variable ($brandinput) which will contain many <div>,<input>,... etc. Then index.php echo $brandinput, showing all the content of the variable. But I have a js.js which change appearances in div's, input's, etc.. and is this js which is not recognizing the content of the variable $brandinput.
I'd like to know if you have more ideas or what am I doing wrong...
All the code is working well, I tested many times (except for what I said before)
The ajax call work well and Index.php displays $braninput correctly.
p.s. $brandinput is something like this:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
and yeah it works well too.

Actually this is how it supposed to be working, what you need to do is to wait for the ajax request to finish first before executing the functions in js.js
try this way
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
or (assuming js.js is loaded after the script within build.php, or js.js has to be loaded after it)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
P.S
$brandinput just hold the string whatever assigned to, and will never be changed with ajax request, where ajax success handler just manipulate the rendered DOM directly in the client side.

You can try moving your <script> tag to after your php codes like this:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
On a slightly different note, you should consider avoid embedding/intermixing PHP codes with HTML and Javascript. Take a look at this post for better ways way "passing data from PHP to Javascript".

Related

How to upload a HTML variable to a PHP file using AJAX

On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?

AJAX load php file using GET method and when loaded but some jquery plugin is not appear

Hallo I beginner learning AJAX and JQuery, Maybe this is a stupid question, but please don't judge me.
I create the live showing data, the data is loaded without refresh the page, so I use the AJAX, I load the function onload in body tag.
I use image picker, it's look good when not using AJAX GET,
and separated my file index.html is the main file, and I also add getdata.php the file show.
on index.html
<div class="col-xs-8 picker" id="viewdata">
// content getdata.php here
</div>
on script.js
function viewdata(){
$.ajax({
type: "GET",
url: "php/getdata.php",
dataType: "html"
}).done(function( data ) {
$('#viewdata').html(data);
});
}
on getdata.php
<select class="image-picker">
<?php
include "config.php";
$res = $conn->query("select * from images");
while ($row = $res->fetch_assoc()) {
?>
<option data-img-src="images/<?php echo $row['file_name'];?>" value="<?php echo $row['file_name'];?>"> <?php echo $row['file_name'];?> </option>
<?php } ?>
</select>
but the result become like this
It's like the image-picker not loaded
I'm sorry my english is bad.
Your script should be the following:
function viewdata(){
$.ajax({
type: "GET",
url: "php/getdata.php",
dataType: "html",
success: function(data){
$('#viewdata').html(data);
$('select').imagepicker(); // to reinitialize the plugin.
}
error: function(data){
// error handling
}
}).done(function(data){
// something to do after, even if it throws an error.
});
}
you need to reinitialize the plugin after ajax requests.
$.ajax({
type: "GET",
url: "php/getdata.php",
dataType: "html"
}).done(function( data ) {
$('#viewdata').html(data);
$("select").imagepicker(); //reinitialize here
});
remember that, most jquery plugins doesn't apply its effects on dynamically generated html.

div content after html() is not showing

I've got an issue with an ajax call and .html(), as you can see with the javascript below i'm using the geoloc callback to make a ajax call and refresh the content of a div.
The id of the div can be either "result-shops-ajax-desktop" or "result-shops-ajax-mobile" and in my case the php variable $type = "desktop"
The problem is that the content of the div is not reloaded despite the use of .html()
My ajax call is working because msg.response got the content i want. The .html() seems to work because the alert show the content of msg.response but I can't see it on the page :/
Another thing is weird when i put directly the id of the div, the content is shown, but when i echo the $type it's not working despite the fact that the html produced is good (the id of the div is "result-shops-ajax-desktop").
I hoped i made myself clear with my bad english, i would really appreciate any help for this weird issue.
Thanks !
Here is the javascript in my php file :
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
function geolocShow(position) {
$.ajax({
type: "POST",
url: "<?php echo $this->getUrl('shops/index/checkavailability'); ?>",
dataType : "json",
data: "sku=<?php echo $product->getSku(); ?>&lat="+position.coords.latitude+"&lng="+position.coords.longitude,
success: function(msg){
$("#result-shops-ajax-<?php echo trim($type); ?>").html(msg.response);
alert($("#result-shops-ajax-<?php echo trim($type); ?>").html());
}
});
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geolocShow);
}
});
</script>
The html generated:
jQuery.noConflict();
jQuery(document).ready(function($){
function geolocShow(position) {
$.ajax({
type: "POST",
url: "http://localhost/shops/index/checkavailability/",
dataType : "json",
data: "sku=abc&lat="+position.coords.latitude+"&lng="+position.coords.longitude,
success: function(msg){
$("#result-shops-ajax-desktop").html(msg.response);
alert($("#result-shops-ajax-desktop").html());
}
});
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geolocShow);
}
});
Try this: jQuery(document).ready(function($){ this line change to $(window).load(function(){

How to use PHP to send javascript

I posted a more specific question on this yesterday, but I think my problem is more basic than what I initially asked.
I am trying to use PHP to set a setTimeout() with a wait variable from a database, but any script I echo doesn't work, even if it involves no PHP manipulation. Take a look below.
Here is the ajax call
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
And here is the PHP it receives.
echo '<h1>Upload content to start the show</h1>';
echo '<script>
setTimeout(loadContent, 4000);
</script>';
The is showing, so I believe the ajax and the PHP is working properly. The script works properly when I place it inside the javascript file, but the script won't run when it's echoed to the page.
My problem is the javascript I echo doesn't run. How can I use PHP to send javascript to the user? Why is what I wrote not functioning?
UPDATE: I realized that when I echo script, it echoed to the middle of the body and technically is above where the script file is loaded on the bottom of the body. Can I echo to the bottom of the body?
Here is a workaround:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
var myArray = html.split("|");
var message = myArray[0];
var counter = parseInt(myArray[1]); //Minor fix
$("#contentWindow").html(message);
startCounter(counter);
}
});
}
function startCounter(counter){
//counter as the value of 1000 milliseconds are equal to 1 second
setTimeout(loadContent, counter);
}
PHP File
$refreshTimer = 1000; //This is a test
echo "Upload content to start the show|".$refreshTimer; //The message and the counter
If you return just the script portion in your php file you can set the dataType in the .ajax call to 'script' and it will execute the returned javascript (http://api.jquery.com/jquery.ajax/)
So:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
dataType: 'script',
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
Then in your PHP:
echo 'setTimeout(loadContent, 4000);';

Wordpress load sidebar.php with Ajax - loads wrong content (index.php instead)

i have almost got to load the sidebar in wordpress with Ajax, using this example (https://wordpress.stackexchange.com/questions/61830/use-ajax-request-to-load-sidebar)
but instead of loading my new sidebar-ajax.php, it always loads the index.php instead in the div called "sidebar".
I have the Feeling, that my function (get_template_part('sidebar-ajax');
) is not executed properly, but cannot find the error
in my functions.php i have inserted:
add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
function theme_enqueue_scripts() {
wp_enqueue_script('jquery');
/* load your js file in footer */
wp_enqueue_script('theme-script', get_stylesheet_directory_uri() . '/your-js-file.js',
false, false, true);
}
add_action('wp_ajax_get_ajax_sidebar', 'check_ajax');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'check_ajax');
function check_ajax() {
?>
get_template_part('sidebar-ajax');
<?php
} ?>
my js. file:
jQuery.ajax({
type: 'POST',
url: location.href,
data: { get_ajax_sidebar: 1 },
success: function(data){
jQuery('#sidebar').html(data);
}
});
and in my index.php i have added:
<div id="sidebar"></div>
any help is really appreciated. thanks!
get_template_part() is outside of php tags... why? I like to use get_sidebar(). Try this:
add_action( 'wp_ajax_get_ajax_sidebar', 'check_ajax' );
add_action( 'wp_ajax_nopriv_get_ajax_sidebar', 'check_ajax' );
function check_ajax() {
get_sidebar( 'ajax' );
}
A bit late to the party but, the reason this isn't working is because you need the correct url to call the ajax function. On the back end of wordpress this is done automatically and defined in a javascript variable called ajaxurl. On the front end you have to define this yourself, it's quite straight-forward. In your functions.php:
add_action('wp_head','yourfunctionname_ajaxurl');
function yourfunctionname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Now you can change the javascript code to:
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: { action:'get_ajax_sidebar' },
success: function(data){
jQuery('#sidebar').html(data);
}
});
More information can be found on the codex here: wp_ajax

Categories