Rectangle 27 1

HttpResponse is only available when using pecl_http. The default way to output content with php is to simply echo it. In rare occasions you might want to exit processing after some content, you could use die for that.

echo 'Incorrect Length for Password');
die('Incorrect Length for Password');

You also might want to add error reporting into your PHP file, preferably at the beginning:

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

This should only be considered for developing though.

I feel so dumb... durp durp durp... Thank you... But if I echo from the server side, how do I rerender the login page with lets say an alert?

api - Request Response with PHP front-end and back-end - Stack Overflo...

php api request client-server response
Rectangle 27 4

PHP

Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.

My solution allows for AJAX to return the following:

  • A message through AJAX, which updates a <div> container.
  • A URL, which causes the browser to redirect to the URL
  • A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.

This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.

<?php
// Random messages to return
$messages = array(
    'Stack Overflow',
    'Error Message',
    'Testing'
);

// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
    $response = array(
        'redirect' => // Flag to redirect
            ( rand() % 2 == 0) ? true : false, 
        'load_html' => // Flag to load HTML or do URL redirect
            ( rand() % 2 == 0) ? true : false,
        'html' => // Returned HTML
            '<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
        'title' => 'History API previous title',
        'message' => // Random message
            $messages[ (rand() % count( $messages)) ]
    );
    echo json_encode( $response);
    exit;
}

Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.

$.ajax({
    type: 'POST',
    url: "/test.php",
    data: {ajax : true},
    dataType: "json",
    success: function( json) {
        if( json.redirect) {
            if( json.load_html) {   
                // If the History API is available  
                if( !(typeof history.pushState === 'undefined')) {
                    history.pushState( 
                        { url: redirect_url, title: document.title}, 
                        document.title, // Can also use json.title to set previous page title on server
                        redirect_url
                    );
                }
                // Output the HTML
                document.open();
                document.write( json.html);
                document.close();
            }
            else {
                window.location = redirect_url;
            }
        }
        else {
            $('#message').html( json.message);
        }
    },
});

Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
    <title>Default Page</title>

    <script type="text/javascript"">        
        $( document).ready( function() {
            $('#ajax_link').click(  function() {
                var redirect_url = "/test.php";
                $.ajax({
                    type: 'POST',
                    url: "/test.php",
                    data: {ajax : true},
                    dataType: "json",
                    success: function( json) {
                        if( json.redirect) {
                            if( json.load_html) {   
                                // If the History API is available  
                                if( !(typeof history.pushState === 'undefined')) {
                                    history.pushState( 
                                        { url: redirect_url, title: document.title}, 
                                        document.title, // Can also use json.title to set previous page title on server
                                        redirect_url
                                    );
                                }
                                document.open();
                                document.write( json.html);
                                document.close();
                            }
                            else {
                                window.location = redirect_url;
                            }
                        }
                        else {
                            $('#message').html( json.message);
                        }
                    },
                });
            })
        });
    </script>
</head>

<body>
    <div id="message">The default contents of the message</div>
    <a id="ajax_link" href="#">Fire AJAX</a>

</body>
</html>
document.open();                 document.write( json.html);                 document.close();

php - Update whole page on Ajax request - Stack Overflow

php javascript jquery ajax http
Rectangle 27 4

PHP

Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.

My solution allows for AJAX to return the following:

  • A message through AJAX, which updates a <div> container.
  • A URL, which causes the browser to redirect to the URL
  • A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.

This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.

<?php
// Random messages to return
$messages = array(
    'Stack Overflow',
    'Error Message',
    'Testing'
);

// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
    $response = array(
        'redirect' => // Flag to redirect
            ( rand() % 2 == 0) ? true : false, 
        'load_html' => // Flag to load HTML or do URL redirect
            ( rand() % 2 == 0) ? true : false,
        'html' => // Returned HTML
            '<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
        'title' => 'History API previous title',
        'message' => // Random message
            $messages[ (rand() % count( $messages)) ]
    );
    echo json_encode( $response);
    exit;
}

Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.

