/    Sign up×
Community /Pin to ProfileBookmark

Problems with Ajax POST and Send

Like others before me, I too have a problem with Ajax POST method and Send. I have set up a Site Search using the Google Ajax Search API, and it works fine. The search term is stored in the variable (?) [COLOR=”red”]query[/COLOR]. Just to make sure, I have set up a new variable ([COLOR=”red”]searchTerm[/COLOR]) to read the value of [COLOR=”red”]query[/COLOR], and a temporary Alert box shows that this variable does indeed contain the search term.

I want to store the search terms in a database so I can see what people are searching for. So I set up a POST method to send the [COLOR=”Red”]searchTerm[/COLOR] to a php file, which uses [COLOR=”Red”]if (isset($_POST[‘searchTerm’]))[/COLOR] to obtain the [COLOR=”red”]searchTerm[/COLOR] and then insert it into a MYSQL database. But it doesn’t work.

When I couldn’t insert into the database, I added a second (temporary) insert using a dummy value as the [COLOR=”red”]else[/COLOR] part of the above [COLOR=”red”]if[/COLOR] statement, to test (1) if the Ajax file was actually setting the php file going, and (2) to check my Insert code was working. Both work.

So the problem is clearly that either the Ajax code doesn’t Send correctly, or the php isn’t receiving it. I am stumped to find what is wrong. Here are the two relevant sections of code:

[QUOTE]

//Ajax section
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (othermicrosoft) {
try {
request = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (failed) {
request = false;
alert(“fail”);
}

}
}

if (!request) {
return;
}

var url = “http://URL/insertSearch.php“;
request.open(“POST”, url, true);
var searchTerm = query;
alert(searchTerm);
request.send(searchTerm);

[/QUOTE]
[QUOTE]

/*PHP section */
$link = mysqli_connect(‘localhost’, ‘USERNAME’, ‘Password’, ‘DBNAME’);
mysqli_set_charset($link, ‘utf8’);

if (isset($_POST[‘searchTerm’]))
{
$searchterm = mysqli_real_escape_string($link, $_
POST[‘searchTerm’]);
mysqli_query($link, “INSERT INTO searches (SearchTerm, Date) VALUES(‘$searchterm’,CURDATE())”);
mysqli_close($link);
exit();
} else {
$searchterm = mysqli_real_escape_string($link, ‘dummy’);
mysqli_query($link, “INSERT INTO searches (SearchTerm, Date) VALUES(‘$searchterm’,CURDATE())”);
mysqli_close($link);
exit();
}

[/QUOTE]

To repeat, the php is running and always loads the dummy variable from the [COLOR=”red”]else[/COLOR] section, indicating that [COLOR=”Red”]isset($_POST[‘searchTerm’])[/COLOR] is null. I’m sure it’s something simple I am overlooking, but assistance would be greatly appreciated. Thanks.

to post a comment
JavaScript

17 Comments(s)

Copy linkTweet thisAlerts:
@tirnaMar 15.2010 — I can see one obvious error in your code.

Data sent to php scripts should be in the form of name=value pairs. You are sending just a value from your ajax function to the php script.

If you like have a read of my post at:

[URL]http://www.webdeveloper.com/forum/showthread.php?p=1074647#post1074647[/URL]

that describes my view on how to code and debug scripts which hopefully will help you debug the rest of your code
Copy linkTweet thisAlerts:
@ercatliauthorMar 16.2010 — Thanks for your help, that was indeed a problem. I have been learning Ajax via web-based tutorials, and I have found they do not document the POST method very clearly. They tend to spend more time on GET, which is well documented, but when they get to "Send" in the POST method, they tend just to give "Send(parameters)" without mentioning the "name=value pairs". So I had missed that syntax, thanks for filling me in.

Just for the record, to make the code work, I also had to add a "request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");" line.

Finally, I agree with you about developing code in small sections. I used that technique to get the Google API part of the code working, and also the insert to mysql. So I was up to the last hurdle, the POST.

Thanks again for your help.
Copy linkTweet thisAlerts:
@ercatliauthorMar 24.2010 — Data sent to php scripts should be in the form of name=value pairs.[/QUOTE]

As I said in my previous post, that worked fine for one parameter. But what if I want to send two parameters? I can easily make up the two pairs in the javascript, so the send will look like this:

[COLOR="Red"]var sendthis = "Fieldname1=" + value1 + "Fieldname2=" + value2;

Send(sendthis);[/COLOR]


But how can I get the php file to read the multiple variables? The php code will be:

[COLOR="red"]$value =mysqli_real_escape_string($link, $_POST['sendthis']);[/COLOR]

