Solved

AJAX Call with two returns

Posted on 2016-08-03
19
68 Views
Last Modified: 2016-08-09
If I have an AJAX call that calls a php file that has two different queries and two different returns.  How do I split those 2 returns and show them?

Is there an example page someplace?
0
Comment
Question by:rgranlund
  • 7
  • 5
  • 5
  • +1
19 Comments
 
LVL 35

Expert Comment

by:YZlat
ID: 41741007
You should use JSON for return values. Also you could put the return values into an array and then convert it to JSON.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41741046
Here is a simple example
Server (test.php)
<?php
$return = new stdClass;
$return->name = 'John Smith';
$return->email = 'jsmith@somewhere-else.com';
die(json_encode($return));

Open in new window

Client
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function() {
    $.ajax({
          url: 'test.php',
          'type': 'POST',
          'dataType': 'JSON'
    }).then(function(ret) {
          alert('User: [' + ret.name + '] has email address [' + ret.email +']');
    });
});
</script>

Open in new window

Working sample here
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41741089
0
 
LVL 7

Author Comment

by:rgranlund
ID: 41741198
@ Julian & Ray, thank you, that is very helpful.  Let me code it and test it and then post it to see if I need to clean it up.  I think I understand now, more clearly.
0
 
LVL 7

Author Comment

by:rgranlund
ID: 41741304
@julian or Ray, How would I add an IF statement to that return?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41741487
An IF statement?  What would be the conditions that would indicate the use of IF?
0
 
LVL 7

Author Comment

by:rgranlund
ID: 41741516
on my php page I have a success message or a failure message:
$success->success =  "Success";
$success->fail =  "Fail";

echo json_encode($success);

Depending upon if the query is successful or not, one of those two will be filled.

Then my AJAX would look something like:
<script>
                        $(function () {
                            $("#newsjoin").on('submit', function (e) {
                                e.preventDefault();
                            });
                            $("#submit").click(function () {
                                $.ajax({
                                    url: 'http://MYSITE.com/functions.php',
                                    data: $("#newsjoin").serialize(),
                                    method: 'POST',
                                    success: function (d) {
                                        if (d.success) {
                                            $( "#successmessage").html(function() {
 var successmessage = d.success;
  return successmessage;
});
 if (d.fail) {
                                            $( "#failmessage").html(function() {
 var failmessage = d.success;
  return failmessage;
});
       $("#newsjoin")[0].reset();                                 
        } 
                                    }
                                });
                            });
                        });
                    </script>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41741567
Depending upon if the query is successful or not, one of those two will be filled.
Are you sure of that?  Might want to check the definition of "success" and "failure."  These pertain to the success or failure of the HTTP request, and not to the query that might be run in the PHP script that was started by the HTTP request.  The promise methods you want are probably .done(), .fail(), .always(), and .then().
http://api.jquery.com/jquery.ajax/
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41741763
Rather do
$return->success = true;
//OR
$return->success = false;

Open in new window

Then in your AJAX
.then(function(result) {
  if (result.success) {
     ...
  }
  else {
    ...
  }
});

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41741765
Just noticed your success function is returning values - what are you hoping to achieve with that?

The AJAX call is async - it makes no sense to return a value. Your success callcack has to do something with the returned data - either that or you have to return a promise from your .ajax call and then act on the resolution of that promise.

What do you want to do with the returned values?
0
 
LVL 7

Author Comment

by:rgranlund
ID: 41742966
I wrote my reply in haste, walking out the door. I should have waited and been more clear.  The PHP searches the database for a specific entry.  If it finds that entry that matches the form submission a message is returned, "That data is already in the database" (Which I simply called "Fail")

If the data submitted is not in the DB it is inserted into the table and a message is returned "Data has been entered. (Which I called success)  So I am returning one of two echoed statements.  A success statement or a Fail Statement.
$success->success =  "Data has been entered";
OR
$success->fail =  "That data is already in the database";

So, what I am trying to figure out is in the AJAX success I want to determine if the JSON returned ->success OR ->fail .
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 41743269
OK, that part is easy.  But using names like "success" and "fail" makes for confusion.  You want a single field, probably named something like "response status" and this field will contain a signal showing success or failure of the PHP script, according to your rules.  

Here is an example.  
https://iconoun.com/demo/temp_rgranlund_client.php

You will need to run it a few times to see how it works.  Basically, if the timestamp is an even number, it returns one thing and if the timestamp is odd, it returns a different thing.  This is the server-side script.
<?php // demo/temp_rgranlund_server.php
/**
 * https://www.experts-exchange.com/questions/28961286/AJAX-Call-with-two-returns.html
 */
error_reporting(E_ALL);


// A RESPONSE OBJECT
$response = new StdClass;

// DEFAULT RESPONSE STATUS
$status = 'Foo';

// IF THE TIMESTAMP IS AN ODD NUMBER, CHANGE THE RESPONSE STATUS
$now = time();
$now = $now % 2;
if ($now) $status = 'Bar';

// PUT THE STATUS INTO THE RESPONSE OBJECT
$response->status = $status;

// RETURN THE RESPONSE OBJECT
echo json_encode($response);

Open in new window

And this is the client-side script that calls the server and injects the response status into an element of the web page.  it also tests to see if the response status == 'Bar' and raises an alert if that's what the response status contains.
<!DOCTYPE html>
<!-- https://www.experts-exchange.com/questions/28961286/AJAX-Call-with-two-returns.html -->
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
#clickable {
    color:white;
    background-color:navy;
    width:16em;
}
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
    $("#clickable").click(function(){
        $.get("temp_rgranlund_server.php", function(response){
            var resp = JSON.parse(response);
            $("#dynamic").val(resp.status);
            if (resp.status == 'Bar') {
                alert('Received ' + resp.status + ' from server');
            }
        });
    });
});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<input id="dynamic"   value="Dynamic Field" /><br>
<input id="clickable" value="Click here" />

</body>
</html>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41743654
For Success,
$response = new stdClass;
$response->success = true;
$response->message = "Data has been entered";
die(json_encode($response));

Open in new window

For failure

$response = new stdClass;
$response->success = false;
$response->message = "That data is already in the database";
die(json_encode($response));

Open in new window

$.ajax({
   ....
}).then(function(resp) {
     if (resp.success) {
            alert('Success! ' + d.message);
     }
     else {
            alert('Oops! ' + d.message);
     }
});

Open in new window

0
 
LVL 7

Author Comment

by:rgranlund
ID: 41744821
Instead of using IF and ELSE, is there a way to just access the content of "Success" or "Message"?
$response = new stdClass;
$response->success = "Hi, today is Friday";
$response->message = "That data is already in the database, Cause it is Friday";
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41744874
Yes ... but you need an if statement otherwise how do you know which one succeeded failed?

What is wrong with using the if may I ask?

Not understanding why the method presented above does not work for you - it is a pretty standard way of dealing with this situation.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41744879
Both Success and Message are available in the return

in your success if you did this
alert(d.success);
alert(d.message);

Open in new window

Both would show - trying to understand the use case here though?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41744986
... is there a way to just access the content of "Success" or "Message"?
Yes, of course.  You would need to access the content before you an use it in an if() statement!  Please see line 23-25 in the client-side script example here.

You can send a lot of different information back from the server-side script, but the more information you send, the more tightly coupled the client and server scripts become.  Cohesion is good; tight coupling is not.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41749868
Please note that the method given in the accepted answer was first posted here
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Ajax control editor 4 32
XML Data Missing in PHP SimpleXML 8 21
sql sentence 2 12
File not deleting using unlink 6 8
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now