ajax query onclick Uncaught SyntaxError - php

I have a working code using javascript event "onchange" :
<select id="mySelect" onchange="change_table(this)">
the jquery :
unction change_table(elem) {
var adressesInfo;
$.ajax({
type: "POST",
url: "test.php",
data: {id: elem.value},
success: function(data){
adressesInfo = jQuery.parseJSON(data);
},
async: false
});
and the php :
$data = array();
[...]
print json_encode($data);
This is working fine.
Now I want to do exactly the same, but using an onclick event on the th elements:
$(function(){
$("th").on('click', function(e){
change_table($('#mySelect')[0].value);
});
})
(This might not make much sense to do, but this is just for the sake of the example)
When I do this, i get the error Uncaught SyntaxError: Unexpected token <
I'm a bit confused on why it would work with onchange event and no onclick event, what is the difference ? i'm kinda new to jquery/ajax.
Thanks for your help.

Your change_table function expects an element that it can get value from (data: {id: elem.value}). So in the second case you should supply mySelect directly:
$("th").on('click', function(e){
change_table($('#mySelect')[0]);
});

$("th").click(function(){
change_table($('#mySelect')[0].value);
});
Please try this.

It looks like your error is jQuery trying to parse HTML output from your PHP, which probably means your back end is raising errors, probably due to posting it the wrong data.
Your original change_table function takes an element as its only argument, and in your final example you are passing it the string already evaluated. Perhaps this explains why the wrong data is going to your server.
Aside: there's no need to parse the json explicitly in jQuery. You can use dataType: 'json' in your ajax set up and the deserialized json will be passed to your success handler. If it fails your error handler will fire instead.

Related

Ajax call always end up in error handler

I am trying to get a text value('selected crate') from the server using an ajax call. Ajax call is:
var selected_crate ='';
$.ajax({
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
type: 'get',
dataType: 'text/html',
success: function(data){
selected_crate = data.responseText;
$('#crates option').filter(function(){
return $(this).attr("id") == selected_crate;
}).prop('selected', true);
},
error: function(data){
var e = data.responseText;
alert(e);
}
});
And the server side code snippet is:
case 'get_crate':
$msg = $bagit_manager->getSelectedCrate();
print $msg;
break;
I want to do something upon success but this call always end up in error handler. If there were complete handler, it would go in that handler. But I want to use both success and error handlers because I want to
Send error response if something is wrong from the server side
Do something on success in the client side
I am struggling to achieve this. Why this call always end up in error handler and how can I actually send an error response with regard to this call that would end up in error handler if any error occurs otherwise success response?
If the URL is right then try this:
dataType: "html"
See: http://api.jquery.com/jQuery.ajax/
see if in error handler data is been retrieved or not if data is been retrieved correctly it means your data-type is not matched for response in ajax call [see your server code that it must be returning some extra values in that case]
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
in place of this try directly url like
url: www.yoursite.com/ajax/bagit_handler.php?action=get_crate
i think it will help you to get Sucess.

How to use jquery ajax error parameter

I'm looking for a simple example and/or explanation of how to use the error parameter for .ajax.
This question (jQuery ajax error function) points to this jQuery documentation (http://api.jquery.com/jQuery.ajax/) which I do not understand.
I have the following code that does not work and I can't figure out why. I'm hoping the error parameter will help:
jquery:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$("#myForm").submit(function(){
var user_input = $("#signup_id_email").val();
$.ajax
({
type: "POST",
url: "ajax_test.php",
dataType: 'json',
data: {email: user_input},
**error: ""**
})
.done(function(r)
{
$("#answer_id").append(r.email);
});
});
});
</script>
PHP (ajax_text.php)
<?php
echo json_encode($_POST);
?>
The error "property" of the $.ajax parameter object is used to supply a callback function known as a closure to the $.ajax method. In other words you need to provide an anonymous function to handle an error if one occurs during the ajax request. Here is a basic example.
$.ajax({
type: "POST",
url: "ajax_test.php",
dataType: 'application/json',
data: {email: user_input},
success: function(result) {
// You can use success instead of .done
},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
}
});
Keep in mind that the error callback function will only be invoked if the request actually errors out. If your code simply does not return anything but the request still returns a status of 200 you will have to handle that exception in the success callback function.
Hope this helps.
EDIT: note that I removed the use of chaining events and now all callback functions are handled inside the original parameters object passed into $.ajax.
I doubt you're even sending a request. Your whitespace is off.
Javascript does not require semicolons at the end of statements. Because of this, it sometimes infers them where you don't want them.
Try putting the '({' on the same line as the '$.ajax'. You didn't see the error because there isn't one. The $.ajax is a valid statement, even though it does nothing. Similarly, the object that you create inside of the parentheses is a valid object, even though it does nothing as well.
$.ajax({
type: "POST",
...
}).done(function(r) {
....
});
To answer your original question, error takes a function as a parameter. This function takes 3 parameters in this order:
the XHR (the request)
the status of the request
the error that was thrown (can be undefined)
An example looks like this:
$.ajax({
...
error: function(xhr, status, error) {
alert("oh no!");
}
})

ajax call on CodeIgniter page returns result "an empty string"

I've got an AJAX script in my index.php of my CI application. I am just trying to return a simple string at this point for my testing. I'm using the following code for this:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'index.php/loader/opc_client',
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
$('#opc-results').html(data.test);
}
});
});
</script>
The url in this call is a standalone file with it's own controller. When I access this file directly in the browser it's loaded normally and returns expected results. Following is my PHP code:
<?php echo json_encode("test"); ?>
I can see the post results in Firebug after the function is fired but the Firebug window just displays "an empty string" under the POST in console view.
Any clues? I'm not understand this...
UPDATE: If I console.log('success') in the success parameter of the AJAX call, it logs it properly so for some reason data is empty
you shouldn't just json_encode a string although technically php can deal with a string as an array but I guess in this case things get weird. Just wrap it in an array, and when youre done testing you'll probably be better off using key value pairs as it makes thing on the client side easier to deal with, ie obj.property.
try echo json_encode(arrray('test'));

Ajax request multiple data info

I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps

AJAX/JQUERY/PHP issue

I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code:
In JS file:
$.ajax({ type: "POST",
url: "setData.php",
data: "myPOSTvar=myData"
success: function(){ alert("Data Saved"); }
});
In php file:
$var = $_POST['myPOSTvar']
...
$var ends up with a default value instead of the data it is sent.
Any ideas?
Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...
Try this and see if you get any info.
$.post("setData.php", { myPOSTvar: "myData" },
function(data){
alert("Data saved");
});
I doubt it's a success, the url should be a string : url: "setData.php" .
I really doubt that piece of JS code is working as it should. POST and setData.php should be enclosed with quotes. Right now you should get some errors because "POST" variable is not defined and then because you're accessing a "php" property on a non existent object "setData".

Categories