Redirect from external page after ajax submit - javascript

Hello i'm using an ajax script redirecting to a php page where i make the validation. After there are no validation errors i want to redirect to another page but i cant manage to make it work. here is my script:
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$("#imageform").ajaxForm({
target: \'#preview \',
});
});
</script>
and here is the external php were i make the validation
<?php
require_once('../core/dbconfig.php');
mysql_query("SET NAMES utf8");
$fname=$_POST['name'];
$email=$_POST['email'];
$country=$_POST['country'];
$city=$_POST['city'];
$type=$_POST['type'];
$story=$_POST['story'];
$cookie=$_COOKIE['cookie'];
$sizee = $_FILES['img1']['size'];
if (!$fname or !$city or !$email or !$country or (!$story && $sizee==0))
{
if ($sizee==0 && !$story)
{
echo'<p style="color:red;">Please upload a photo or type your story.<p>';
}
if(!$fname)
{
echo'<p style="color:red;">Please enter your name.<p>';
}
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
}
else
{
echo'<p style="color:red">Please enter a valid email.<p>';
}
if(!$country)
{
echo'<p style="color:red">Please select your country.<p>';
}
if(!$city)
{
echo'<p style="color:red">Please enter your city.<p>';
}
}
else
{
....
}
what i want to achiev is that after all the conditions are completed to redirect to a confirmation page. If i use a succes:window.location.href = "example.php" doesnt work as intended.
Thnx in advance.

$(myform).ajaxForm({
beforeSend: function() {
},
error: function() {
},
complete: function(response) {
window.location.href='yourfile.php'
}
});

With ajaxForm you'r can use function complete, according to documentation this function... "A function to be called when the request finishes (after success and error callbacks are executed)".
But you need consider property async, By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
$(myform).ajaxForm({
async: true,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
OR
$(myform).ajaxForm({
async: false,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});

$.ajax({
type: "POST",
dataType: "json",
url: "friends/get_user_friends",
data:{
action:"action",
type:"type"
},
success: function (response) {
window.location.href = "http://google.com";
},
error: function (response, ajaxOptions, thrownError) {
}
});

Related

Conditionally handle ajax request

I have a full screen loading animation whenever Ajax start (most of them are action by the user) and hide on completion. At the same time I also have Ajax call to check server status using setInterval.
How do I separate the Ajax call to check server status because it is annoying if it appear as full screen. A small loading icon beside the status is fine.
May refer to the snippet below:
$(document).ajaxStart(function() {
$.LoadingOverlay("show");
});
$(document).ajaxComplete(function() {
$.LoadingOverlay("hide");
});
$(document).ready(function() {
setInterval(ajaxCall, 3000);
function ajaxCall() {
$.ajax({
url: "action.php",
type: "POST",
data: {
'action': 'checkstatus'
},
dataType: "json",
success: function(data) {
console.log('online');
$('.serverStatus').removeClass('ssOffline');
$('.serverStatus').addClass('ssOnline').text('Online');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('offline');
$('.serverStatus').removeClass('ssOnline');
$('.serverStatus').addClass('ssOffline').text('Offline');
}
});
}
});
.ssOffline {
color: red;
}
.ssOnline {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay#1.5.4/src/loadingoverlay.min.js"></script>
<p>Server status: <label class="serverStatus">-</label></p>
You can use the global which is default true.This option can be use control global handlers like ajaxStart and ajaxStop.This will prevent the full screen loading icon from appearance.
If you want to show any other icon specific to this call you can use beforeSend handler
$(document).ajaxStart(function(event) {
console.log(event)
$.LoadingOverlay("show");
});
$(document).ajaxComplete(function() {
$.LoadingOverlay("hide");
});
$(document).ready(function() {
setInterval(ajaxCall, 3000);
function ajaxCall() {
$.ajax({
url: "action.php",
type: "POST",
data: {
'action': 'checkstatus'
},
dataType: "json",
global: false, // changed here
success: function(data) {
console.log('online');
$('.serverStatus').removeClass('ssOffline');
$('.serverStatus').addClass('ssOnline').text('Online');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('offline');
$('.serverStatus').removeClass('ssOnline');
$('.serverStatus').addClass('ssOffline').text('Offline');
}
});
}
});
.ssOffline {
color: red;
}
.ssOnline {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay#1.5.4/src/loadingoverlay.min.js"></script>
<p>Server status: <label class="serverStatus">-</label></p>
You can set a property at jQuery.ajax() settings object, substitute using beforeSend at $.ajaxSetup() for .ajaxStart(), check if the current settings have the property set
function log(message) {
$("pre").text(function(_, text) {
return text + message + "\n"
})
}
// does not provide `settings` or `jqxhr` as argument
// we do not perform logic evaluation of current `$.ajax()` call here
$(document).ajaxStart(function() {
log("ajax start");
});
$(document)
.ajaxComplete(function(e, jqxhr, settings) {
if (!settings.pollRequest) {
log("not poll request complete\n");
// $.LoadingOverlay("hide");
} else {
log("poll request complete\n");
}
});
$.ajaxSetup({
beforeSend: function(jqxhr, settings) {
if (settings.pollRequest) {
log("poll request beforeSend");
// $.LoadingOverlay("show");
} else {
log("not poll request beforeSend");
}
}
});
$(document).ready(function() {
setInterval(ajaxCall, 3000);
function ajaxCall() {
"ajaxCall";
$.ajax({
url: "data:text/plain,",
pollRequest: true
});
}
$("button").on("click", function() {
$.ajax("data:text/plain,")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button>
click
</button>
<pre></pre>
jsfiddle https://jsfiddle.net/5hfty5mc/

Depending on type of AJAX request show LoadingGif

I have 1 POST ajax and 1 GET ajax, and I have this:
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#div28").show();
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
It is for showing the LoadingGif, at this point it is showing for both Ajax requests, so what should I do to make the LoadingGif show only when the POST type ajax is working?
EDIT:
Here are my ajax functions:
$(document).ready(function () {
$.ajax({
contentType: "application/json; charset=utf-8",
type: 'GET',
url: 'api/Appointments/',
dataType: 'json',
success: function (result) {
if ((result.AppTime = "9:00") && (result.AppWithYritys = "Laakkonen")) {
document.getElementById("A9").style.background = "red";
}
else {
alert("error1");
}
},
error: function (error) {
alert("error");
},
});
});
and the POST ajax:
var request = $.ajax({
type: "POST",
data: JSON.stringify(app),
url: "/api/Appointments",
contentType: "application/json",
dataType: "html"
});
request.done(function (data) {
if (data != -1) {
alert("You Have successfully made an appointment");
location.assign("http://tid.fi");
}
else {
alert("There has been an error!");
}
});
request.fail(function (gr) {
location.assign("http://google.com");
});
};
POST ajax is in a custom function which is trigger on a button-click. Just an info.
using ajaxSend and ajaxComplete you can see what the "type" of request is
However, you'll need to keep a count of active requests too - possibly not required for your simple page - but it's good to have
$(document).ready(function () {
var started = 0;
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(started++)) { // only need to show on the first simultaneous POST
$("#div28").show();
}
}
});
$(document).ajaxComplete(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(--started)) { // only hide once all simultaneous POST have completed
$("#div28").hide();
}
}
});
});
Solution without counters
$(document).ready(function () {
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
$("#div28").show();
}
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
This will show on POST, and hide once all ajax has stopped - a little less obvious, but it's probably just as valid a solution
I think the easiest option is to create a tiny functions that you can use:
function showLoading(isLoading){
if(isLoading){
$("#div28").show();
}
else{
$("#div28").hide();
}
};
Then use as documented here Ajax events
just use the function either using the global events for your specific post or call the function directly on the beforeSend and complete event hooks.

Ajax response not appears inside success function - jquery mobile

I am trying simple login form with username, password fields in jquery mobile. Username and password should validate from ajax page. In my system i am able to get response perfectly. When convert my code to .apk uging phonegap, my mobile unable to receive response from ajax page. Any code inside success function is not working, Directly it goes to error function. What am i doing wrong?
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'liveurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true); },
complete: function() {
$.mobile.loading(false);
},
success: function (result) {
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert(error);
}
});
} else {
alert('Fill all nececery fields');
}
return false;
});
});
Two points:
Your APK is not running on your server. That means, that your url is wrong it needs to be something like:
url: "http://www.your_server.com/liveurl/check.php"
You have to whitelisten every external url, please read the docs for that:
http://cordova.apache.org/docs/en/dev/guide/appdev/whitelist/index.html

How to use Ajax call to a specific controller action?

I am trying to use Ajax to reload data from a database. However, the Ajax doesn't call the controller action that I specified in the url:. Here is my Ajax code:
function selectFieldChanged(id){
$.ajax({
type: "POST",
url: Routing.generate('demo_ajax'),
data: id,
success: function(){
alert("Success");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
$(document).ready(function(){
var id = $(this).val();
$('#form_patient').change(function(){selectFieldChanged(id)});
});
The routing.xml :
demo_ajax:
pattern: /ajax/patient
defaults: { _controller: DemoBundle:Default:index}
options:
expose: true
So, I tried to simply echo the value out in the indexAction to see whether it is called or not.
public function indexAction(Request $request)
{
if($request->isXmlHttpRequest()){
echo "xmlHttpRequest is called";
}
if($request->getMethod()=='POST'){
echo 'POST is called';
}
}
However, I didn't get anything from the indexAction but I got the alert message, `Success, from my Ajax What did I do wrong?
The success callback receives data from your server so a variable must be declared to capture it:
success: function(data){ // <-----
console.log(data);
alert("Success");
},

JQuery ajax call never triggers error handler

I have an Ajax call that is called once and then it calls itself recursively in order to manage a newsletter send job (the send is managed by the send.php script). The call works pretty well (generally for the first 15-20 mins it goes well), the only problem is that sometime the call never returns but it does not trigger the error function that you can see inside the ajax call. Infact the alert is never called and the "SEND ERROR!!" message is never displayed. What can be the problem?
The following is the interested function:
function _ajax_send(id_send, curr_index)
{
$.ajax({
type: "POST",
url: "ajax/send.php",
data: { id: id_send, index: curr_index },
async: true,
dataType: "json",
global: true,
timeout: 130000,
erorr: function(xhr, status, error) {
alert("SEND ERROR!!");
setTimeout(function(){ _ajax_send(<?php echo $_GET['id']; ?>, Number(sent)); }, 3000);
},
success: function(data) {
if(data.result) {
if(!data.completed)
{
calls = calls + 1;
_ajax_send(id_send, data.curr_index);
}
else
{
done = true;
}
}
else
{
alert("Logic Error. Cause: " + data.error);
}
}
});
}
Thank you very much for any help ;)

Categories