But how do I extract the two pieces of information? Are [COLOR="red"]$_POST['sendthis'][/COLOR] and hence [COLOR="red"]$value[/COLOR] strings or arrays? Do I have to work out how to extract them in the php code before writing to the mysql database? (I think I could do that if I knew whether they were strings or arrays.)

Thanks.
Copy linkTweet thisAlerts:
@iandevlinMar 24.2010 — [CODE]var sendthis = "Fieldname1=" + value1 + "&Fieldname2=" + value2;[/CODE]

Then:

[code=php]$value1 =mysqli_real_escape_string($link, $_POST['Fieldname1']);
$value2 =mysqli_real_escape_string($link, $_POST['Fieldname2']);[/code]
Copy linkTweet thisAlerts:
@tirnaMar 24.2010 — In addition to iandevlin's post I would recommend appending a dummy parameter to your sendthis string of parameters

[CODE]........+"&sid="+Math.random()[/CODE]

This essentially ensures a new url to the php script is generated every time you call the AJAX function and so eliminate the risk of receiving browser cached results from the server.
Copy linkTweet thisAlerts:
@ercatliauthorMar 25.2010 — iandevlin:

That did the trick, thanks so much! The php was sort of obvious, and I should have thought of that, but I don't recall seeing the "&" in front of the second fieldname anywhere, and I've looked up literally dozens of sites. Thanks again.

tirna:

