Here i am using AJAX ,I am passing like this url:"http://www.domain.com/api/get/searchProperties?area="+area+"&city="+city+"&listingType="+listing_type, URL means it is working fine, but i want to pass data so i am trying like this data = 'area='+ area + '&city='+ city + '&listingType='+ listing_type;,now i am getting error:
Uncaught SyntaxError: Unexpected identifier.
<script>
$(document).ready(function(){
$.ajax({
type:'GET',
//url:"www.domain.com/api/get/searchProperties?area=Marathahalli&city=Bangalore&listingType=RENT",// this working
url:"http://www.domain.com/api/get/searchProperties?"
data = 'area='+ area + '&city='+ city + '&listingType='+ listing_type;
success: function(data) {
console.log(data); // Suucess
},
error:function(exception){
console.log('Exeption:'+exception);
}
});
});
</script>
<script>
$(document).ready(function(){
$.ajax({
type:'GET',
//url:"www.domain.com/api/get/searchProperties?area=Marathahalli&city=Bangalore&listingType=RENT",// this working
url:"http://www.domain.com/api/get/searchProperties?",
data :{ area: area,
city:city,
listingType: listing_type
},
dataType:"JSON",
success: function(data) {
console.log(data); // Suucess
},
error:function(exception){
console.log('Exeption:'+exception);
}
});
});
</script>
dont forget that $.ajax({}) which have {} that means you need to provide an object which fulfilled the parameter like Jquery Ajax Doc , because object format is {key1:value, key2: value2, key3: value3} that means you must use data: instead of data= and each key:value pair must be separated by comas ,.
Make sure you close off the previous statements with ;.
Related
So I'm trying to show validation errors after jquery ajax call, but for some reason instead of printing the actual messagge I'm getting either +value+ or +data.success+, am I appending the values wrong?
This is my code:
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').append('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(key , value){
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">+ value +</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Yes you are appending the values incorrectly as shown by the syntax coloring: the whole text is in dark red.
Your String is starting with a single quote ' so you need to end the string with ' too before your + value + :
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
Answer given by #pyb and original code will almost always work. However, I can see that the DIV will keep appending the errors even though the form has been reset or triggered multiple times.
Below is the code which I prefer:
NOTE: I have used html function in the success block container which will NOT append the success message always.
NOTE: I have cleared the form_error_container using html function before printing the error messages, so that it will not keep appending the error messages even though the form is reset or triggered multiple times.
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').html('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$('.form_error_container').html("");
$.each(errors , function(key, value) {
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
});
}
});
Thanks.
I'm trying to check if a user exists in my database and then change the values of my input fields to match that user's information. I have the following code but it doesn't seem to work.
<button onclick="checkAvailability()">Check Availability</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function checkAvailability()
{
$(function()
{
$.ajax(
{
type: 'POST',
url: 'test.php',
data: "name=" + $("#name").val(),
dataType: 'json',
success: function(row)
{
$('#name').val(row[0]);
$('#address1').val(row[1]);
$('#phone1').val(row[2]);
alert('success');
}
});
});
}
</script>
The alert goes off but none of the values are changed. I checked the response using Firebug and the response is a JSON object with the user's information. I'm not sure where the error is. Thank you for any input.
If you have a json object you must use: $("#name").val(row.name);
In case you are getting a json then it might look like this
var json = [{"name": "sample"},{"phone":"sample"},{"address":"sample"}];
When you are doing row[0].
what you get is an object["name":"sample"]
So you must make the following change
success: function(row)
{
$('#name').val(row.name);
$('#address1').val(row.address);
$('#phone1').val(row.phone);
alert('success');
}
Also make sure you have input types with id's name, address1 and phone1
I'm using Ajax to change data in a page. So, I want to know that what is the current route in order to call to different functions. I have read many solutions used to retrieve the current url and also to get the current route in Controller and Twig. However, is there any possible way to achieve this in javascript or jQuery?
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
// Get the current route
var route = ??; // <----------------Want to get the current route
if(route === 'route1'){
functionForRoute2(id,route)
}
else{
functionForRoute2(id,route);
}
});
});
** Function for the Route1 **
function functionForRoute1(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route1
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
** Function for the Route2 **
function functionForRoute2(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route2
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
What I would do is to output route (any route you want) in a html tag for example (twig version):
<div id="my-route" data-route"{{ path("my_route") }}"></div>
Then in your code I would retrive that route via jquery like this:
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
var route = $('my-route').data('route');
});
});
You can also change path("my_route") to a string with a name of the route and then you are doing your if/else statement. However I dont think its a good idea as if your route name changes then your code will be affected as well
You will not get current route using just Javascript or JQuery. You can, however, get current URL with Javascript or current route using Twig.
Another possible solution is to issue one more AJAX call to server passing current URL, then match it to the correct route and send it back. However, if I were you, I would just get the current route from Twig.
var route = "{{ app.request.attributes.get('_route') }}";
I am trying to implement a form containing a list of cities, using a JSON array and an autocomplete function.
My ajax call is successful and gives the expected success alert, but I'm still not getting the JSON array data.
The problem is that my suggest_json_application function is failing at the 'if form.has_key('term')' statement and giving the message "form has no key".
How can I pass the form data to the function properly through the ajax call, with the key term?
HTML form
</head>
<body>
<form>
<fieldset><legend>Cities</legend>
<input type='text' name='term' id='term'>
</form>
JQuery
$('document').ready(function() {
var term = $('#term').val();
$.ajax({
url: "/suggestjson",
type: "POST",
dataType: "json",
data: JSON.stringify({'term': term}),
success: function (data) {
alert('success');
console.log( data );
}
});
});
Webserver
cities = ['New York', 'London', 'Los Angeles',
'Paris', 'San Francisco', 'Adelaide']
if environ['PATH_INFO'] == "/suggestjson":
return suggest_json_application(environ, start_response)
def suggest_json_application(environ, start_response):
//Return JSON array of completions for a city name
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
if form.has_key('term'):
print "form has key"
q = form.getvalue("term", "")
matches = [c for c in cities if c.lower().startswith(q.lower())]
else:
print "form has no key"
matches = []
return json.dumps(matches)
Currently you are sending whole html element to server. Invoke val() function to get the value of element,
Also use id selector for easy access to element,
like this:
var term = $('#term').val();
please try to change "data" option to a object in the ajax call as follow
$('document').ready(function() {
var term = $('input[name=city]');
$.ajax({
url: "/suggestjson",
type: "GET",
dataType: "json",
data: {'term': term},
success: function (data) {
alert('success');
console.log( data );
}
});
});
Use val() :- see details here
var term = $('#term').val();
and also data parameter in ajax it should be
data : {term: term}
I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.