Reputation: 616
I have a web service which works fine, when I open it manually and type the parameters in manually. For example:
When I navigate to url.url/webservice.php?region=NY it gives me all the data I need from my database. Now I want to type in a city in an input field and let ajax do the rest.
<form>
<input type="text" value="NY" name="myText" id="input">
<input type="submit" value="Submit" name="mySubmit" id="submit" onClick="changeView()">
</form>
So now, when I type something in the input field Ajax should send an request to my webservice and get the data.
My web service looks like this:
<?php
header("Content-type: application/json");
$mysqli = new mysqli('localhost','root','','ttzaferis');
$array = array();
$region = $_GET['region'];
if($result = $mysqli->query("SELECT lon, lat FROM pointsofinterest WHERE region = '".$region."'")){
$tempArray = array();
while($row = $result->fetch_assoc()){
$tempArray = $row;
array_push($array, $tempArray);
}
echo json_encode($array);
}
?>
I have now only problems on the Ajax-part. I can't understand how to make it work. I tried the following
function changeView(){
var region = document.getElementById('input').value;
alert(region);
$j.ajax({
type: 'GET',
url: 'webservice.php',
data: region,
success: function(response, textStatus, XMLHttpRequest) {
alert("test");
}
});
}
I don't understand what the problem is and how to solve it.
Upvotes: 1
Views: 3236
Reputation: 16062
I usually send get data like this :
$j.ajax({
url: 'webservice.php?region='+region,
success: function(response, textStatus, XMLHttpRequest) {
alert("test");
}
});
Which according to your comments should solve this. I don't know if it's possible sending via data, but if it is then you should do something like this :
$j.ajax({
url: 'webservice.php',
dataType: "json",
data: {region : region},
success: function(response, textStatus, XMLHttpRequest) {
alert(response.somekey);
}
});
Or seirlizing it, But yet again, i'm not sure if it'll work. Note that i added dataType
, though jQuery usually tries to find out what the dataType will be, won't hurt to add it
Upvotes: 3