How to Get JSON Data from PHP Script using VueJS Ajax

How to Get JSON Data from PHP Script using VueJS Ajax

In this Post We Will Explain About is How to Get JSON Data from PHP Script using VueJS Ajax With Example and Demo.Welcome on Live24u.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to php – Submit form using VueJs and AJAX Example

In this post we will show you Best way to implement how to return json data from php to VueJs ajax, hear for Fetching Data from a Third-Party API with Vue.js and Axios with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




Getting Started for PHP Script using VueJS Ajax

We have used CDN(libes) for VueJS so you must need Your internet Data connection for them to work on php – Submit form using VueJs and AJAX.

Also Read :   AngularJS – How to Pass Parameters to Controllers on Initialization

    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>

index.html

This is the main HTML view of our Simple Web Application. In here, we have init Base declared all our simple my this Example(Fetching Data from a Third-Party API with Vue.js and Axios) dependencies and the HTML Elements that we have created.

<html>
  <head>
    <meta charset="UTF-8"/>
	<title>php - Submit form using VueJs and AJAX</title>
  </head>
  <body>

    <div id="app">
      <form v-on:submit.prevent="run">
        <input v-model="liveMymsg" type="text" placeholder="Enter here your message"/>
        <button v-on:click="run" type="button">{{ mybrnlbl }}</button>
      </form>
      <p>{{ products.length }} of {{ products_count }} times “{{ orignal_msg }}”:</p>
      <ul>
        <my-product v-for="product in products" :key="product.flag" v-bind:product="product">
        </my-product>
      </ul>
    </div>

    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
  </body>
</html>

index.js

This contains our simple Example for Fetching Data from a Third-Party API with Vue.js and Axios custom index.js files Add Like as javascript, vuejs scripts

    Vue.component('my-product', {
      props: ['product'],
      template: '<li>{{ product.text }}</li>'
    });

    var liveEvents = false;
    
    var app = new Vue({
      el: '#app',
      data: {
        liveMymsg: 'Hello world - Live24u.com',
        orignal_msg: '',
        products_count: -1,
        products: [],
        loading: false
      },
      computed: {
        mybrnlbl: function() {
          return (this.loading ? 'Loading…' : 'Go');
        }
      },
      methods: {
        run: function() {
    
          this.reset();
      
          var mydataUri = 'stream.php'
            + '?liveMymsg=' + encodeURIComponent(this.liveMymsg);
      
          liveEvents = new EventSource(mydataUri);
          this.loading = true;

          var that = this;

          liveEvents.addEventListener('header', function (e) {
            var header = JSON.parse(e.data);
            that.products_count = header.products_count;
            that.orignal_msg = header.liveMymsg;
          }, false);

          liveEvents.addEventListener('product', function (e) {
            var product = JSON.parse(e.data);
            that.products.push(product);
          }, false);

          liveEvents.addEventListener('close', function (e) {
            liveEvents.close();
            that.loading = false;
          }, false);
        },
        reset: function() {
          if (liveEvents !== false) {
            liveEvents.close();
          }

          this.loading = false;
          this.products = [];
          this.products_count = -1;
        }
      }
    })

stream.php

Last step,For completeness, the server side PHP source code Like file name as stream.php producing the simple above output.

Also Read :   Vue.js GET ajax request Fetch Data using PHP

<?php
//Live24u Parameters
$repeat = 20;
$liveMymsg = filter_input
(
    INPUT_GET,
    'liveMymsg',
    FILTER_SANITIZE_FULL_SPECIAL_CHARS,
    ['options' => ['default' => '']]
);

if ($liveMymsg === '') {
    $liveMymsg = 'Wel come to Live24u.com';
}

@ob_end_flush();
header('Content-Type: text/event-stream; charset=UTF-8');
echo liveDataToEventsEx
(
    'header', 
    ['products_count' => $repeat, 'liveMymsg' => $liveMymsg]
);
flush();
// user Message more times repeat
for ($flag = 1; $flag <= $repeat; $flag++) {
    usleep(50000);
    echo liveDataToEventsEx
    (
        'product', 
        ['flag' => $flag, 'text' => sprintf('[%s] %s', $flag, $liveMymsg)]
    );
    flush();
}
// Says users to close the database connection
echo liveDataToEventsEx('close', []);
flush();
function liveDataToEventsEx($ltyep, array $data, $cid = '')
{
    $datares = '';
    if ($ltyep !== '') {
        $datares .= sprintf("event:%s\n", strtr($ltyep, ["\r" => ' ', "\n" => ' ']));
    }
    if ($cid !== '') {
        $datares .= sprintf("id:%s\n", strtr($cid, ["\r" => ' ', "\n" => ' ']));
    }
    $datares .= "data:" . strtr(json_encode($data), ["\r\n" => "\n", "\r" => "\n", "\n" => "\ndata:"]);
    $datares .= "\n\n";
    return $datares;
}

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example

Also Read :   vuejs http get and post methods example | Fetching and persisting data using vue.js





Example

I hope you have Got What is Fetching Data from a Third-Party API with Vue.js and Axios And how it works.I would Like to have FeedBack From My Blog(live24u.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(live24u.com) Are Most Always Welcome.