I'm trying to update a div with id=OCRID, which is a div on my page that contains some data. I used the code at the following URL first, however we switched to a jQuery approach. <-Ugly ajax->. Switched to this. Using alert, I saw that the message being returned on success was the correct message, but the document.getElementById(OCRID).innerHTML=msg doesn't change the value. I have some other javascript that does some similar things but not with data from the server. Please help?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).value,
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg;
}
});
First of all you mentioned OCRID is an id of div and you've used
document.getElementById(OCRID).value // a div doesn't have a value attribute
which returns value of an HTML element but a div doesn't contain any value attribute and in the success callback you have used
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg; // innerHTML is right for a div
}
From the jQuery Documentation:
success(data, textStatus, jqXHR)
A function to be called if the
request succeeds. The function gets passed three arguments: The data
returned from the server, formatted according to the dataType
parameter; a string describing the status; and the jqXHR (in jQuery
1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in
turn. This is an Ajax Event.
in this case you shouldn't use OCRID as the second parameter because jQuery uses 3 parameters in the success callback and these are basically data, textStatus, jqXHR and in this case data is your msg, OCRID in this case become textStatus and it is the response's status message and the third parameter is the xhr object. So it should be
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+$('#'+OCRID).html(), // or text()
success: function(msg){
$('#'+OCRID).html(msg); // or text()
}
});
Also remember that you OCRID looks like a variable and this should be available in the scope of your ajax call and if this is not a variable then it should be $('#OCRID') in both places as given below
$('#OCRID').html();
and in the success callback
$('#OCRID').html(msg);
Replace this line:
document.getElementById(OCRID).innerHTML=msg;
With:
document.getElementById("OCRID").innerHTML=msg; // notice the quotes
If your success callback has OCRID as a parameter(which is incorrect) it will be used instead of the one you used in your data parameter, so remove it.
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).innerHTML,
success: function(msg){
document.getElementById(OCRID).innerHTML=msg;
}
});
Why not use the jQuery version for the interface to the element? To me it looks like OCRID is a variable, right?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus=" + $('#' + OCRID).text(),
success: function(msg, OCRID){
$('#' + OCRID).html(msg);
}
});
Related
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
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!");
}
})
I have the following ajax call. What I would like to do is set the variable "lan_setting" during the ajax requests, and be able to use that variable on success.
In reality I want to set that variable to be post data, which will vary depending on the form input, but as of now I can't even get it working with just this basic example. It just returns "undefined".
_jqXHR = $.ajax({
url: url,
data: {lan_setting: 'en'},
scriptCharset: "UTF-8",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(lan_setting, data, textStatus, jqXHR) {
alert(data.lan_setting);
}
});
How do I can I use post variable sent via ajax on success?
thanks!
Well, if you're posting, you should use the jquery post function here
$.post(
url,
{lan_setting:"en"},
function( data, status, jqXhr ){
alert(data.lan_setting);
},
"json"
);
then php:
<?php
// do stuff
$response = new stdClass;
$response->lan_setting = $_POST["lan_setting"];
print json_encode($response);
?>
Well, you're declaring the success function wrong (from the jQuery .ajax() documentation):
success(data, textStatus, jqXHR)
In other words, the success function gets data, textStatus, jqXHR and nothing else. You can't just will it to take your POST variable -- it only gets what it gets. You also can't pass a POST variable in by just specifying it in the config object: you have to pass it in via the data property. Lastly, .ajax() defaults to a GET request, so you have to explicitly specify that you want to use a POST request.
I'm a little confused about what you want to do; if you know the value of lan_setting before making the AJAX call, why do you need to have it passed into the success function? Just use it:
var lan_setting = 'en';
_jqXHR = $.ajax({
url: url,
type: "POST",
data: {
lan_setting: lan_setting
},
scriptCharset: "UTF-8",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(lan_setting, data, textStatus, jqXHR) {
alert(lan_setting);
}
});
If, on the other hand, you want to pass the lan_setting value in, have it modified by the server, and passed back, you will have to somehow encode it in the response, probably with JSON.
Well the success() method in jQuery.ajax, accepts 3 parameters.. The first being the response from the request.
success(data, textStatus, jqXHR)Function, Array A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
Also, when using $.ajax, there are a certain number of objects you can pass. See http://api.jquery.com/jQuery.ajax/
As far as your post, you are able to do...
$.post("service.php", {lan_setting: "en"}, function(response) { alert(response); }
which will post the second parameter, {lan_setting: "en"} to that php service, and echo it's response.
I have a simple script that gets the value of a textarea and posts this via AJAX. If I post "??" I get strange values. If I log out the value it retrieves before posting it all is correct. But the POST data my script receives includes the jQuery version number. My code and results are are below. Should I be escaping this somehow ?
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
My post data comes through as "jQuery17106460378167700797_1345234676316" for the value of text.
It's a POST request, not GET, and should be:
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data: {text : value}, //object
dataType:'JSON',
success:function(data){
}
});
PHP
$value = $_POST['text'];
Also, setting the dataType to JSON evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner, any malformed JSON is rejected and a parse error is thrown. This means any malformed JSON, and your ajax call will fail.
I am not sure when you are executing the script, is it on button press?
If not, you will need to wrap it so that it runs only after DOM had completed loading:
$(document).ready(function()
{
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
});
Im trying to save this string:
~`##$%^&*()_+}{":?><,./;'[]=-|\
using a AJAX call in php. But in the database it saves as this:
~`##$%^????
this is my AJAX call
function saveComment(timesheetId,activityId,date,comment,employeeId) {
var r = $.ajax({
type: 'POST',
url: commentlink,
data: "timesheetId="+timesheetId+"&activityId="+activityId+"&date="+date+"&comment="+comment+"&employeeId="+employeeId,
async: false
}).responseText;
return r;
}
Edit: Fixed display of strings and code.
You need to in javascript call encodeURIComponent on the string with the weird characters before you send it to the server.
EDIT: Tomalak pointed out a better method.
If you want to put a variable 'text' in the data, you should run it through $.URLEncode(text) before doing so; as it is, the '&' character in the text introduces a new parameter.
jQuery supports an object as the data parameter in Ajax requests. This also does the URL encoding for you automatically:
$.ajax({
type: 'POST',
url: commentlink,
data: {
timesheetId: timesheetId,
activityId: activityId,
date: date,
comment: comment,
employeeId: employeeId
},
success: function (data) {
alert(data);
}
});
Also - you should never use synchronous Ajax requests. Always work with callback functions.