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?.

28
  • 1
    what error do you see in console ? Commented May 6, 2016 at 18:07
  • 3
    And in the console you see? And nothing would happen as you don't define success callback. Commented May 6, 2016 at 18:07
  • 1
    He can still see the php output from the response page. Just nothing in JS. Did you include jQuery library on the page before your script? Commented May 6, 2016 at 18:08
  • 4
    submit(function() { here event is missing submit(function(event) { Commented May 6, 2016 at 18:12
  • 2
    Maybe it's a permissions issue? Can you run your PHP script without an ajax call to it? Like access it in your browser directly, like at localhost/echo.php ? Commented May 6, 2016 at 19:13

6 Answers 6

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.';
}
?>
Sign up to request clarification or add additional context in comments.

12 Comments

I did this. Console is still empty, which has added to the confusion. Also, this page says success is optional?
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
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
So the error is inside your php file, because if u got a success, that mean you comunicate the js to your server
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?
|
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';
    }
?>

1 Comment

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
1

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

3 Comments

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
What about adding the absolute path?
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?
1

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

2 Comments

Did that. No luck.
so I can't comment on other answers, but did you try adding JSON.stringify({ nameEntered : name })
1

What does this give you:

$.ajax({
    type:'POST',
    url:'echo.php',
    data: {
        nameEntered : name
    },
    success: function(recd){   // <-------
        alert(recd);           // <-------
    },
    error : function(){ 
        alert("error");
    }
});

3 Comments

An alert having a blank string
Aha! That tells you something - the data being echo'd out from PHP is also blank. See new test in separate answer.
"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
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();
};

1 Comment

No I added it later. Lemme reflect it in question. Should already have, My bad

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.