Redirection in json code - javascript

Am not a json geek but really need your help. During form submission & after successful validation, the following code is executed thus returning a 'registration successful' message.
I want it to be able to redirect to another page instead of returning that 'registration successful' notification.
$json_response = array(
'status' => 'success',
'message' => $success_message,
);
$json_response = json_encode( $json_response );
echo $json_response;
I tried replacing the text with
header('Location: http://localhost/successful.php');
But in vain, Thanks in advance

You can't use a server-side redirect from an AJAX request. You need to return that data, and then redirect in the success handler of your javascript.
Something like this in jQuery:
$.ajax({
url: '/foo/',
success: function(data) {
if (data.status == 'success') {
window.location.assign('/newpage'); // <- redirect at this point
}
else {
console.log(data.message);
}
}
});

Related

if else statement in AJAX success

This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?
AJAX
$( "#frm_add" ).on('submit',(function(e) {
e.preventDefault();
var img= new FormData(this);
datas = $("#frm_add").serializeArray();
$.each(datas,function(key,input){
img.append(input.name,input.value);
});
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
//data:new FormData(this),
data:img,
// data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
if(data == true)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
});
}));
php
function insertCategories($params)
{
$fileName = $_FILES['cat_image']['name'];
$name = $params['cat_name'];
$type = $params['cat_type'];
$switch = $params['cat_switch'];
$chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
if(mysqli_num_rows($chk)==0)
{
$sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");
if ($result) {
if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
echo $fileName . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/" .$fileName; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
}
}
echo json_encode($result);
}
}
Add the error command in your ajax call to execute if the command fails or returns no data in general
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:img,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data), // A function to be called if request succeeds
{
if(data)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
error: function (data)
{
$("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
}
});
I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.
In this type of actions You should:
Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
Use response object with uniform structure - that might help with building complex applications and easy to modify
Example pseudocode:
PHP
if($success) {
die(json_encode([
'error' => false,
'message' => 'Thank You',
'data' => $some_extra_data
]));
} else {
die(json_encode([
'error' => true,
'message' => 'Sorry',
'data' => $some_extra_data
]));
}
Then in ajax.success() method, its really easy to handle:
success: function (data) {
try {
var response = JSON.parse(data)
if(response.error == true) {
$('#nameerr').text(response.message)
} else {
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
} catch (err) {
alert('Sorry. Server response is malformed.')
}
}

Ajax Alert Response from PHP

Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.
I have an ajax Post function I am using to pass data to a php script.
Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.
Here is the Ajax:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
</script>
And in my php script I used this:
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
?>
The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.
The error is because you received the returned data as json but the content type is a simple string (text/html) so you need to JSON.parse() the received data first like so:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
response = JSON.parse(response);
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
The second option is to send json headers from php itself thus removing the need of parsing JSON in javascript. You can do that by using the following line of code BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT:
header('Content-Type: application/json');
and then
echo $output;
If you are working with JSON responses, you need to set the header so your browser and your JavaScript could interpret it correctly:
<?php
$success = true;
if ($success == true) {
$output = json_encode(array(
'type' => 'success',
'message' => 'YAY'
));
} else {
$output = json_encode(array(
'type' => 'error',
'message' => 'WHOOPS'
));
}
header('Content-Type: application/json');
echo $output;

Using angular.js to send data to a php file

Right so I have a angular function that is sending data to a php file using the http method.The php code I want to process the data and echo it back onto the page to confirm that the php file has processed it. I'm currently getting undefined alerted back to me, surely I should be getting the vaule of email back to me?. Thanks all
I'm following this tutorial https://codeforgeek.com/2014/07/angular-post-request-php/
var request = $http({
method: "post",
url: "functions.php",
data: {
email: $scope.email,
pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
//.then occurs once post request has happened
//success callback
request.success(function (response) {
alert(response.data);
},
//error callback
function errorCallback(response) {
// $scope.message = "Sorry, something went wrong";
alert('error');
});
My php code...
//receive data from AJAX request and decode
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$email = $request->email;
#$pass = $request->pass;
echo $email; //this will go back under "data" of angular call.
From the documentation:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
Your code should look like this:
request.then(
function( response ) {
var data = response.data;
console.log( data );
},
function( response ) {
alert('error');
}
);
Now, you need to encode the response from the server in a JSON format, so replace echo $email; with:
echo json_encode( array(
'email' => $email
) );
And you can access the email property from the angularjs $http.success promise callback function (it's the first function inside the then closure) by response.data.email

How to load article without page reloading in Yii & Ajax

I have an viewing articles from databases and every article view with hole page load. So I would load articles without page reloading, I think this is possible using Ajax but I'm not so strong about it.
This is my initial concept like below:
Layout:
CHtml::link($menu['items'][$itemId]['label'],
array('articles/view',
'id'=>$menu['items'][$itemId]['link'],
)
);
// This showing articles name & link
View:
<?php
echo $model->article_body;
?>
<script>
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: ('articles/view'),
success: function(data){
document.getElementById('articles').innerHTML = data;
},
error: function(){
alert('Somthing wrong');
}
});
</script>
Controller:
public function actionView($id)
{
$model=$this->loadModel($id);
$this->render('view',array('model' => $model));
}
Does someone can help me? Thanks
if i understood you correctly,
in your view file something like this.
echo CHtml::link($menu['items'][$itemId]['label'],
array('articles/view',
'id'=>$menu['items'][$itemId]['link'],
),array('class'=>'youclassnamehere')
);
echo '<div id="yourDivId"></div>';
in javascript your code should be something like e.g.
$(".youclassnamehere").click(function(){
$.ajax({
type:'POST',
url:$(this).attr('href'),
success:function(data){
$("#yourDivId").html(data);
}
error:function(data){
alert('Error occured please try again later..');
}
}),
return false;//this will not redirect your page
});
in controller action your code like e.g
public function actionView($id)
{
$model=$this->loadModel($id);
$this->render('view',array('model' => $model));
}
hope this will help you
You must return json:
public function actionView($id)
{
$model=$this->loadModel($id);
...
echo CJSON::encode(
array(
'status' => 'success',
'content' => $this->renderPartial('view',
array(
'model' => $model,
),
true,
true
),
)
);
}
I reach solution from above answer but I newly add like below:
array(
'onclick'=>'javascript:return false'
)

AJAX data contains one or more words..?

I'm using an AJAX post to submit form data and this is working well.
I'm not trying to show an message based on success or failure..
I've got this so far:
alert("Yehh.. Saving Data.");
$.ajax({
url:'go.php?doit=1',
data:$("form").serialize(),
type:'POST' })
.done(function(data) {
console.log(data);
})
When the submit completes data will contain either nothing or the text back from the update saying why it failed.
As an example I'd like to show an alert if there are no errors returned.
Any idea how I can do that?
If there are errors, I'd like to show an different alert.
I would return a response from the server in both cases, just to be safer...
but it will work if you don't, unless the server had a problem, no string was returned and you assumed you had a success! Do you see the problem here?
On the server:
Success:
$response = {
'status': 1,
'message': 'Success'
}
Error:
$response = {
'status': 0,
'message': 'Some error'
}
The Ajax function:
$.post( "go.php?doit=1",
{
data : $("form").serialize()
},
function(data) {
if(data.status == 1){
// success! Do something
}
else{
// error! Do something! eg: alert message
alert(data.message)
}
});
Assuming you mean that your HTTP request is sending, and that you are evaluating deliberate return values (for example you are validating your form, and returning an empty string to signify an error), you can do the following:
JS:
alert("Yehh.. Saving Data.");
$.ajax({
url: 'go.php?doit=1',
data: $("form").serialize(),
type: 'POST'
})
.done(function (data) {
if ( typeof data !== 'string' )
console.log("data is not a string. Consider 'return false' if this is unexpected?")
if ( data.length > 0 )
console.log("There was data returned")
if ( data.length === 0 )
console.log("Empty string returned!")
})
It might be a better idea to return a JSON object with the exact data you are trying to pass (such as a valid or fail flag, along with a message)

Categories