Jquery AJAX to retrieve PHP variable - javascript

I have a php script that makes my page load slowly because it fetches API data from another site and parses it so I want to make it load last. I'm reading AJAX is the way to go because it is asynchronous. Below is my AJAX code so far. All I want to do at the moment is have AJAX fetch a variable from PHP and display it but I can't get it to work. I think I'm really close though.
Here is the DIV I want it to load to and the script trigger.
<div id="results"></div>
<script type="text/javascript">ajax_lastcount();</script>
Here is the AJAX script
<script type="text/javascript">
function ajax_lastcount() {
var hr = new XMLHttpRequest();
hr.open("GET", "/viewcount.php", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = data;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
Here is viewcount.php page
header("Content-type", "application/json");
$lastcount = "ten";
echo json_encode($lastcount);

Using jQuery this could be achieved by this code (called automatically after the page's DOM is loaded):
$(document).ready(function() {
$.ajax({
url: '/viewcount.php',
type: 'get',
dataType: 'json',
})
.success(function(data) {
$('div#results').html(data);
});
});
If you want to perform simplified GET or POST request, you can also call this instead:
$(document).ready(function() {
$.get('/viewcount.php', {'optional_params_object':'value'})
.success(function(data) {
$('div#results').html(data);
});
});
or
$(document).ready(function() {
$.post('/viewcount.php', {'optional_params_object':'value'})
.success(function(data) {
$('div#results').html(data);
});
});

Related

How to use jQuery in WordPress shortcode?

I want to show this jquery variable's value into WordPress shortcode.
I already tried but not working.
Jquery code:
jQuery('.button').on('click', function(){
var post_id = jQuery(this).attr('data-product_id');
//alert(post_id);
});
PHP Code:
echo do_shortcode('[product_page id="36"]');
It's a bit more complicated than you might think. What you have isn't going to work because PHP processes on the server and jQuery runs in the clients browser.
A potential solution could be.. on button click send the variable (post_id) via an AJAX request to the server, this would then process and generate the shortcode html which will then return the html for you to use in your JS.
Below is an example of what I mean...
jQuery
$('.button').on('click', function() {
var $button = $(this);
var post_id = $button.data('product_id');
$button.prop('disabled', true); // Disable button. Prevent multiple clicks
$.ajax({
url: myLocalVariables.ajax,
method: 'post',
data: {
action: 'render-product-shortcode',
id: post_id
}
}).then(function(response) {
if (response.success) {
var $shortcode = $(response.data);
// Do what ever you want with the html here
// For example..
$shortcode.appendTo($('body'));
} else {
alert(response.data || 'Something went wrong');
}
}).always(function() {
$button.prop('disabled', false); // Re-enable the button
});
});
functions.php
// Set local JS variable
add_action('wp_enqueue_scripts', function() {
wp_localize_script('jquery', 'myLocalVariables', [
'ajax' => admin_url('admin-ajax.php')
]);
});
// Handle AJAX request
add_action('wp_ajax_render-product-shortcode', 'render_product_shortcode');
add_action('wp_ajax_nopriv_render-product-shortcode', 'render_product_shortcode');
function render_product_shortcode() {
$product_id = !empty($_POST['id']) ? (int)$_POST['id'] : 0;
if ($product_id) {
return wp_send_json_success( do_shortcode('[product_page id="'.$product_id.'"]') );
}
return wp_send_json_error('No ID in request.');
}

How can I make a Ajax request & response with firefox OS?

I'm having a php function which returns a Json data from db.
I want get all the json from the function and display that into my Firefox App. I tried Jquery Ajax. But its not working.
Any other library or Ajax coding?
var a=1;
$.ajax({
url:"http://localhost/shop/home/home/demo",
type:"POST",
data:{b:a},
success: function(msg){
alert(msg);
}
});
It's not working with firefox app. Help me.
You must use the mozSystem property. Here's an example using native XMLHttpRequest.
var xhr = new XMLHttpRequest({
mozSystem: true
});
xhr.open("POST", "http://localhost/shop/home/home/demo");
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send("b=" + a); //serialized data
Hope it helps!

Jquery Ajax function is not working while calling the Servlet

I am facing some problem while calling ajax. Can anyone look at my code and suggest something to solve my problem
function search(file,input){
$.ajax({url:'/Searchandhighlight?name='+input+'&file='+file,type:"post",
success:function(){
$("#bodyy").html();
}
});
}
I am using ajax to call the servlet and servlet changes some contents of database and after success I am trying to refresh my "#bodyy" div.
Thanks in advance
Firstly let us know what file variable holds.
Normally Ajax call with parameters goes like this. dataType depends on what kind of response you are expecting.
$.ajax({
type: "POST",
url: "/Searchandhighlight",
dataType: "json",
data: {"name" : input, "file" : file},
success:function(data){
if(data){
alert("success");
}
},
error:function(){
alert('failed');
}
})
I finally solved my issue by following code
function search(file,input){
if(input != "") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Searchandhighlight?name=" + input + "&file=" + file, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location.reload();
}
}
xmlhttp.send(null);
}
}

Transmit data script Ajax and Script PHP

I'm trying to send data from a script using Ajax to a script PHP. And I have this error : Notice: Undefined index: background. Thanks for your help.
ajax.php :
<?php
$mavariable2=$_POST['background'];
echo $mavariable2;
?>
script.js :
function open_script(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "ajax.php";
var back = "blue" ;
var backgroundf = "&background="+back;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(backgroundf); // Actually execute the request
//window.location.assign('ajax.php');
}
If you already have jQuery as a dependency in your project try using $.ajax().
var request = $.ajax({
url: "script.php",
method: "POST",
data: { background : 'blue' },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
More Information: http://api.jquery.com/jquery.ajax/

Javascript AJAX call to Jquery Call

In order to have my code written almost fully written in Jquery, I want to rewrite an AJAX call in Jquery.
It's a call from a webpage to a Tomcat servlet.
Similar code of my present situation:
var http = new XMLhttpRequest();
var url = "http://example.com/MessageController?action=send";
http.onreadystatechange = function ()
if (http.readyState == 4)
{
if (http.status == 200){ var response = http.responseText;}
else {/*code2*/}
};
http.async = false;
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(string);
Which would be the best way to do this? .ajax or .post? Could you help me with some pseudo code to start this?
Use .ajax or (as you are using POST) .post:
$.ajax({
url: "http://example.com/MessageController",
type: "POST",
data: { action: "send", yourStringName: "something" },
async: false, // make sure you really need it
contentType:'application/x-www-form-urlencoded'
}).done(function(response) {
console.log(response);
});
It doesn't matter which one you use, because .post is shorthand for .ajax.
You can use jQuery post.
var url="MessageController"
$.post(url, { action : "send"} ,function(data){
//response from MessageController is in data variable
//code 1
alert(data)
}).error(function(){
alert("error"); //code 2
})
Assuming MessageController is some url in your domain and you are aware of the same origin policy

Categories

Resources