3

I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.

This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.

Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);. Why isn't this working properly? How can I fix this?

From index.php:

<form id="form">
  Name:
  <input id="name" type="text" />
  <input type="Submit" value="Go" />
</form>

From scripts.js:

$(document).ready(function() {

    $("#form").submit(function(event) {
        event.preventDefault();

        var name = $("#name").val();
        alert(name);

        $.ajax({
            type:'POST',
            url:'echo.php',
            data: {
                nameEntered : name
            }
        });

    });

});

echo.php:

<?php  
if (    isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])    ) {
    echo $_POST["nameEntered"];
} else {
    echo '$_POST["nameEntered"] is not set.';
}
?>

EDIT:

Console:

enter image description here

Network:

enter image description here


EDIT 2:

Added the following to $.ajax():

,
success: function(){
    alert("success");
},
error : function(){ 
    alert("error");
}

I get an alert saying success but the browser NEVER directs to echo.php =s


EDIT 3:

After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.

Solace
  • 8,612
  • 22
  • 95
  • 183

6 Answers6

2

This way should show response.

JAVASCRIPT

$("#form").submit(function(event) {
    event.preventDefault();

    var name = $("#name").val();
    //alert(name);

    $.ajax({
        type:'POST',
        url:'http://localhost/Test12/echo.php',
        data: {
            nameEntered : name
        },
        success : function(data){
            console.log(JSON.parse(data));
        },
        error : function(error){
            console.log('erro', error);
        }
    });

});

PHP

<?php  

if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
    $name = array("nome" => $_POST["nameEntered"]);
    echo json_encode($name);
} else {
    echo '$_POST["nameEntered"] is not set.';
}
?>
Johnny John
  • 394
  • 2
  • 10
  • I did this. Console is still empty, which has added to the confusion. Also, [this page](https://learn.jquery.com/ajax/jquery-ajax-methods/#success-callback) says `success` is _optional_? – Solace May 06 '16 at 18:20
  • 1
    Is optional, but you need a promisse, to say if your request fail or give success, maybe not the success function, but a done function at least, if still empty the console, the problem maybe is in the php file – Johnny John May 06 '16 at 18:22
  • OK I removed `data` and `error` arguments from the functions you added, and changed `console.log()` statements to `alert("success");` and `alert("error");` statements respectively. I got the alert saying "success". But this browser NEVER directs to `echo.php` =s – Solace May 06 '16 at 18:23
  • 1
    So the error is inside your php file, because if u got a success, that mean you comunicate the js to your server – Johnny John May 06 '16 at 18:24
  • The "echo.php" are in the same folder or path? – Johnny John May 06 '16 at 18:26
  • Well yes they are in the same folder – Solace May 06 '16 at 18:30
  • So try use your path url:"localhost/mypath/echo.php", or something like this – Johnny John May 06 '16 at 18:32
  • Doesn't work. Hey no offense but are you making blind guesses? – Solace May 06 '16 at 18:35
  • Please see my last edit in the question? I think it is some clue. – Solace May 06 '16 at 18:41
  • 1
    I`m not making blind guesses, the error are in the url, you need specify the url where are your php file, so the ajax can send a request, and php return a response, so every change in code you need look to your network tab, to see if your app send a request to the right path. You are running a server right? – Johnny John May 06 '16 at 18:43
  • Network tab remains empty. Could you try it on your machine? – Solace May 06 '16 at 18:59
  • I make some changes, but here work's, i'll edit my answer, please take a look – Johnny John May 06 '16 at 19:12
1

Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'

Nitin
  • 898
  • 1
  • 9
  • 25
  • Changing `.submit` to ` .on('submit', function(e){});` didn't change anything. Removing `document.ready()` results in reloading of page as soon as submit is clicked – Solace May 06 '16 at 18:27
  • What about adding the absolute path? – Nitin May 06 '16 at 18:29
  • Try adding only a slash '/page' in case you tried the full path else last option, probably wont make a difference but have you tried setting cache to false and putting quotes around nameEntered in the js file? – Nitin May 06 '16 at 18:43
1

I think you need to add "event" as parameter in your submit function, in addition to the success call to show results

1

What does this give you:

$.ajax({
    type:'POST',
    url:'echo.php',
    data: {
        nameEntered : name
    },
    success: function(recd){   // <-------
        alert(recd);           // <-------
    },
    error : function(){ 
        alert("error");
    }
});
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • An alert having a blank string – Solace May 06 '16 at 21:38
  • 1
    Aha! That tells you something - the data being echo'd out from PHP is also blank. See new test in separate answer. – cssyphus May 06 '16 at 22:00
  • "the data being echo'd out from PHP is also blank" - No someone in the answers had said that I have to use `return` instead of `echo`. I was using return statement in echo.php – Solace May 07 '16 at 08:52
1

As a test, replace your echo.php with:

<?php  
    echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";

    if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
        echo 'Here 01';
    } else {
        echo 'Here 02';
    }
?>
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • I changed `echo 'Here 01';` to `echo $_POST["nameEntered"];` and I get the correct value in the alert. This works. Someone in the answers had previously said that I had to use `return` statement instead of `echo`. I was doing that. But I guess I did not have to do that. Thank you so, so very much – Solace May 07 '16 at 08:50
0

You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.

Try:

function(e){
    e.preventDefault();
};
Aaron Cicali
  • 1,496
  • 13
  • 24