JQuery, include a php file - javascript

I've been trying this for 3 days but couldn't find a solution yet. I need to load a php page with javascript. I'm using the code bellow however changing the page while the function is still working slows the page down.
$.post("connect.php?refresh_steamdata=true",{
},
function(data)
{
alert("loaded!");
});

load() is a simplified version of Post that replaces the contents of an element with the response from the server.
".load() sets the HTML contents of the matched element to the returned data."
$.post() will get you the result you are looking for but it does so Asynchronously. This means that if you plan to do something with the response you get back from the server you need to do it inside of the success function
$.post("<? echo $js_url."?refresh_steamdata=true"; ?>",{},function(data){
alert("loaded!");
// do something with data HERE
});
// not here since this will run before the data is returned

Related

How to replace php function with ajax

I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

How to write a div with jquery or javascript?

I was looking a solution to write one table, which comes from query to a DB in PHP, to a DIV, using Jquery. I'm not looking for the append's method, which I know works, but with append every time I press the button, which executes the query, the table is append to the document. The idea is not to load every time the page, but using the Jquery option, to send the post and get data back. Thank you.
UPDATE
<script>
var values = {var1: 2, var2:"Hello"};
$.get("phpfile.php", values, function(data) {
$('#id').append(data);
});
Suppose that script is call from a "onclick()"; I don't want the append each time the data, but just write in a div.
If I get you right, you just want to "update" the contents of a single div instead of reloading the whole page and this update contains a html table?!
For this purpose you could use the .html() function of jQuery: jQuery html()
In addition you should check .ajax() function of jQuery for all options/parameters: jQuery ajax()
A sample code could look like this:
$.ajax(
{
url: "yourfile.php",
cache: false,
success: function(htmldata){
$("#IdOfYourDiv").html(htmldata);
},
error: function(jqXHR, status, errorThrown){
alert("something went wrong");
}
}
);
This would load data returned for example via an echo of the php file yourfile.php, load it in the temporary variable htmldata and write/update the html contents of YourDivID with the newly returned data.
1 - on button pressed, do ajax get request (see https://stackoverflow.com/a/5942381/1163786)
2 - server receives request
3 - server sends back json response or html fragement
4a - json arrives and you start looping over these elements to build your desired html structure, then insert into the dom
4b - html fragment arrives and you simply insert it at the desired position into the dom
It's your decision, if you return a JSON respones or a HTML response.
For 4a and 4b read:
Best way to add DOM elements with jQuery
Best Practice For Creating HTML (PHP Or Jquery)?
Every piece of these steps is already explained on StackOverflow.

How do I doa Jquery.get on a JS file without executing it?

So I'm trying to make an Ajax request to pull down a js file, just to check the version number recorded inside its comments. However, if I run a jQuery.get, and the file pulled down is a javascript it automatically executes it, when I DON'T want the JS to be executed, I just want to read it and look at parts of the text of the script. How do I alter this:
jQuery.get("somefile.js", function(data) { console.log("Do stuff here.") });
So that I can run that success handler WITHOUT first executing somefile.js?
Set the dataType argument to $.get() to "text" to tell jQuery that the data is a string and it should not guess the type.
$.get("file", function(data) { alert(data) }, "text");
See here: Jquery get javascript file without running

How to include a file OR PHP code with JS?

How can I include code, for example using Javascript? Or if that can't be done, how can I include a whole PHP file?
P.S. Found some script called "require" or "include," but I prefer two lines of code instead of a huge library (using jQuery though). If that can't be done, let me know, I will try to think of something else.
EDIT:
Okay, an example of what I want to do:
function foo() { if(x = 1) return 1; else return 0; }
Then if the function returns 1, I want to either add HTML/PHP code to DIV tags OR I want to include a PHP file containing that code.
EDIT #2:
What about only HTML?
document.getElementById('test').innerHTML = 'a cool link';
That doesn't seem to work either.
I have an empty div tag with id="test" in my code.
function foo() {
if(x = 1) {$("#divid").load("somephp.php");return 1;}
else return 0;
}
Or
if (foo()) $("#divid").load("somephp.php");
The only files could Javascript includes is Javascript files, what ever the extension is. and the only way to do it is using
<script src="path/to some/file.ext"></script>
You should note that the file should be javascript text contents, else errors may be generated.
Javascript can call any file as long as it is on your server.It can't call files on the user's local files, for obvious security reasons.
However, javascript cannot, and will never be able to call PHP code, as in it cannot execute php code. This is because since javascript is client side, users can call their own javascript on your page, and execute PHP code, and potentially mess up your site or browse your backend.
You can, however add HTML code to your page using javascript, fairly simply using the innerHTML property of DOM elements or JQuery.
Javascript can also call more javascript code if you wanted, using eval()
If you wanted to call files off your server onto the page using javascript, you'd have to use AJAX
Google it up, and you can code it from scratch, or use JQuery's convenient AJAX handler.
Let's say you had a php file myfile.php that had some html/php, and you wanted to insert it into a div with the id "mydiv", or in css, "#mydiv"
If you just want to quickly load the html/php and push it into the div:
$("#mydiv").load("myfile.php");
If you want to have maximum control of the response from the html/php file:
$.ajax({
url: "myfile.php", // url to load
success : function(data) { // on success function
// data is the response of the ajax request, the response text
// you can manipulate it here
manipulateData(data);
$('#mydiv').html(data); // set the html of the div
}
});

Categories