简体   繁体   中英

how to get the response back to javascript from php using json?

THIS ISSUE HAS BEEN SOLVED

THE BELOW CODE IS THE CORRECTED AND WORKING CODE

I have created a html form which sends certain variables to a php file and returns the success through json back to the javascript. But the problem is am not able to get any response back to the javascript file. I donno what is the reason. So can some help me with this. Thank you

my form is

<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">       </script>
<script src="scriptj.js"></script>
</head>
<body>
<form action="http://localhost/donotdel/process.php" method="POST">
    <div id="name-group" class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" name="name" placeholder="name">
    </div>
    <div id="email-group" class="form-group">
        <label for="email">Email</label>
        <input type="text" class="form-control" name="email" placeholder="email">
    </div>
    <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
  </form>
</body>
</html>

my javascript file is

$(document).ready(function () {
    $('form').submit(function (event) {
        $('.form-group').removeClass('has-error');
        $('.help-block').remove();
        var formData = {
            'name': $('input[name=name]').val(),
            'email': $('input[name=email]').val(),
        };
        $.ajax({
            type: 'POST',
            url: 'http://localhost/donotdel/process.php',
            data: formData,
            dataType: 'json',
            encode: true
        }).done(function (data) {
            console.log(data);
            if (!data.success) {
                if (data.errors.name) {
                    $('#name-group').addClass('has-error');
                    $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>');
                }

                if (data.errors.email) {
                    $('#email-group').addClass('has-error');
                    $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>');
                }
            }
            else {
                $('form').append('<div class="alert alert-success">' + data.message + '</div>');
            }
        }).fail(function (data) {
            console.log(data);
        });
        event.preventDefault();
    });
});

and my php file is

<?php

$errors         = array();      
$data           = array(); 

if (empty($_POST['name']))
    $errors['name'] = 'Name is required.';

if (empty($_POST['email']))
    $errors['email'] = 'Email is required.';

if ( ! empty($errors)) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $data['success'] = true;
    $data['message'] = 'Success!';
}
header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);
?>

the error that i am getting is instead of passing the json to javascript file, the json is printed in the screen. But whereas i need the javascript to show an alert.

Try setting the proper header in php:

header ('Content-Type: application/json');

Failing that - can you post a plunker or jsfiddle?

As discussed with OP.

-> First error is jQuery library not loaded from goole server so suggest to download latest jQuery library

-> second error is 'Access-Control-Allow-Origin' . suggest to add header ('Content-Type: application/json');header("Access-Control-Allow-Origin: *"); in php file or make sure to call ajax request from same origin domain

header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);

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