Redirect somewhere else upon JSON success? - javascript

My Code:
<script>
$('#form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
}
});
return false;
});
</script>
The FORM:
<form id="form" class="center" action="http://localhost/products/index.php?route=checkout/cart/add" method="post">
<input type="text" name="cname">
<input type="hidden" name="product_id" value="51">
<input type="submit">
</form>
When the form presses submit it goes to the action page which is just a JSON success message, what I want to do is redirect to a different page other than the action page, but my code does not seem to be working?
What exactly is wrong with my code, can someone help me fix it?
I would be so grateful if you could help me out, many thanks!

You aren't posting any data which makes a POST fairly useless .
Also you have no error handler either
Try:
$(function(){
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function(){
// do something when request fails - See $.ajax docs
}
})
return false;
});
});

You can used this code for error handling! You also check this question on stackOverflow for redirecting to another page using jQuery/JavaScript:
click here
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
},
});
});

You need to have separate error and success handlerS like below.
In success method you can redirect to other pages/sites (window.location.href = "http://www.EXAMPLE.com";)
var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully, //Separate method for handling success
error: showError //Separate method for handling error
};

Related

alert is not working on error message

// Alert is not working on error message , I want to insert only few 4 issue after that it should not work.
success: function(msg, String, jqXHR) {
window.location = 'home.html';
$("#result").html(msg, String, jqXHR)
alert("Data Uploaded: ");
if (msg.success == 'Error') {
alert("Please close the previous issue");
window.location = 'home.html';
}
// here (msg.success=='Error') is not working i want to display this message - "Please close the previous issue" on this .
Hope this works for you.
$(document).ready(function(){
$('#your_form').submit(function(event) {
event.preventDefault();
dataString = $("#your_form").serialize();
$.ajax({
type: "post",
url: "post.php",
dataType:"json",
data: dataString,
success: function (response) {
if(response.status === "success") {
// do something with response.message or whatever other data on success
alert("Data Uploaded: ");
window.location='home.html';
} else if(response.status === "error") {
alert("Please close the previous issue");
window.location='home.html';
}
}
})
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

csrf token for ajax serialize data in codeigniter

I am putting csrf token for my all ajax call but I'm getting error 500 where I am passing serialize data and JSON data in my ajax call.
I included in my view page but it's not working and throwing an error.
$("#submit").on('click', function(e) {
e.preventDefault(); // prevent default form submit
if(validateCode()){
$.ajax({
url: 'verifyCode', // form action url
type: 'POST', // form submit method get/post
data: $('#frm').serialize(),
success: function (result) {
result = JSON.parse(result);
if(result.st == 1){
window.location.href="backupCode";
}
else{
$('#validCodeFormat').html("<span style='color:red'>Invalid authentication code.</span>");
}
},
error: function(e) {
}
});
}
});
var json='json={"age":"'+age+'","age1":"'+age1+'","afterTaxincome":"'+aftertaxincome+'","afterTaxincome2":"'+aftertaxincome2+'","annualSave":"'+annualSave+'","annualSave2":"'+annualSave2+'","liqInvest":"'+liqInvest+'","liqInvest2":"'+liqInvest2+'","nonliqassets":"'+nonliqassets+'","nonliqassets2":"'+nonliqassets2+'","totalLia":"'+totalLia+'","totalLia2":"'+totalLia2+'","savingsChange":"'+savingsChange+'","savingsChange2":"'+savingsChange2+'","preference":"'+preference+'","market":"'+market+'","mail":"'+mail+'","investorTypePage":"'+investortype+'"}';
//alert(json);
$.ajax({url: "questions/sendQuestions",
type: "POST",
data: json,
success: function(result){
},
error: function(xhr, status, errMsg) {
alert("error while fetching data from server.\nPlease try again.");
}
});
You might need to use $.ajaxSetup() before your AJAX calls:
<script type="text/javascript">
var csrf_token = {TOKEN};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
</script>
I have needed this before when using Flask CSRF Protection.

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

jQuery $(this).closest("form").submit(); not executing

Can anyone please tell me why my submit is not being executed? The log tells me: "Validation passed, will submit form", but is not submitting?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $("#ajax-payment-form").serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest("form").submit();
} else {
console.log(msg);
}
}).fail(function() {
console.log('AJAX error');
});
});
});
Thanks for your time
thar
just do this:
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
var $this = $(this);
e.preventDefault();
// Serialize data, make AJAX call
var str = $("#ajax-payment-form").serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$this.closest("form").submit();
//....
or shorter code: (Notice de submit event)
$(function(){
$("#ajax-payment-form").submit(function(e) {
e.preventDefault();
var $form = $(this);
$.post(
url: templateDir+"/payment_form/payment_process.php",
$form.serialize(),
function(){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$form.closest("form").submit();
} else {
console.log(msg);
}
},
'json'
).fail(function() {
alert( "error" );
});
});
});

Decoding Json String From Javascript in PHP

I have the following json sent (POST) from my javascript to the php
function boardToJSON() {
return JSON.stringify({
"pieces" : gPieces, // gpieces and gdestinations is an array
"destinations" : gDestinations,
"boardSize" : kBoardHeight // boardSize is an integer value 9
});
// Below function is called on Button Click and url contains PATH to the php file.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Unable to connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested URL of HalmaAI not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Data from HalmaAI was not JSON :( Parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
On the server side (in PHP) I am trying to get it like this
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString);
echo $myJson["boardSize"]; // also tried $myJson.boardSize etc
Issue is that I am unable to decode JSON in PHP. Can someone guide me here please ? Thanks
You should set the contentType property on AJAX request to application/json. This will set proper header on request such that server will not attempt to populate $_POST in favor of you working with the raw input.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json"
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
}
});
}
Assuming this works, you can access the boardSize property at:
$myJson->boardSize;
The other problem you have is that since you specify dataType: "json" you need to make sure you send back valid JSON, which you currently are not.
This is not valid JSON:
echo $myJson["boardSize"];
This would be (of course this is a trivial example):
$returnObj = new stdClass();
$returnObj->boardSize = $myJson->boardSize;
echo json_encode($returnObj);
If you want decode json to array in PHP, you should set the 2nd argument of json_decode to true.
Example:
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString, true);
echo $myJson["boardSize"];

Categories

Resources