0

Although I'm still reading Nicholas C. Zakas' book (read over 300 pages within 4 days), in the meantime I got a little project to create a half-automatized documentation generator page for our later big project. It's half-done, but now I want to give more features to it which requires that I need to send the values of textareas to PHP, so PHP can update the mysql and vica versa, but that's not the matter now.

The problem: Ajax succeed, I get the success message, but PHP doesn't read the POST. Why?

I made my research, I read tones of stackoverflow topics and other websites, phpmanual, w3school examples, but something is going wrong.

Basic html example:

<form id="foo">
   <label for="bar">A bar</label>
   <input id="bar" name="bar" type="text" value="" />
   <input type="submit" value="Send" />
</form>

<div id="result"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="script.js"></script>

The basic ajax call(send) I found for this:

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get some values from elements on the page: */
    var values = $("#foo").serialize();
    console.log("val: "+values);

    /* Send the data using post and put the results in a div */
    $.ajax({
        url: "ez.php",
        type: "POST",
        data: values,
        success: function(){
            $("#result").html('Submitted successfully');
        },
        error:function(){
            alert("failure");
            $("#result").html('There is error while submit');
        }
    });
});

Simple PHP for test if I get that data or not

<?php

   if(isset($_POST['bar']))
   {
       echo "hello " . $_POST['bar'];
   };

?>

All three files are in the same folder.

I'm surely will learn about this topic more and deeper later on, just now I need to finish this small project as soon as possible. I'm going to be front-end developer, so the php part won't wait for me, but now I need it for testing until I can speak with the server-side programmer. I want to be sure which variables and data I'll send to him, so he can handle them later.

Thanks in advance!

ThePianist
  • 611
  • 2
  • 9
  • 14
  • 1
    Why do you think PHP didn't receive the values? Your Javascript never does anything with the result. – Barmar Jan 06 '14 at 10:58
  • You should check your network tab and see – A. Wolff Jan 06 '14 at 11:00
  • Because I get a blank page if a refresh. After Ajax send the POST it supposed to send it, isn't it? I mean if a refresh the php, shouldn't I see the result? – ThePianist Jan 06 '14 at 11:01
  • Your PHP script just returns something when called, not storing any data – A. Wolff Jan 06 '14 at 11:02
  • Wolff, I checked it now! Pending then ajax send the data, then on php page, pending then refresh the network tab and the post disappear. It's like if it got the data, but the page still remain blank. – ThePianist Jan 06 '14 at 11:04
  • By page you mean the HTML page which call the PHP script? Do you mean nor success or error callback are called? I'm not sure to understand what you are talking about especially by 'blank page' – A. Wolff Jan 06 '14 at 11:06
  • check my answer - Also for clarity you mis-understand how it works - you PHP page sends information when it is run - your Ajax call asks for this information - straight after the information is sent the page 'forgets' what it has done until you run it again. If you access the page directly it starts again asking 'is bar set' - as you aren't sending 'bar' in the URL it says 'no it isn't' so doesn't send you a response. – GrahamTheDev Jan 06 '14 at 11:09

3 Answers3

9

How do you know your script isn't receiving the data?

change success to the following:

success: function(data){
        $("#result").html('Submitted successfully:' + data);
    },

All you are doing is saying 'if a response is received without an error update a div' - you have no way of knowing if your php script has run SUCCESSFULLY (it has run as you are getting success) or not at the moment.

with the 'data' in the function you can then see if information has been passed back by your script.

Try the above and let us know how you get on

FOR CLARITY

