0

So I have html form send data via ajax to php like:

index.html

<script type="text/javascript">
    $("#button").click(function(){
        var ajaxname=$("#name").val();
        $.ajax({
            method:"POST",
            url:"some.php",
            data:"name="+ajaxname,
            success:function(data){
                $("#formresult").html(data);
            }
        });
    }
</script>

<form>
    <input type="text" name="name" id="name">
    <input id="button" type="button" value="send"/>
</form>
<div id="formresult"></div>

and php file like:

some.php

<?php

$name = $_POST['name'];

if($name == "mahdi"){
    echo 'true' . '<br/>';
    echo 'welcome' . '<br/>';
    echo 'have good time!' . '<br/>';
}
else{
    echo 'false' . '<br/>';
    echo 'wrong name' . '<br/>';
}

?>

When form submit and AJAX callback success, show all of echo in one moment and together. but I want echo "delay in time" for example 2 sec between any echo.

I used "sleep(2);" in php, "setTimeout" and "for loop" in JavaScript, but no one does not work.

Please anybody know the answer put it in https://jsfiddle.net/ to see it work.

ekad
  • 14,436
  • 26
  • 44
  • 46
mahdi
  • 31
  • 6
  • 2
    Change your AJAX response to a structured format such as JSON. Then output each part of response by delay using setTimeout. – hindmost Sep 24 '16 at 09:14
  • @Tasos it working only for show some sentences without connect to php file and do process – mahdi Sep 24 '16 at 10:55

6 Answers6

1

A lot of confusion here. If I understand correctly, you want each of the echos to execute with a 2 second delay between them, resulting in the text of each echo displaying one after another on the page?

If so, you can't use one PHP script with a set of echos like that. You'd need to send back an array of strings and have JavaScript use setInterval to display one at a time.

Edit for example:

PHP would be something like:

<?php
header('Content-Type: application/json');
$name = $_POST['name'];

if($name == "mahdi"){
    echo json_encode(array('true', 'welcome', 'have good time!'));
} else {
    echo json_encode(array('false', 'wrong name'));
}

And JS like:

$("#button").click(function(){
    var ajaxname = $("#name").val();
    $.ajax({
        method: "POST",
        url: "some.php",
        dataType: "json",
        data: "name=" + ajaxname,
        success: function (data) {
            var index = 0;
            var intervalId = setInterval(function () {
                $("#formresult").append('<p>' + data[index] + '</p>');
                index = index + 1;
                if (index === data.length) {
                    clearInterval(intervalId);
                }
            }, 2000);
        }
    });
}

This sets a setInterval after successful AJAX response. After all messages are appended to #formresult, the interval is cleared.

Dean James
  • 2,491
  • 4
  • 21
  • 29
0

when you use Ajax, the request sent to server and waits to server do the job and return the response.you can not get the result in separated parts.

you have to use Socket to do such things.

0

To make it delay in PHP do:

<?php
sleep(1);
$name=$_POST['name'];

if($name == "mahdi"){

echo 'true' . '<br/>';

echo 'welcome' . '<br/>';

echo 'have good time!' . '<br/>';
}
else{
echo 'false' . '<br/>';
echo 'wrong name' . '<br/>';
}

?>

But for Javascript use:

<script type="text/javascript">

    $("#button").click(function(){

var ajaxname=$("#name").val();
   $.ajax({
          method:"POST",
          url:"some.php",
          data:"name="+ajaxname,
          success:function(data){setTimeout(function(data){
                          $("#formresult").html(data);

                                }});
                          },2000,data)};
</script>

<form>
<input type="text" name="name" id="name">
<input id="button" type="button" value="send"/>
</form>
 <div id="formresult"></div>

Keep in mind, by using both snippets you will get a total of a 4 second delay.

Some Dinosaur
  • 154
  • 1
  • 14
0

Please go through this. You can use setTimeout.

https://jsfiddle.net/687qgqz0/?utm_source=website&utm_medium=embed&utm_campaign=687qgqz0

u_mulder
  • 54,101
  • 5
  • 48
  • 64
Davinder Kumar
  • 652
  • 4
  • 17
  • nope! it make delay for "n" sec and echo all of statements all together not one by one and delay – mahdi Sep 24 '16 at 10:24
0

You can return an array from php, iterate returned array with $.each(), use .delay(), .queue(), at success to delay two seconds between each call to .append()

<form>
  <input type="text" name="name" id="name">
  <input id="button" type="button" value="send" />
</form>
<div id="formresult"></div>
<script type="text/javascript">
  var arr = ["true<br/>"
            , "welcome<br/>"
            , "have good time!<br>"
            , "false<br/>"
            , "wrong name<br>"];
  $("#button").click(function() {

    var ajaxname = $("#name").val();
    $.ajax({
      method: "POST",
      url: "/echo/json/",
      data: {
        json: JSON.stringify(arr)
      },
      dataType: "json",
      success: function(data) {
        $.each(data, function(index, html) {
            $("#formresult").delay(2000)
            .queue(function(next) {
              $("#formresult").append(html);
              next()
            })
        })
      }
    });
  })

</script>

jsfiddle https://jsfiddle.net/berhth9r/

guest271314
  • 1
  • 15
  • 104
  • 177
  • please, more explain for me. should I change that php code too? – mahdi Sep 24 '16 at 11:24
  • but I think you are sending "arr" data with "json" type via "AJAX". So where you use value of input name and send it? – mahdi Sep 24 '16 at 16:11
  • @mahdi `arr` at Answer is to demonstrate approach at jsfiddle, which `echo`s posted data, see http://doc.jsfiddle.net/use/echo.html. Use `data:{name:ajaxname}` or `data:"name="+ajaxname` at actual `javascript` – guest271314 Sep 24 '16 at 16:23
  • yeah i do. in console inspect element it "POST 200 OK" and in Response show the result but page is blank yet – mahdi Sep 24 '16 at 17:03
  • @mahdi _"and in Response show the result but page is blank yet"_ After two seconds? What does `console.log(data)` log within `success` callback? – guest271314 Sep 24 '16 at 17:04
  • I don't know after two second or not because there isn't any result on page but on the console in "Response" tell {true
    welcome
    have good time!
    } and in "HTML" tell {true welcome have good time!}
    – mahdi Sep 24 '16 at 17:16
  • Is an object or an array returned as `data`? Are you stating that the entire string is appended to `document`? – guest271314 Sep 24 '16 at 17:21
  • @mahdi _"nope! today it made really confused!"_ ? – guest271314 Sep 24 '16 at 17:24
  • I told no, there isn't any an object or an array returned as data. I don't know why it doesn't work and I confused – mahdi Sep 24 '16 at 17:26
  • `console.log(data)` does not log any value at `console`? – guest271314 Sep 24 '16 at 17:34
  • http://stackoverflow.com/a/1969520/6838666 problem was this and I fix it. So now I have echo but still there is no "delay" – mahdi Sep 24 '16 at 17:54
  • _"but still there is no "delay""_ What do you mean? Is the array returned as `data` at `success`? – guest271314 Sep 24 '16 at 17:56
  • I exactly copy code you write in here and php file is up there. Is the array returned as data at success? – mahdi Sep 24 '16 at 18:03
  • What does `console.log(data)` within `success` log at `console`? – guest271314 Sep 24 '16 at 18:09
  • NOTING look=> http://s6.uplod.ir/i/00823/rabzwkucz9g1.jpg http://s6.uplod.ir/i/00823/pshgyy56wwoz.jpg – mahdi Sep 24 '16 at 18:20
  • When you include `console.log(data)` within `success` function, what is logged at `console`? Did you click button? – guest271314 Sep 24 '16 at 18:26
  • yes I clicked but noting logged as you see in photos – mahdi Sep 24 '16 at 18:31
  • The image does not help. Are you aware of what `console` is? See https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference?hl=en#log. Press `F12` key, click button and share what, if anything, is printed. – guest271314 Sep 24 '16 at 18:36
  • if i insert dataType: "json",in source console is blank even I click button. but if I remove it and click button error me: TypeError: invalid 'in' operand obj – mahdi Sep 24 '16 at 18:41
  • Have you returned valid `JSON` from `php`? – guest271314 Sep 24 '16 at 18:49
-1

use below code

<?php

     $name="mahdi";

     if($name == "mahdi"){

     echo 'true' . '<br/>';
     sleep(2);
     echo 'welcome' . '<br/>';
     sleep(2);
     echo 'have good time!' . '<br/>';
     }
     else{
     echo 'false' . '<br/>';
     echo 'wrong name' . '<br/>';
     }

     ?>
ram singh
  • 117
  • 5