Jquery:
$.ajax({
type: "GET",
dataType: 'html',
url: "order",
timeout: 30000,
cache: true,
success: function(data, status, xhr) {
$('#changes').append(data);
alert("x amount of changes have been updated");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
PHP:
$stmt = $db->prepare("SELECT * FROM `orders` WHERE `date` > NOW()");
//Other MySQL stuff
Basically I have no idea how I would do this, but I want to alert a user everytime there is a new order, but how exactly would I go about on the PHP side of alerting the user that there has been a change?
My brain is just not working today, I need to detect how many orders there have been and then append just the new orders to a table (And not the old ones)
Can I parse json from my order.php page but not display it and only display the HTML?
I really hope someone can help me out!
Yes, you can send and receive JSON from PHP. The following is from a production system, but I have removed a lot of code from it just to show you the important stuff. You will need to add error checking logic, etc (the code may have syntax errors (typos), but is, as I said, functional):
<script>
function checkForNew() {
var POSTData='CMD=getNewInvoices&'; /* Your PHP script can handle different requests */
POSTData=POSTData + 'myData=' + pseudoSave;
$.ajax( {
type: 'POST',
url: './checkForNewInvoices.php',
data: POSTData,
async: false,
error: function(data) {
retData=data;
// Do error stuff
},
success: function(data) {
retData=data;
retJ=JSON.parse(retData);
// Check here if valid JSON
}
});
setTimeout(function() { checkForNew(); }, 5000);
}
$(document).ready(function() {
checkForNew();
});
</script>
<?php {checkForNewInvoices.php}
...
...
echo json_encode($myJsonData); /* If data is in an array */
?>
Here is what I would do (logic/thinking {warning may be flawed :-)} ):
When I save the order (update/insert) I would update a text file (or db field) with an integer or 'flag (true/false)'.
My web-site, when loaded, will start with the count and the status of the flag, check for orders that don't have the processed flag and keep a local 'tag' of the loaded status.
I will then check if the flag/int has changed (order without the status flag). If it has changed or has orders without the 'shown/processed' status then I know there are new orders/invoices and I will then send a server query (ajax) to retrieve the orders or count, etc.
Worries/conditions:
If the orders come from all over and the web sites are accessed by lots of people (many to many).
The orders come from lots of people but only one person is loading the monitor site (many to one).
Order site is one place and monitor site is one (one to one - easy).
Trust this helps.
Happy Easter!
Related
I'm new to AJAX and not so good at PHP. I'm trying to simply send a string saying "Hello" to my PHP page using the JQuery $.AJAX function. So far I have successfully got AJAX to send the information to the page and log it in the console but the data doesn't get stored into the POST variable.
Please keep in mind I'm not being lazy by coming to this forum and asking for help but I have no other choice because I've been searching for about 2 days now on how to fix this problem and haven't found anything that's worked.
Here's my HTML (order.html) - This isn't all my HTML but it's all you will need):
<html>
<body>
<form method="POST">
<button id="order-btn" type="submit" formaction="PHP/sendMail.php">Order</button>
</form>
<!-- JavaScript/JQuery links -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="JS/order.js"></script>
</body>
</html>
Here's my JavaScript (order.js - Once again, I'm only providing necessary code)
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "PHP/sendMail.php",
type: "POST",
data: {data: txt},
dataType: "html",
asyc: true,
success: function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
Here's my PHP(sendMail.PHP - I'm only providing necessary code)
<?php
if(isset($_POST['data'])) {
$data = $_POST['data'];
echo $data;
} else {
echo "Failed to grab data.";
}
Just to clarify, in my actual code the URL is the full URL of my website page.
Let me know in the comments if you would like to see the site to get a better understanding of how and why I need this feature to work.
UPDATE & SOLUTION:
From the help I received I now understand that AJAX will only update information on the current page (So, for example, if you have an AJAX function on index.html then you can only run AJAX on that page and can't transfer information across pages)
To solve my problem I stopped sending users to the sendMail.php page and instead changed the HTML content of the page I was currently on (order.html) in the $.ajax success method.
Here's the updated JavaScript code:
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "order.html",
type: 'POST',
data: {data: txt},
dataType: 'html',
success: function(data){
if(parseInt(data)!=0) {
$("body").html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
I'd like to thank everyone that helped :)
$.ajax({ //create an ajax request to load_page.php
type: “POST”,
url: “load-page.php”,
data: {page:url}, //with the page number as a parameter
dataType: “html”, //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$(‘#pageContent’).html(msg); //load the returned html into
pageContet
$(‘#loading’).css(‘visibility’,’hidden’);//and hide the rotating
gif
}
});
Like in above example load-page.php is called so data returned is going to dispaly in pageContent which is the id of some div etc and this div is not on load-page.php this div is on the page from where this ajax request is sent.
may be it will make sence
reference link: Reference Link!
It's not like this way as you have called sendMail.php this file and the data returned will be available in the page from where it was called.
Let suppose with button click on page A you called sendMail.php, so the ajax response returned to page A not to sendmAil.php.
First thing, garantees that your API is working. Using a toolchain for API, like postman or insomnia.
If your api is returning what you want, then you go to your javascript code, because I don't see any problem in your code. I even used your code and worked.
Then use session
session_start(); //at the top
$_SESSION['mydata'] = $data; // something like it
but as far as I know it's necessary to refresh the page for session to work. please try it
i have used car selling site. users can post their car for sale. I want users should be able to see the expected price of their car when they click on expected price field without submitting the from. function input is to be passed as variable. Se below image
Search for ajax. For example (with jQuery)
$.ajax({ url: "website.com/phpfile.php?var=" + encodeURIComponent(value),
cache: false,
timeout: 10000,
success: function(response)
{
// do something with the result, or omit the whole success if not needed
},
error: function(jqXHR, textStatus, errorThrown)
{
// notify user about error?
}
});
There are easier, more oriented versions, like $.post or $.get
Check out here: http://api.jquery.com/category/ajax/
I have a select box(list box) where it has 3 values drop down like Pending,Approve,NotApproved and when I select any one of them I want to fire a query so that I get data from database
like select * from table where status="Pending" without reloading page.
can any one help me how can I get data from database without page refresh in a php file.
Thanks in Advance
You can use a get or post AJAX request like so:
jQuery.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'xml/html/script/json/jsonp', // I guess html will be do or JSON if you are returning in a JSON format
data: {param1: 'value1'}, // Here you can send any additional parameters like status ( pending etc.)
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
// in the data variable you will receive the data from your PHP file if the request was succesfull
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Reference: https://api.jquery.com/jQuery.post/
You should use AJAX for this (as is said in comments). You have can use :
XmlHttpRequest,
jQuery : Less code than an ordinary XmlHttpRequest and easier to implement. Perfect for beginner but heavy if you are looking for performance (to my mind),
And some libraries that I don't know.
I'm been trying for many hours to get this working, just a basic long polling to a php script on the web server. I am testing it by having a text file which I check the last modified time of and compare it to the time the javascript sends a request. If the date of the file is newer then I send back a message "update". When I load the page in my browser it sends the request and waits as expected which I can verify using Chrome dev tools but then when I edit the file (ie. change the modified date) the update.php script never echos the update message. Instead it just continues until it times out.
I think it might have something to do with caching because if I copy the URL that the JS requests into a separate tab it also doesn't respond but if I change the random parameter that jQuery attaches to prevent caching I get the desired "update" message back. Any ideas what is wrong?
Thanks
The javascript running on the main page:
<script>
window.onload = function longPoll(){
var d = new Date;
$.ajax({
url: "http://localhost/site/update.php?time=" + d.getTime(),
success: function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
//error message here
},
type: "GET",
cache: false,
complete: longPoll,
timeout: 600000
});
}
</script>
The update script:
// while the file is NOT newer
while(!(filemtime('./test.txt') > $client_time)) {
sleep(1);
}
echo 'update';
?>
Somthing to keep in mind:
1: never trust what you got from client side like time.
2: The time you send to the server with client side is not really what you except, so if the user time is set wrong like 11 jun and in server your current time is 10 jun, the
filemtime('./test.txt') > $client_time
always return false
3: use clearstatcache() when you check file status
4: sleep(1) is too high, specially when you want to deploy high usage website, change that to more than 10 ms
5: as vher2 said, use this code for complete:
complete: function(jqXHR, status) {
if (status === 'success'){
setTimeout(function(){ longPoll() }, 1000);
}
}
Use this code to check current time on server and time time that received from user:
var_dump(time() , $client_time);
Try this:
complete: function(jqXHR, status) {
if (status === 'success'){
setTimeout(function(){ longPoll() }, 1000);
}
}
I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.