PHP scripts when you access them are run ONCE - they have no memory (other than fixed variables such as $cheese = "yummy";

The reason you cannot see a response when you access the page (even after running your script) is that it is a bit stupid and doesn't remember you ran it.

So accessing the script directly the script is going

'Oh - it's show time, right.....err.....ok - has the person sent me 'bar' - nope well in that case I will not do what is inside the if statement - end of my job - nothing to do here I will send nothing back.'

Try this:

change $_POST['bar'] to $_GET['bar'];

Then go to your URL where the script is and type http://yoururl.com/script.php?bar=terrence

You will notice you now get a response because you passed the script what it wanted to return true and so do what is inside the if statement.

For data to persist you need to store to a database or a text file.

Hope that is clear!

Padmanathan J
  • 4,614
  • 5
  • 37
  • 75
GrahamTheDev
  • 22,724
  • 2
  • 32
  • 64
  • I tried: I added "Norbert" into the box and got this: "Submitted successfully:hello Norbert". Basically what I don't understand is why can't I see this result "hello Norbert" inside the php file. :) So because we want to work with that later either to upload to mysql or just something else.. I just assume if $_POST['bar'] would work than echo would print it to the browser. – ThePianist Jan 06 '14 at 11:09
  • @ThePianist $_POST['bar'] is equal to 'Norbert', what makes you think it is not? EDIT: Why should it be equal to: `"hello Norbert"` ??? – A. Wolff Jan 06 '14 at 11:11
  • Maybe we misunderstand each other! :) Maybe I should change the description of the problem. I don't want to receive data from php file, I know how to do that. What I want to do now is to GIVE data to php file to handle that data. – ThePianist Jan 06 '14 at 11:13
  • @ThePianist but this is already what you are doing, passing value from html form to php script using ajax. Now if you need to store this data, you should use a database server side – A. Wolff Jan 06 '14 at 11:14
  • Wolff, correct me if I know it wrongly, but I assume if echo $_POST['bar']; doesn't print the value "Norbert", then something went wrong .. or if I would put it into a variable and I can't read it via echo then? That's why I assume it doesn't work. – ThePianist Jan 06 '14 at 11:15
  • @ThePianist ya, you are correct on this one but you said you got this as response: "Submitted successfully:hello Norbert" so your PHP script is working as expected – A. Wolff Jan 06 '14 at 11:17
  • Thank you Graham! It's more clear now! :) So if I want to see the result immediately just for check, send it via GET and it can get the variables because it can get it from the url and if I want to store a long long textarea text, send it via post and immediately store it to mysql. Got it! Thanks! :) – ThePianist Jan 06 '14 at 11:20
  • 2
    @ThePianist GET and POST are just methods to pass data, what you do with passed datas server side is not dependant of method used. You can use GET to store in database too. If you don't want to care about method used, you could still used $_REQUEST[] which will handle both case http://www.php.net/manual/en/reserved.variables.request.php – A. Wolff Jan 06 '14 at 11:23
  • Yeah my bad - wrote in a rush - just best practices - you are indeed correct Wolff +1 to you comment – GrahamTheDev Jan 06 '14 at 11:25
  • @GrahamRitchie my previous comment was for ThePianist's last comment, your answer is really good Graham IMHO – A. Wolff Jan 06 '14 at 11:27
  • coming from a 28k rep guy that means a lot :-D – GrahamTheDev Jan 06 '14 at 11:28
  • :) Yeah, thank for your comments as well @Wolff! I know the difference between GET and POST and we don't send sensitive data via GET, right? I actually get the table name what for we want to write documentation via GET .. url/something.php?function=get_table_data&table="+tableName .. – ThePianist Jan 06 '14 at 11:37
  • Actually I got it what was my problem. I was thinking in a way when you send data via submit without ajax, it refreshes the page, then everything is clear, but with ajax it's a bit different. Now I read the jQuery documentation again as well and noticed the success() argument, data: "The data returned from the server." :) So if I get anything inside it, I can be calm that the server got my data, I made my job. – ThePianist Jan 06 '14 at 11:38
0

If you're on windows, get Fiddler. It's a free packet sniffer from Microsoft. It will allow you to see what is in between. You will be able to see what the socket sees coming from the browser and what the socket receives from the server.

http://msdn.microsoft.com/en-us/library/bb250446%28v=vs.85%29.aspx#ie_introfiddler_topic2

It may be a little overkill for what you are doing, but I think it's always good to have great tools for debugging. It buys you options, and opens possibilities.

There are others out there too. And I'm sure there are nix tools available as well.

Elliptical view
  • 3,338
  • 1
  • 31
  • 28
0

I think everything is correct except you dint pass any value from you form.Just replace this code

<form id="foo">
   <label for="bar">A bar</label>
   <input id="bar" name="bar" type="text" value="something" />
   <input type="submit" value="Send" />
</form>

I think it will solve your problem.And add change this small code in js

Form

success: function(){
    $("#result").html('Submitted successfully');
},

TO

success: function(result){
    $("#result").html('Submitted successfully'+result);
},
Amit Chowdhury
  • 623
  • 1
  • 7
  • 22