$.ajax({
    type: 'POST',
    url: "/test.php",
    data: {ajax : true},
    dataType: "json",
    success: function( json) {
        if( json.redirect) {
            if( json.load_html) {   
                // If the History API is available  
                if( !(typeof history.pushState === 'undefined')) {
                    history.pushState( 
                        { url: redirect_url, title: document.title}, 
                        document.title, // Can also use json.title to set previous page title on server
                        redirect_url
                    );
                }
                // Output the HTML
                document.open();
                document.write( json.html);
                document.close();
            }
            else {
                window.location = redirect_url;
            }
        }
        else {
            $('#message').html( json.message);
        }
    },
});

Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
    <title>Default Page</title>

    <script type="text/javascript"">        
        $( document).ready( function() {
            $('#ajax_link').click(  function() {
                var redirect_url = "/test.php";
                $.ajax({
                    type: 'POST',
                    url: "/test.php",
                    data: {ajax : true},
                    dataType: "json",
                    success: function( json) {
                        if( json.redirect) {
                            if( json.load_html) {   
                                // If the History API is available  
                                if( !(typeof history.pushState === 'undefined')) {
                                    history.pushState( 
                                        { url: redirect_url, title: document.title}, 
                                        document.title, // Can also use json.title to set previous page title on server
                                        redirect_url
                                    );
                                }
                                document.open();
                                document.write( json.html);
                                document.close();
                            }
                            else {
                                window.location = redirect_url;
                            }
                        }
                        else {
                            $('#message').html( json.message);
                        }
                    },
                });
            })
        });
    </script>
</head>

<body>
    <div id="message">The default contents of the message</div>
    <a id="ajax_link" href="#">Fire AJAX</a>

</body>
</html>
document.open();                 document.write( json.html);                 document.close();

php - Update whole page on Ajax request - Stack Overflow

php javascript jquery ajax http
Rectangle 27 4

PHP

Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.

My solution allows for AJAX to return the following:

  • A message through AJAX, which updates a <div> container.
  • A URL, which causes the browser to redirect to the URL
  • A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.

This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.

<?php
// Random messages to return
$messages = array(
    'Stack Overflow',
    'Error Message',
    'Testing'
);

// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
    $response = array(
        'redirect' => // Flag to redirect
            ( rand() % 2 == 0) ? true : false, 
        'load_html' => // Flag to load HTML or do URL redirect
            ( rand() % 2 == 0) ? true : false,
        'html' => // Returned HTML
            '<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
        'title' => 'History API previous title',
        'message' => // Random message
            $messages[ (rand() % count( $messages)) ]
    );
    echo json_encode( $response);
    exit;
}

Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.

$.ajax({
    type: 'POST',
    url: "/test.php",
    data: {ajax : true},
    dataType: "json",
    success: function( json) {
        if( json.redirect) {
            if( json.load_html) {   
                // If the History API is available  
                if( !(typeof history.pushState === 'undefined')) {
                    history.pushState( 
                        { url: redirect_url, title: document.title}, 
                        document.title, // Can also use json.title to set previous page title on server
                        redirect_url
                    );
                }
                // Output the HTML
                document.open();
                document.write( json.html);
                document.close();
            }
            else {
                window.location = redirect_url;
            }
        }
        else {
            $('#message').html( json.message);
        }
    },
});

Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
    <title>Default Page</title>

    <script type="text/javascript"">        
        $( document).ready( function() {
            $('#ajax_link').click(  function() {
                var redirect_url = "/test.php";
                $.ajax({
                    type: 'POST',
                    url: "/test.php",
                    data: {ajax : true},
                    dataType: "json",
                    success: function( json) {
                        if( json.redirect) {
                            if( json.load_html) {   
                                // If the History API is available  
                                if( !(typeof history.pushState === 'undefined')) {
                                    history.pushState( 
                                        { url: redirect_url, title: document.title}, 
                                        document.title, // Can also use json.title to set previous page title on server
                                        redirect_url
                                    );
                                }
                                document.open();
                                document.write( json.html);
                                document.close();
                            }
                            else {
                                window.location = redirect_url;
                            }
                        }
                        else {
                            $('#message').html( json.message);
                        }
                    },
                });
            })
        });
    </script>
