0

I am using javascript and php to run an Ajax code. The result at the moment is undefined.

I am using localStorage to move the variable from the Ajax function because I cannot understand the use of a callback (I have followed numerous examples of using callbacks but none ever worked. I figured this solution might be the least complex.

Javascript:

$( document ).ready(function() {

   $('#submit-values').click(function(e){
        /************************************************************* SUBMIT */
        e.preventDefault();//Stop page reload on click

        $('#put-output-here').val(createParagraph());

   });

   function createParagraph(){
        createSentence();
        return localStorage.getItem('sentence');
   }

   function createSentence(){
        $.when(ajax1()).done(function(a1){
            localStorage.setItem('sentence', a1);
        })
   }

   function ajax1(){
       $.post("word-engine.php",
        {

        },
        function(data){
        });
   }
});

PHP:

<?php
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';


    $randomString = '';
    for($x = 0; $x < 10; $x++){
        $rand = rand(0,62);
        $randomString = $randomString.$chars[$rand];
    }
    echo $randomString;

?>

At the moment my result is undefined

Joseph
  • 3,899
  • 10
  • 33
  • 52

2 Answers2

2

use this: since $.post is a asynchronous function. The control from function will immediately return after it run post but the response from post may be received later.

function ajax1(){
   $.post("word-engine.php",
    {

    },
    function(data){
        setdata(data);
    });
}

function setdata(data){
    localStorage.setItem('sentence', data);
}

note: for more info see this post:why cant I return data from $.post (jquery)

Community
  • 1
  • 1
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
1

You need the done event on the $.post function not on the function that's wrapping that function.

E.g.

$.post( "word-engine.php", function( data ) {
  localStorage.setItem('sentence', data );
});

On 'done'/return of the ajax post it will put the returned value into your localStorage 'sentence' key. The first param of the post function is the URL of the endpoint, the next is the success handler function. You can then specify more including the callback function handler for failure etc. See docs here for more information.

@suchit makes a good point, you won't be able to access the value in localStorage straight away because post is an async event, the javascript code will move on and the callback will happen when the response is received. You're best displaying your returned localStorage variable to screen inside the success handler or trigger whatever needs to happen with it from there.

Gareth Hopkins
  • 354
  • 1
  • 11