简体   繁体   中英

return true in php and obtain result in javascript

I have a javascript function that I want to redirect to php on my server obtain a result and then if that php file returns true to complete the function. I've tried this:

if (window.location.href = "http://cosy.azurewebsites.net/servertest.php?u=" + Username + "&p=" + Password ==true)
    {
       alert ("it was true");

    }

But that just returns false no matter what I do.

When I go to the php page here is where I return null and go back to the javascript:

header("location:javascript://history.go(-1)?result=true/false");
            return true;

            //header('Location:some_page.php?result=true/false');
            exit;

I know it isn't the right way to do it but I tried a few different things and this is as far as I get!!

So from what I can tell you want to fire off a request using Javascript to your Server, then want PHP to react to that request and return true, and then your JS file should react to the response.

What you are going to need to use is AJAX (Asynchronous Javascript And XML) request. The easiest method would be to use JQuery, it also means that they can handle cross-browser comparability for you.

You can find the official docs here: http://api.jquery.com/jquery.ajax/

I'll provide a quick example, but I think you'll learn more by experimenting with it yourself.

JS File:

$.ajax({
    async: true,
    url: 'end-point.com/servertest.php?u=' + Username,
    dataType: 'json',    
    success: function (response) {
        if (response.result === true) {
            // Run your function.
        }
    }    
});

PHP File:

<?php

// Do whatever check you are doing, for the example i'll just return true.
echo json_encode([result => true]);

I'd advise researching into AJAX it sa very handy tool.

First off, I think what you need is a jQuery ajax call , although it's really vague what you actually want to achieve with your current description.

Second off, you're trying to retrieve a return value from a page which essentially only redirects to another page.

What you can do, is run an ajax call to your PHP script, and do something according to the return value that's given back from the script to JS. For example:

In your servertest.php:

<?php
    ...

    die(json_encode(true));
?>

In your JS script:

$.ajax({
    url: 'path/to/servertest.php',
    type: 'GET',
    data: {
        u: Username,
        p: Password
    },
    success: function (data) {
        data = $.parseJSON(data);

        if (data === true) {
            alert('it was true');
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM