0

I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks

Ajax :

  var a = "test";
    $.ajax({
            url: "search.php",
            dataType: "json",
            data: a ,
            success: function(data) {
               alert('Successfully');
            }, 
            error: function(data) {
               alert('Failed');
           }
        })

PHP :

    <?php
        $pictures = "img1";
        echo json_encode($pictures); 
    ?>
1
  • Forgot type:'POST' or 'GET'. Commented Apr 3, 2017 at 23:49

3 Answers 3

1

I refined your code slightly and it works.

    var a = "test";
    $.ajax({
        type: 'POST',
        url: 'search.php',
        data: 'a=' + a,
        dataType: 'json',
        cache: false,
        success: function (result) {
          alert('Successful');  
        },
        error: function (result) {
          alert('Failed');
        }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but i got the same error i replaced also type: 'POST', with type: 'GET', still doesn't work
Are you receiving any other errors? Check your browser console.
0

If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.

Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.

Try this code above.

Javascript:

var a = "test";

$.getJSON("search.php", {
  a: a
}, function (json) {
  console.log(json);
});

PHP:

<?php
$pictures = ["img1"];
echo json_encode($pictures);

The only way to this not work, is if you have a huge mistake on you webserver configuration.

Comments

0

Your ajax is wrong, it should be:

var a = "test";
$.ajax({
    type: "POST",
    url: "search.php",
    dataType: "json",
    data: {a:a},
    success: function(data) {
        alert('Successfully');
    },
    error: function(data) {
        alert('Failed');
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.