I apologize for my bad english :)
I'm doing php file with ajax request. json response comes in the format of. but in some cases can be redirect. In this case I want the redirect of the page.
Could you please help me. Thank's.
Example PHP File :
<?php
$status = $_POST['status'];
if($status == 'a'){
// return json response
}else{
echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>
Example JS File :
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
});
Use success function https://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
data: { status : statusVar },
success: function(response){
if (response.status == 'a'){
$( "#results" ).append( response);
}else{
window.location = 'http://www.url.com'
}
});
});
Try this.
url: "http://www.my_php_file.com",
success: function(data) {
document.location.href='YouNewPage.php';
}
You need to detect if the response data is valid JSON:
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com',
success: checkAJAX
});
function checkAJAX(data)
{
var response = $.parseJSON(data);
if(typeof response === "object")
{
}
else
{
// If the AJAX response is not JSON, append the HTML to the document
$('body').append(data);
}
}
Return the html that you want to echo as JSON also:
if($status == 'a'){
// return json response
} else {
echo json_encode(array("redirect" => "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>"));
}
And check redirect in the ajax response:
$.ajax({
type: "POST",
dataType: "json",
url: 'http://www.my_php_file.com',
success: function(data) {
if(typeof data.redirect !== "undefined") {
$("body").append(data.redirect);
}
}
});
Just two reminders, there will be no redirection if request fails( no fail callback) and I assume your casual JSON response doesn't have an attribute redirect.
Related
I am trying to figure out how to just display a particular response from php using ajax for example. I have a php which gives the following response -
echo 'Success'; //Display only this
//Some other process
echo 'Something else for other process';
JS
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Use if else.
And while sending AJAX request, send conditional parameters.
For example, flag: set it to either yes or no.
Get these parameters $_POST ed in PHP back end.
Depending upon the value of AJAX sent parameter, print the response.
JS:
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test', 'flag' : 'yes'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Set flag to yes or no // This is just sample.
In PHP,
if (isset($_POST['flag'] && $_POST['flag'] == 'yes') {
echo 'Success'; //Display only this
}
else {
echo 'Something else for other process';
}
You will have send json_encode to receive a JSON response and will have to accordingly change the PHP too. Below is the updated code that you can try:
PHP:
if($_POST['action'] == 'test') {
$returnArray = array('message' => 'Success');
} else {
$returnArray = array('message' => 'Something else for other process');
}
echo json_encode($returnArray);
JS
$.ajax({
type: "POST",
url: "some.php",
data: {
action: 'test'
},
dataType: 'JSON',
success: function(response) {
var responseObj = jQuery.parseJSON(response);
$('#name_status').html(responseObj.message);
}
});
I have here my AJAX code:
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
if ($returnValue == "success") {
alert("+");
}
else {
alert("-");
}
}
});
The code works. But how can i get a value in $returnValue via PHP? Something like this dont't work:
PHP
<?php return $returnValue; ?>
Your php needs to output what you want to return:
echo $returnValue;
or, for multiple values (this needs to be parsed in javascript):
echo json_encode($returnValue);
And then the value will be available in response:
...
success: function(response){
console.log(response);
...
Firstly you need to echo the value you want to return in PHP:
<?php echo $returnValue; ?>
Then in JS it will be assigned to the parameter you defined in the success handler function, in your case response. Try this:
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
if ($.trim(response) == "success") {
alert("+");
} else {
alert("-");
}
}
});
This should work for you.
$.ajax({
url: url,
type: type,
data: data,
success: function(data){
if(data.response == "success"){
alert("+");
}
else{
alert("-");
}
}
});
In your Js file :
$.ajax({
url: "file.php", //Point your php file
dataType: "text",
success: function(response) {
if ($.trim(response) == "success") {
alert("+");
} else {
alert("-");
}
}
});
In your file.php
header("Content-Type: text/plain");
echo "success";
I have a simple PHP script which, when it executes correctly from an AJAX call, ends with:
echo "ok";
Yet when I try to parse this information it tells me its not a string.
In the example below the result is: alert('error: Type Mismatch');
Why does JQuery not read the php echo as a string?
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if(typeof response == typeof 'string'){
if( response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Screenshot below shows that the response is correct and simply says 'ok'
As I'm reading from jquery Api Doc I understand that you can get a "string" or something else as a response, based on what kind of dataType you passed (if u did) in your $.ajax object. Otherwise it will be assumpted from jQuery, based on some its own logic.
In my opinion you should avoid every assumption and explicitly pass your dataType based on the response format you'll send.
So,
in case you'll set response.php to return
echo "ok";
you should set dataType "text" in your ajax call:
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "text",
...
and get the response with:
if(typeof response == "string")
{
console.info(response);
...
Or
in case you'll set response.php to return something like
echo json_encode(array("data" => "ok"));
you should set dataType "json":
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "json",
...
and get the response with:
if(typeof response == "object")
{
console.info(response.data);
...
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if (typeof response === "string"){
if (response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Do it another way:
In you php script echo back a JSON: json_encode("ok");
In AJAX specify dataType: "json" and add event:
complete: function(jsondata, stat)
{
if(stat == "success")
alert( $.parseJSON( jsondata.responseText ) );
}
The response is not string type, it is a PlainObject object.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
typeof response == 'object' // true
Try this:
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
dataType: "text",
success: function (response) {
if( response == 'ok')
alert('all is good');
else
alert('error:');
}
});
I am working on my site and i have a jquery request to the server
$.ajax(
// do an ajax to send value to the database...
{
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
})
How can I get a response as a json data from which is not a html data and how do I parse the json response from the server to the html file?
You write the PHP to emit JSON.
<?php
# Some code to populate $some_associative_or_non_associative_array
header("Content-Type: application/json");
echo json_encode($some_associative_or_non_associative_array);
?>
You need to use the parseJSON function in the js.
Here is the Php code:
function send_reply(){
echo json_encode(array('reply'=>'here is my reply'));
exit;
}
Here is the js code:
$.ajax({
url:'myajax.php',
data:{'func':send_reply},
type:'POST',
dateType:'json'
}).success(function(data){
data=$.parseJSON(data);
alert(data.reply);
}).error(function(jqxhr,error,status){
alert('Error sending reply');
});
As #Quentin said, you need to output JSON in your PHP result. Then you need to use done() to receive the data on the client side and work with it from there:
$.ajax({
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
}).done(function( json ) {
// do something with json here
});
You need to add the "JSON" header to your "pages/welcome_get.php" file:
header("Content-Type: application/json");
And also in your AJAX call remember to add the "success" and "error" callback:
jQuery.ajax({
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
success: function(response) {
//Do stuff with response here
}
error: function(){
//Display error msg or something like that
}
});
lets say you are checking user in your welcome_get.php
then in your welcome_get.php
use this
if(isset($_GET['wm_val'])){
$wm_val = $mysqli->real_escape_string($_GET['wm_val']);
$check_user = $mysqli->prepare("SELECT email FROM members WHERE username = ? LIMIT 1 ");
$check_user->bind_param('s', $wm_val);
$check_user->execute();
$check_user->store_result();
$check_user->bind_result( $email);
$check_user->fetch() ;
if ($check_user->num_rows == 1) { $datas['msg']= "failed" ;}
else{$datas['msg']= "success" ;}
$check_user->close() ;
echo json_encode($datas);
}
and your ajax
$.ajax(
// do an ajax to send value to the database...
{
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel},
success: function(msg) {
if (data.msg == 'success'){
// do what you like here example
$('#mydata').html("<span >you welcome ! </span>").delay(4000).fadeOut('fast');
}else{
//do something else example
$('#mydata').html("<span >failed ! </span>").delay(4000).fadeOut('fast');
}
})
function getProject(){
var postData = {
'project' : proj_id
};
//console.log(postData);
var site_url = "<?php echo site_url('/'); ?>";
$.ajax({
type: "POST",
url: site_url + "maincontroller/project",
data: postData, //assign the var here
success: function(msg) {
$("#project").html(msg);
getSubProject();
}
});
Suppose that is a function now I want to apply a condition on AJAX response and response id is <div id="project"></div>. If response is successful then this div is generated otherwise not. Can anyone help me please?
Replace
$("#project")=.html(msg);
With
$("#project").html(msg);
try this
success: function(msg, status){
if (status == 200) {// ok
$("#project").html(msg);
getSubProject();
}
}