Get data from mysql database table without page reload - javascript

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.

Related

Why can't my ajax get request find my handler route when I add arguments?

I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.

AJAX/PHP/MySQL - Detect database changes and alert user?

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!

How to pass php variable to function in separate file and get results back without submitting the form?

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/

unable to run script on dynamically json parsed content

I would like to give a high level explanation of what's my issue because I can't put up complete code which is too complex.
I have a button. when I click on the button, it pulls data from fb parses it and adds it to the page. Now after it is loaded to then page.. I want to run a script on the loaded content. I am running the script after the data is parsed but somehow it shows that element is not loaded by the time script started running. can some one throw some light.
$("somebutton").on("click",function(){
LoadAndParseFbData();
});
function LoadAndParseFbData(){
//loaded the json, parsed it and added to the page.
anotherScript();
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
This is what i am trying on high level. please help thanks :)
$("somebutton").on("click",function()
LoadAndParseFbData();
});
function LoadAndParseFbData(){
FB.api(path, method, params, function(){
//loaded the json, parsed it and added to the page.
anotherScript();
});
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
Run anotherScript() from within the ajax success callback:
$J.ajax({
url: url2,
type: "post",
data: { data: "yourdata", },
success: function (data, textStatus, jqXHR) {
anotherScript();
},
error: function(jqXHR, textStatus, errorThrown) {
/*error handling code here*/
}
});

After submit make ajax call!

I won't to write some values into database with ajax on submit event, after that I want to query the database (with ajax) once again to check for some response that will be written after the first ajax action. Last, if the response values are "ok" then I want to refresh the page, else I will make the query 2 secs latter till the response gets ok!
//Write into database form values on submit event
$('form').submit(function(){
$.post("submitForm.php", { "array": submitedArray});
//HOW to verify if submited values where well written into databse?
return false;
});
//ONLY after submit I want to query the database and based on the response values I will refresh the page every two seconds (if response values not good) or refresh only once (if values checked are good)
var refresh = setInterval(function(){
$.getJSON('someOtherScript.php', function(data){
$.each(data, function(index, value){
//Check values
});
});
}, 2000);
onComplete: function(){
setTimeout(function() {$("#ajaxResponse").fadeOut();}, 500);
}
Write this in your ajax function and that's it. It worked for me.
If I have this correctly, you are using ajax to submit the form and want to do the check on callback.
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'xml/html/script/json/jsonp',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
// This is where you will do your get request to find the result you are looking for.
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Definitely don't use setInterval. setInterval will have that code execute EVERY 2 seconds, not just after 2 seconds. What you were looking for is setTimeout. But don't use that either.
have a look at
http://api.jquery.com/jQuery.post/
post can take a success parameter. This will let you run your 2nd bit of code only after the first completes.
Why not just have the initial submit code check the database write, if successful it returns a success code, otherwise it returns an error code. Either you trust ajax or you don't.

Categories