I am trying to pass variables via ajax to a PHP script that will run a MySQL query. However, I keep getting the error 404 Not Found with: \"http://myurl/database/%5Bobject%
try sending your data in an object instead, like:
data: {
dataid : dataid,
industry : industry,
geolocation : geolocation
}
It seems to be a jquery bug. jQuery.post
is a shorthand of jQuery.ajax({method:"post"});
, so I changed my code to this, and it worked for me. Hope they will correct this issue.
Note, the issue still exists in 1.10.2 and 2.0.2 versions.
You should change the $.post
to $.ajax
or pass the URL and data as parameters.
$.post is just a shorthand to $.ajax, and it takes the URL as the first paramter.
So it should be:
$.ajax({
type: "POST",
url: "http://myURL/database/InsertData.php",
data: "dataid="+ dataid+"&industry="+ industry +"&geolocation="+ geolocation
});
or, with $.post
$.post("http://myURL/database/InsertData.php", "dataid="+ dataid+"&industry="+ industry +"&geolocation="+ geolocation);
Remember that the docs are almost always helpful
Evan is right, tryy sending your data an an object, jquery will take care of properly URL encoding the values. String concatenations can be problematic in js.
As andi said, $.post expects an URL string as a first parameter; if you want to pass an option object, you must use $.ajax.
When you try to call $.post(<option object>)
, the option object is used as an URL; in that process, it is cast to a string (and an object cast to a string becomes [object <type>]
in Javascript; in this case, [object Object]
), it gets URL-encoded (%5Bobject%20Object%5D
), and, since it does not start with a /
or a protocol name, it is interpreted as a relative URL and gets prefixed with the current protocol, domain and path. Then, since there are no more parameters, an empty POST AJAX request is sent to that URL.
Another problem is that you use &
to separate the parameters; that should be done only in HTML, here you should just use &
. (Or a data object, as Evan said, that way you don't need do think about encoding issues.) And .val()
and .attr('value')
are not the same; the first is the current value of the field, the second is whatever value it had when the page was loaded.
The simplest way to this correctly is this:
function insertData() {
var data = $('#dataid,#industry,#geolocation').serialize();
$.post('http://myURL/database/InsertData.php', data);
return false;
}
This assumes that the three fields have the same name
and id
as $.serialize uses name
for the parameter name.