</head>

<body>
    <div id="message">The default contents of the message</div>
    <a id="ajax_link" href="#">Fire AJAX</a>

</body>
</html>
document.open();                 document.write( json.html);                 document.close();

php - Update whole page on Ajax request - Stack Overflow

php javascript jquery ajax http
Rectangle 27 6

Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.

Here are a couple of code examples for Node.js:

var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

You can jump straight to the Node docs here

javascript - HTTP GET Request in Node.js Express - Stack Overflow

javascript node.js express httprequest
Rectangle 27 0

HttpResponse is only available when using pecl_http. The default way to output content with php is to simply echo it. In rare occasions you might want to exit processing after some content, you could use die for that.

echo 'Incorrect Length for Password');
die('Incorrect Length for Password');

You also might want to add error reporting into your PHP file, preferably at the beginning:

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

This should only be considered for developing though.

I feel so dumb... durp durp durp... Thank you... But if I echo from the server side, how do I rerender the login page with lets say an alert?

api - Request Response with PHP front-end and back-end - Stack Overflo...

php api request client-server response
Rectangle 27 0

You can get access to the FedEx API by logging into your FedEx account and clicking on the "Developer Resource Center" link in the footer. The direct link is http://www.fedex.com/us/developer/web-services/index.html. You can download the documentation and sample code from there.

The FedEx documentation can be quite extensive & complicated. I'm working with Shippo (https://goshippo.com). We provide an easy-to-use FedEx REST API and a PHP client library. Let me know if I can help with further questions!

php - how to get fedex shipment xml api request and response? - Stack ...

php xml api fedex
Rectangle 27 0

The downside: sometimes one of the servers might get very busy but you need to benchmark the solution and find where the problem might be.

We already use ip_hash so that clients get directed to the same web server each time. This does not help when our servers need to fetch data from an external API however. The API provider's IP might be directed to the same web server each time but any of our web servers could have made that request initially. e.g. all API returns might get directed to web1 based on the API provider's IP being the same, but the request might have come from web1, web2 or web3

now I understand! You don't know what web-server initiated the API call, so how can you redirect the API return to the proper one without knowing which one is actually? One dirty solution: use different upstreams but I need to think about how to actually implement it.

can you please explain why do you need the API answer to be redirected to the same backend server? I assume you may actually receive the answer on any other server and fetch the response internal. But this is more an architecture issue and it's hard to provide a solution without actually knowing what happens in your application.

php - How to direct the response from a call to an external API back t...

php api nginx load-balancing
Rectangle 27 0

Build an array. When you're done, just use json_encode($array) to output as correct valid json format.

Doing this will secure your code, you wont get unexpected results - as it's much easier to deal with arrays compared to json-formatted code.

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);

//Output: {"a":1,"b":2,"c":3,"d":4,"e":5}
?>

php - creating a json API request response from data stored in MySql -...

php mysql json codeigniter getjson
Rectangle 27 0

I'm not privy to your particular setup, but you might be able to create a single script that runs your PHP scripts in the background with a bash script like this:

nohup php /path/to/script.1.php &
nohup php /path/to/script.2.php &
nohup php /path/to/script.3.php &

The ampersand at the end tells it to run the script in the background. the "nohup" command tells it to ignore any hangup signal, ensuring the script will continue running even if the user logs out.

Good solution, although I might get in trouble when I have to do domain-specific things on one server.

This ended up being the essence of what I finally used as a solution.

api - Fire a (multi) curl request and don't wait for the response (PHP...

php api curl httpwebrequest
Rectangle 27 0

Have a look at the PHP port of Ruby's delayed_job.

api - Fire a (multi) curl request and don't wait for the response (PHP...

php api curl httpwebrequest
Rectangle 27 0

That's an SSL issue. Please try the following line before the curl_exec call

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
var_dump($response);

