After submit make ajax call! - javascript

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.

Related

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/

How to display progress from an Ajax call using a custom PHP function?

I have an Ajax call that is processing some data and the length of time it takes varies widely depending on the site. I'd like to set a progress value in the PHP function doing the processing (I'm assuming to a SESSION variable).
While that is processing, I'd like to have another loop that is running and fetching the SESSION variable value every second or so and updating the user on what % is complete as it goes along.
So my main Ajax call to process the data is working and takes place when the user clicks a button. This is in WordPress, so the call looks something like this -
function get_data(refresh){
$.post({
url: ajaxurl,
beforeSend:function(){
$("#loader-gif").show();
},
complete:function(){
$("#loader-gif").hide();
},
data: { refresh: refresh, action: "refresh_data"},
success:function(data){
$("#loader-gif").hide();
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.responseText);
$("#loader-gif").hide();
}
});
}
What do I need to add to this in order to loop as this is running and update a span/div on the page from a PHP session variable?
This is the only Ajax call on the page currently and will likely remain so.
Checkout this link for an progress bar:
https://www.sitepoint.com/community/t/progress-indicator-for-an-ajax-request/100083

Get data from mysql database table without page reload

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.

Ajax with Jquery - Callback not executing

I have tried so many things, cannot figure this out, I am using this code, and I know that the start is working, because the script it connects to sticks some info in the db, but the callback never runs.
<script type="text/javascript">
$(document).ready(function() {
$(document.body).on('click', "#reply_submit", function() {
var formData = $('#reply').serialize();
$.post("newpost.php",formData, function(data){
alert("hi");
}, "json");
});
});
My form's id is "reply" and the button I am using to submit it is "reply-submit", just to make sure those things are clear.
It also doesn't work if I remove that last "json" thing btw.
If you read the docs for jQuery.post(), it says this about the callback:
success(data, textStatus, jqXHR)
A callback function that is executed if the request succeeds.
If it's not getting called, it means that request did not succeed. There is probably an error in newpost.php (sometime after the data insert, but before it would normally exit).
You can also catch error conditions by using the long-form jQuery.ajax() instead of the post shorthand:
$.ajax({
url: 'newpost.php',
data: formData,
type: 'post',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error!');
}
});
When you click, the form is also being submitted the standard way. Modify your click handler like this:
$(document).on('click', "#reply_submit", function(e) {
e.preventDefault(); // prevent the default submit event
var formData = $('#reply').serialize();
// ...
});
Although I think document.body should be a valid node to wrap in jQuery, I've also modified it to the more commonly used document.
On that note, if the form is never destroyed by an Ajax event or other DOM modification, you could bind to #reply instead of document (or body).
I'm simply assuming that you want to submit a form without reloading the whole page.
Based on that assumption, following code will serve the purpose.
$(document).ready(function(){
//on form submit event
$('form#reply').submit(function(){
$.post('newpost.php',$(this).serialize(),function(){
alert("Message or do something with the response data if you are expecting one");
});
//prevent default action
return false;
});
});
Please ignore the post if this is not the functionality you are looking for in your project.

How can I be sure my Ajax call has fully completed?

I have the following code:
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function () {
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
});
When a user changes some data the code updates the database. There is code that comes before this that picks the data values and it all works good.
When the user changes the Position column the database gets changed and I wanted to trigger a refresh of the screen (it's a report screen sorted by position). The refresh works but it seems like it is out of sync. I have the location.reload() in the success area but is it possible that is getting run before the Ajax has completed?
Is it possible that this kind of refresh is taking place before the database has been properly updated? When I do another refresh of the page manually from the browser the data always appears in the correct order.
Your document is cached. You shouold use
location.reload(true)
to realod with clear cache.
AJAX is asynchronous by default. Once the call is issued, the rest of your code will continue executing. If the value of location gets changed before the ajax call returns its data, the success function will be using the current-at-the-time-it-executes value of location, which is now something different than what it was when the ajax call started.
The success code will not run until the ajax call returns, so that's not the problem. but you're depending on location not being changed between the time you start the ajax stuff and the time it completes.
there is a API in jquery ajaxComplete. whenever a ajax call will be completed this will be invoked.
$.ajaxComplete(function(){
//do something
});
reference : http://api.jquery.com/ajaxComplete/
Whatever you write inside the success handler will be executed only after the completion of the ajax request you made to the server page. so you can load the updated content in that handler.you can use a parameter to accept the response from your success function and check whether your transaction is success or not.
From your server page, after making the database update,you can return true or false.
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function (data) {
// This will be excuted only after you receive a response from your server page
if(data=="true") //db updated properly
{
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
else
{
alert("Error in updating the data");
}
}
});

Categories