That seems like a nifty idea. I presume this means that the POST method sends the parameter string as part of the URL, just the same as the GET method does? (I didn't realise that.) But just curious, why is this necessary? If the two parameters are the same as a previous string now in cache, it wouldn't make any difference which one was used, would it? I'm just looking to understand.

Thanks to both of you.
Copy linkTweet thisAlerts:
@tirnaMar 25.2010 — The POST methos sends the parameters separately to the php script similar to the way POST sends form data to a script separately as opposed to the GET method which appends the paramaters to the url.

When you send a url, with or without a query string browsers will sometimes return a copy of web page from their cache on your local hard disk. To ensure your browser doesn't return the results it cached from the same url on a previous visit to that url, you need to make the url unique. That is what the sid parameter is for (you can replace sid with whatever you like).

In most cases you probably don't need the sid but I normally include it by habit to make sure I'm getting fresh and not cached results sent back from the php script.
Copy linkTweet thisAlerts:
@SteelWheelMar 25.2010 — It's quite simple:

Use POST if sending data to the server (saving, edit ...) ...

Use GET, to get data back (screen) ...

If you set "var url = "http://URL/insertSearch.php"[B]+Math.random()[/B];", you have your unique url ... (works absolutely fine and without sID)
Copy linkTweet thisAlerts:
@tirnaMar 25.2010 — It's quite simple:

Use POST if sending data to the server (saving, edit ...) ...

Use GET, to get data back (screen) ...

If you set "var url = "http://URL/insertSearch.php"[B]+Math.random()[/B];", you have your unique url ... (works absolutely fine and without sID)[/quote]


Whether you send paramaters to a server side script using POST or GET, they have to be in name/value pairs as far as I have always known.

Your url of

[CODE]
url = "http://URL/insertSearch.php"+Math.random();
[/CODE]


would evaluate to something like:

[URL]http://URL/insertSearch.php0.621458715698[/URL] which is not a valid url as far as I am aware.
Copy linkTweet thisAlerts:
@SteelWheelMar 25.2010 — Totally right and my fault ... of course you should set a correct param - even "?" or "&" is missing - omg!!! *punish head against keyboard*

Hell, use this ... "http://URL/insertSearch.php?name_as_you_like="+Math.random();"

But if no further param is send, "'[...].php?'+Math.random();" is also functional in all browsers!!

Sorry again ... will not happen again!
Copy linkTweet thisAlerts:
@sohguanhMar 25.2010 — Hi all, recently I discover a Web developer must have tool and that is the Firebug addon for Firefox browser. By turning it on, I can monitor my HTTP Request and Response header. I can also see the HTTP GET or POST data so I can investigate I am sending to the server the correct data format.

Firebug also have a Console tab where I can practise Javascript using a command-line style. It also has a GUI Inspector for me to do HTML editing on the fly.

There are many more Firebug features but I believe if the original poster has use it, it would help to solve his problem. (HTTP POST data cannot be seen at the browser Location bar at the top so Firebug come to the rescue)

Thanks.
Copy linkTweet thisAlerts:
@ercatliauthorMar 25.2010 — The POST methos sends the parameters separately to the php script similar to the way POST sends form data to a script separately as opposed to the GET method which appends the paramaters to the url.

When you send a url, with or without a query string browsers will sometimes return a copy of web page from their cache on your local hard disk. To ensure your browser doesn't return the results it cached from the same url on a previous visit to that url, you need to make the url unique.[/QUOTE]


I'm sorry, but I still don't understand this. (It doesn't really matter, because I've now got it working, but I'd like to understand - I'm only very new to Javascript and Ajax.)

If POST sends the parameters separately to the URL, how does adding the random element to the string affect the URL and hence stops getting an older cached version?

And even if POST sent the parameters as part of the URL, the URL would only be the same if the exact same items were in the string, and then it would update the database correctly anyway, wouldn't it? As far as I can see it would only be a problem if (i) the php file had been amended recently and an older cached version remained, or (ii) I was receiving results back from the server, which I'm not in this case - is that what you meant?

Hi all, recently I discover a Web developer must have tool and that is the Firebug addon for Firefox browser. By turning it on, I can monitor my HTTP Request and Response header. I can also see the HTTP GET or POST data so I can investigate I am sending to the server the correct data format.

Firebug also have a Console tab where I can practise Javascript using a command-line style. It also has a GUI Inspector for me to do HTML editing on the fly.

There are many more Firebug features but I believe if the original poster has use it, it would help to solve his problem. (HTTP POST data cannot be seen at the browser Location bar at the top so Firebug come to the rescue)[/QUOTE]


Thanks for these ideas. I do use Firebug, but I don't think I know how to use all the features you have mentioned. Can you explain how to access these please:

[LIST]
  • [*]I can monitor my HTTP Request and Response header. I can also see the HTTP GET or POST data

  • [*]I can practise Javascript using a command-line style.

  • [*]It also has a GUI Inspector for me to do HTML editing on the fly.

  • [/LIST]


    You can see I am very new to this. Thanks
    Copy linkTweet thisAlerts:
    @tirnaMar 25.2010 — 
    As far as I can see it would only be a problem if (i) the php file had been amended recently and an older cached version remained, or (ii) I was receiving results back from the server, which I'm not in this case - is that what you meant?

    [/QUOTE]


    Yes, it's more important to have a unique url when querying a database and having search results returned for some purpose. If you are sending parameters to update a database then caching should not be an issue.

    By force of habit, I append a random number parameter to GET or POST query strings, especially if I want search results from a database. It's only 1 parameter and only takes me a few seconds to add to my code and I am assured of a unique url.
    Copy linkTweet thisAlerts:
    @SteelWheelMar 26.2010 — As I am right now (it's late at this side of the world), GET is limited (amount of data) ... but hell, hang me if this is wrong again! ^^
    Copy linkTweet thisAlerts:
    @tirnaMar 26.2010 — As I am right now (it's late at this side of the world), GET is limited (amount of data) ... but hell, hang me if this is wrong again! ^^[/quote]

    I don't know if there is a limit on the length of a GET query string, but if there is, it's way beyond whatever I am likely to need.
    Copy linkTweet thisAlerts:
    @SteelWheelMar 26.2010 — Not as far as you might think:

    [I]Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.



    The spec for URL length does not dictate a minimum or maximum URL length, but implementation varies by browser. On Windows: Opera supports ~4050 characters, IE 4.0+ supports exactly 2083 characters, Netscape 3 -> 4.78 support up to 8192 characters before causing errors on shut-down, and Netscape 6 supports ~2000 before causing errors on start-up.



    Note that there is no limit on the number of parameters you can stuff into a URL, but only on the length it can aggregate to.



    Keep in mind that the number of characters will be significantly reduced if you have special characters (e.g. spaces) that need to be URLEncoded (e.g. converted to the sequence '%20'). For every space, you reduce the size allowed in the remainder of the URL by 2 characters - and this holds true for many other special characters that you may encode before sending the URL to the client.



    Keep in mind, also, that the SGML spec declares that a URL as an attribute value (e.g. <a href='{url}'>) cannot be more than 1024 characters. Similarly, the GET request is stored in the server variable QUERY_STRING, which can have similar limitations in certain scenarios.



    If you are hitting a limit on length, you should consider using POST instead of GET. POST does not have such low limits on the size of name/value pairs, because the data is sent in the header, not in the URL. The limit on POST size, by default, is 2 MB on IIS 4.0 and 128 KB on IIS 5.0. POST is also a little more secure than GET -- it's tougher (though not impossible) to tinker with the values of POSTed variables, than values sitting in the querystring. [/I]


    Also IE7 works "only" with exactly 2.083 characters ... (KB @ MS)
    Copy linkTweet thisAlerts:
    @tirnaMar 26.2010 — ok, thanks for those limits.

    They confirm what I said before that I will very unlikely ever approach those limits.
    ×

    Success!

    Help @ercatli spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...