Im going to try in a bit, thank u so much!

do i accept by upvote the answer? sorry, this was my first question, and i dont have enough rep to upvote the answer yet. however, i promise i'll come back to it when i can.

php - cURL request is getting NULL response from imgur api - Stack Ove...

php api curl xampp imgur
Rectangle 27 0

Ok, I think I know what you are trying to do now. There really isn't an out of the box "for each" like there is in php, which is why a lot of frameworks implement there own (jQuery's $.each()), or make prototypes. But, you may be able to do what you need with the below. You can replace all the console.log() with alert() if you want, but it gets hectic not being in Chrome's dev tools (f12 on most machines). Also, if Dale Musser is still there tell him hello! MIZ

function loadXMLDoc()
{
    var xmlhttp;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }

    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {   
            var json = JSON.parse(xmlhttp.responseText);

            //log entire json struct to developer console for easy viewing
            console.log(json);

            //you can reference individual pieces of json by doing something like
            //json.statuses or json.statuses[2]
            var statuses = json.statuses;

            for(var i=0;i<statuses.length;i++){
                var curStatus = statuses[i];

                //access bits directly
                var tweetAuthor = curStatus.user.name;
                var tweetTime = curStatus.created_at;

                //iterate hashtags
                var hashtags = curStatus.entities.hashtags;
                for(var k=0;k<hashtags.length;k++){
                        console.log("Hashtag: " + hashtags[k].text);
                }

                //iterate all elements of tweet
                for(var key in curStatus){

                    var attrName = key;
                    var attrValue = curStatus[key];

                    console.log("attribute name: " + attrName);
                    console.log("attribute key: " + attrValue);
                    if(attrName = "text") {
                        //Do something with tweet texts... like: 
                        //document.getElementById("statuses").appendChild(attrValue);
                    }
                }
            }

        }
    }

    xmlhttp.open("GET","index.php",true);
    xmlhttp.send(); 
}

Awesome, this is exactly what I was looking for. Dale is around ... if I see him, I'll say hello!

I made a request to the Twitter API. How can I get the JSON response f...

javascript php json twitter
Rectangle 27 0

With the help of francisco-spaeth I got this solved:

three private properties were added to the test class:

private $mockLogger;
private $mockClient;
private $linkService;
public function prepareMocks($url, $json)
{
    $responseInterface = $this->getMockBuilder('\Guzzle\Http\Message\Response')
                              ->disableOriginalConstructor()
                              ->getMock();
    $responseInterface->method('getBody')
                      ->with($this->equalTo(true))
                      ->will($this->returnValue($json));

    $requestInterface = $this->getMock('\Guzzle\Http\Message\RequestInterface');
    $requestInterface->method('send')->will($this->returnValue($responseInterface));

    $this->mockClient = $this->getMock('\Guzzle\Http\Client');

    $this->mockClient->method('get')
                     ->with($this->equalTo($url))
                     ->will($this->returnValue($requestInterface));
    $this->linkService = new DefaultPreviewImageLinkService($this->mockLogger, $this->mockClient);
}

In the test methods it is called like follows:

public function testGetPreviewUrlBigImage()
{
    // Given:
    $url = 'http://i1.example.com/teaser.php?action=list&objnbr=60963198&size=320';
    $json = '{"60963198":{"0":{"url":"http:\/\/i1.example.com\/teaser\/320\/8\/60963198.jpeg",'
        . '"size":320,"type":""}}}';
    $this->prepareMocks($url, $json);

    $class_methods = get_class_methods($this->linkService);
    // When:
    $previewUrl = $this->linkService->getPreviewUrl(60963198, '', DefaultPreviewImageLinkService::IMAGE_BIG);
    // Then:
    $this->assert.....
}

By preparing the mocks in a method I keep the code clean, because this has to be called for each test. I just feed the desired input valued into the prepareMock method.

By this the mock behaves like it should: it only gives back the desired value if the matching value is used by my tested class.

php - symfony: How to mock a response to an Guzzle Api request dependi...

php unit-testing symfony mocking