Error: Syntax error, unrecognized expression: <a/> Jquery UI - php

i tried to build an autocomplete search. Therefore i used the jquery ui and this little snippet of code:
$(function() {
$("#search").autocomplete({
source: function( request, response ) {
$.ajax(
{
url: 'autocomplete.php',
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
},
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
});
},
minLength: 2,
select: function(event, ui) {
var url = ui.item.id;
if(url != '#') {
location.href = '/blog/' + url;
}
},
html: true,
open: function(event, ui) {
alert("open");
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
The file autocomplete.php returns json encoded data.
My Problem is, that for every valid response and result i get a "Error: Syntax error, unrecognized expression: " error and my results aren't displayed in a list. What does that error mean?
Thanks a lot!

Try to use
$(document).ready(function () {
/*here comes your code*/
});
Also, in your success function, try to change it to
success: function (data)
{
alert(data.d);
},
because you are returning the d, not data. d represents a property of data object.

You did not give all information to identify the problem, but you should call
console.log(data);
at the start of your success function and look at the response in your console. You must have used the bad syntax of <a/> instead of </a> either in your PHP generating your request response or in the function you pass as response.

Related

jQuery AJAX can't work with JSON response

I have a JSON response from my php file like:
[
{"id":"1"},
{"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]
And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?
$('#loadarchive').click(function(){
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: {
action : 'getArchive'
},
success: function(results) {
var archiveelements = JSON.parse(results);
console.log(results);
$.each(archiveelements, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
});
I tried to run your Code and I get
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:
success: function (results) {
if (results["head"]["foo"] != 0) {
// do something
} else if (results["head"]["bar"] == 1) {
// do something
}
}
this works on my computer:
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
console.log(results);
$.each(results, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:
error: function(xhr, mssg) {
console.log(xhr, mssg);
}
First
your response is not correct,Correct response should look like this
[{
"id":"1",
"archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
...
}]
Second
You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.
Finally your success method should look like this:
success: function(results) {
$.each(results, function(ind,el){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
});
},
As you are saying message from error-handler is showing.
That means AJAX is never sent to server because of incorrect URL or any other reason.
Use Firebug in Firefox and see the error in console tab.
Also I see your code
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
var archiveelements = JSON.parse(results);
}
Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.
I was able to get it working and the problem was quite simple...
I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.
Thanks to all of you.

ajaxSubmit error capturing

I'm having trouble getting ajaxSubmit to catch an error:
$(document).ready(function(){
$("#supportForm").validate({
rules: {
//validation
},
messages: {
//messages
},
submitHandler: function(form) {
$(form).ajaxSubmit({
url:"ajax/supportform",
type:"GET",
dataType: 'json',
error: function() { alert('error'); },
success: function() {alert('success'); },
});
}
});
})
what do I have to return in my php script to get it to fire the error event?
I've tried returning an array with error=>0 , exit(json_encode('error'=>'0'); etc.
See Mike de Klerk's link, it provided the clues as to what had to be done to trap an error:
It seems the success & error callbacks have nothing to do with passing a boolean error/success message, but only if the url was successfully called. I expect I am not getting error results as I am using a CMS that is always returning some kind of content - even if it's a 404 or 403 page.
Anyway, I had to return a json string from my php script:
<?php
$response = json_encode(array("error" => "false","message" => "this is the error message"));
return $response;
then parse it in my success callback:
submitHandler: function(form) {
$(form).ajaxSubmit({
url:"ajax/supportform",
type:"POST",
dataType: 'json',
error: function(data ) { alert(data); },
success: function(response) {
var obj = jQuery.parseJSON(response);
if(obj.error == "true"){
alert('error is true');
}else{
alert('error is false')
}
},
});
}
Edit: to show some specific error description coming from PHP you should read this question: jQuery Ajax error handling, show custom exception messages
Let your server generate some error, with PHP you can do that like this
<?php
header("HTTP/1.0 404 Not Found");
?>
Check out the documentation of the header function: http://nl.php.net/manual/en/function.header.php
What you are doing here is providing your webbrowser with data that does not belong in the typical HTML source, by which the webbrowser knows something went wrong.
You could actually add all meta data you want to the header of the webpage request, but when the webbrowser does not know what it means it is simply ignored. See the definition or status codes here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
change url to something that doesn't exist to force an error
function(form) {
$(form).ajaxSubmit({
url:"ajax/supportform001",
type:"GET",
dataType: 'json',
error: function() { alert('error'); },
success: function() {alert('success');} // <-was an extra comma
});
}

Not able to access the $.getJSON function

Here is a code which try to access the $.getJSON, but it doesn't responding. What may be the possible reason for this.
function getTerms()
{
alert("hello"); //it alerts hello
$.getJSON('http://localhost/context-search.php?callback=?', function(r) {
//not here
alert("Hello");
});
}
$(document).ready(function(){
alert("hello");
getTerms();
});
context-search.php returns json data in the form of
{"options":["osi","tcp","ip","http protcol","ethernet","network protocol","protocol meaning\n"]}
Where have I possibly gone wrong?? Please help me through this!
Thank You!! :)
Did you check your console log?
If it doesn't contain an error, do a json request like this instead
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(){},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
}
});
Which will give you proper error handling.
Possibly the same origin policy. Assuming this is running on localhost have you tried
$.getJSON('/context-search.php?callback=?', ...);
use like this
$(document).ready(function(){
$.getJSON('/ITTA/SavePreference/?t=' + new Date(), { id: id3 },
function (data) {
if (data != null && data != undefined && data != '') {
top.location.href = '/ITTA/Entries/' + id3;
}
}); });

JQuery AJAX - Not sending with data?

I'm building a chatroom that sends messages via AJAX. Whenever I hit enter, with the data: parameter, it returns an error, but if I remove data:, it doesn't do anything. This is very puzzling, and I'm wondering what I'm doing wrong. Here is what I have:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: "message="+$("#message").val()+"&user="+$("#user").val()+"&room="+$("#room").val(),
success: $("#message").val(""),
error: $("#message").val("FAIL"),
});
return false;
}
});
I use PHP in my AJAX call, so I don't know if that is causing the problem?
Try this:
...
$.ajax({
type: 'POST',
url: "send-message.php",
data: {message: $("#message").val(), user: $("#user").val(), room: $("#room").val()},
success: function() { $("#message").val(""); },
error: function() { $("#message").val("FAIL"); }
});
...
In the above code:
a) data sent as JSON - this will make sure that any url encoding and escaping will be correctly performed by jQuery as needed
b) success and error options must be callback functions
I would do this just to check if it grabs all the data correct:
var data = {
message: $('#message').val(),
user: $('#user').val
};
console.log(data);
You need to change these lines:
success: $("#message").val(""),
error: $("#message").val("FAIL"),
to
success: function () { $("#message").val("") },
error: function () { $("#message").val("FAIL") // removed trailing comma
I wrapped your handlers in a function and removed the trailing comma.
You can pass an object into data, and jQuery takes care of transforming it into the correct form for the type of request you issue, in this case a POST:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: {
message: $("#message").val(),
user: $("#user").val(),
room: $("#room").val()
},
success: function () {
$("#message").val("");
},
error: function () {
$("#message").val("FAIL");
},
});
return false;
}
});
Also, error and success are callbacks, so you need to provide a function, not a string if you want it called. Fixed it for you.
If you want to pass your data in POST you should use the javascript key:value format (or JSON format).
Input the following in
data: {"message": $("#message").val(),"var2":variable}
and a hint
...
data: $("#form").serialize();
...

Using jQuery Ajax methods display a response from a PHP page?

I'm trying to implement the Jquery .ajax method to simplify the ajax in my website.
Here is the function I'm working with:
function autoComplete(q, succ)
{
$.ajax({type:"GET",
url: "search.php",
data: "q="+q,
success: succ
});
}
$('input#auto_results').live('keyup', function() {
var text = $('input#auto_results').val();
autoComplete(text,
function(data)
{
alert(data);
});
});
The response on the PHP page is simply:
echo "response";
So I figure that it should alert the response when the function is called, on 'keyup'.
Sadly, nothing occurs. I must be doing something wrong, I am just not sure what it is.
is "keyup" event firing?
do following.
$('input#auto_results').live('keyup', function() {
var text = $('input#auto_results').val();
alert("Keyup event is firing");
autoComplete(text,
function(data)
{
alert(data);
});
});
if event is firing. then see firebug console tab
or put error function callback on your code:
function autoComplete(q, succ)
{
$.ajax({type:"GET",
url: "search.php",
data: "q="+q,
error:function(request, textStatus, err){
alert(request.statusText);
},
success: succ
});
}
you may get near to error.

Categories