Haradzieniec
Haradzieniec

Reputation: 9340

passing variable back from the server to ajax success

User fills input texts, presses the button Submit. The data sends to the server to be stored and result returned back. Fancybox window with result appears. My question is: how to display the result $res1 in the fancybox?

$.ajax({
    type:"POST",
    url:"index/success",
    async:false,
    data:{ name:name, password:password},
    success:function ()
    {
        var html='$res1 from the server should be here instead of this string';//var html=$res1.
        $.fancybox(
            {
                content: html,//fancybox with content will be displayed on success resul of ajax
                padding:15,
            }
        );
    }
});

=========================

OK, still doesn't work (returns in the fancybox the whole page+ the word "hello" on top instead of the message "hello"). Below is my update regarding the answers below, that doesn't work properly:

PHP:

<?php
    $res1="hello";... // handle logic here
    echo $res1; // print $res1 value. I want to display "hello" in the fancybox.
?>

AJAX

$.ajax({
    type: "POST",
    url: "index/success",
    async: false,
    data: {
        name: name,
        password: password
    },
    success: function (html) {
       $.fancybox(
       {
         content: html,//returns hello+page in the fancybox

          //if I use the string below instead of the upper one, the fancybox shows "The requested content cannot be loaded. Please try again later."
         // content: console.log(html) 


         padding:15,
    }
});

============= New update: Fixed!!! The problem was the data ( "hello" in the example above) was sent to the template in the framework, and template was displayed. That's why. Fixed. Thank you. Everybody.

Upvotes: 1

Views: 468

Answers (2)

Daniel Li
Daniel Li

Reputation: 15389

Assuming you're using PHP:

PHP:

<?php
    ... // handle logic here
    echo $res1; // print $res1 value
?>

AJAX:

$.ajax({
    type: "POST",
    url: "index/success",
    async: false,
    data: {
        name: name,
        password: password
    },
    success: function (html) {
        // given that you print $res1 in the backend file,
        // html will contain $res1, so use var html to handle
        // your fancybox operation
        console.log(html);
    }
});

Enjoy and good luck!

Upvotes: 1

Kyle
Kyle

Reputation: 22268

$.ajax({
  type:"POST",
  url:"index/success",
  async:false,
  data:{ name:name, password:password},
  success:function(html){ // <------- you need an argument for this function
    // html will contain all data returned from your backend.
    console.log(html);
  }
});

Upvotes: 1

Related Questions