I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
Related
When I want to send data as datatype json it response this error:
SyntaxError: Unexpected token < in JSON at position 0
When I tried to send the data as datatype text, it sends the data to php successfully but my php wont respond.
ajax/js as datatype json:
let form = $("#form");
$("#form").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "POST",
dataType: "json",
data: {
test: 1
},
success: function (r) {
console.log("!!!");
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
ajax/js as datatype normal:
let form = $("#form");
$("#form").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "POST",
data: form.serialize(),
success: function (r) {
console.log("!!!");
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
php code:
if(isset($_POST["test"])){
echo "<script>console.log('works');</script>";
}
Try this
var ob = {
test: 1
};
$.ajax({
url: "test.php",
method: "POST",
dataType: "json",
contentType: 'application/json',
data:JSON.stringify(ob),
success: function (r) {
console.log("!!!");
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
Here is the code I am using to access my web API controller named Owner; the success function is not being called. Any ideas?
$.ajax({
type: "GET",
url: 'http://localhost:26533/api/Owner',
contentType: "application/json",
dataType: "jsonp",
success: function (response) { alert("yes"); }
});
Remove the contentType and dataType and check the response..
Here an example:
$.ajax({
type: 'GET',
url: 'http://localhost:26533/api/Owner',
success: function(data){
alert(data);
},
error: function(xhr, type, exception) {
// if ajax fails display error alert
alert("ajax error response type " + type);
}
});
With this you can see what's wrong...
How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});
I have a simple form submission with ajax, but it keeps giving me an error. All the error says is "error". No code, no description. No nothing, when I alert it when it fails.
Javascript with jQuery:
$(document).ready(function(){
$(".post-input").submit(function(){
var postcontent = $(".post-form").val();
if (postcontent == ""){
return false;
}
$(".post-form").attr("disabled", "disabled");
$.ajax({
url: '/post',
type: 'POST',
data: {"post-form": postcontent},
dataType: json,
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
});
});
HTML:
<form class="post-input" action="" method="post" accept-charset="utf-8">
<textarea class="post-form" name="post-form" rows="1" cols="10" onFocus="this.value='';return false;">What are you thinking about...</textarea>
<p><input class="post-submit" type="submit" name = "post.submitted" value="Post"></p>
</form>
and if there are no problems there, then the server-side (pyramid):
def post(request):
session = Session()
user = authenticated_userid(request)
postContent = request.POST['post-form']
if not postContent == '':
session.add(Activity(user.user_id, 0, postContent, None, None))
return {}
return HTTPNotFound()
UPDATE:
After some more debugging with firebug, I discovered that the post request body contains only post.submitted=Post, instead of the intended result of {"post-form": postcontent}.
According to jQuery documentation, you must declare the data type:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Also, looking at your server-side code, you don't actually want to post JSON formatted data. This {"post-form":postcontent} is JSON formatted data. What you actually want to do is send TEXT or HTML. Seeming as it's form data, I would guess at TEXT.
Try this:
$.ajax({
url: '/post',
type: 'POST',
data: 'post-form='+postcontent,
dataType: 'text',
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
Since you are posting JSON-data you have to declare the dataType "JSON":
$.ajax({
url: '/post',
type: 'POST',
dataType: "json",
data: {"post-form": postcontent},
success: function(response, textStatus, jqXHR) {
alert("Yay!");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
I think the problem is that the data that you are passing is not properly written.
Try to change this:
data: {"post-form": postcontent},
To this:
data: 'post-form='+ $('.post-form').val(),
question says it all... code:
$(document).ready(function() {
dataToLoad = 'showresults=true';
$.ajax({
type: 'post',
url: 'submit.php',
datatype: 'html',
data: dataToLoad,
async: true,
success: function(data){
$('#results').html(data);
},
});
});
You should use
dataType: 'html'
instead of
datatype: 'html'
and remove the trailing comma at the end (IE<=7 will throw error)
If the problem persists, add an error callback to see if there's an error
error: function(xhr, status, errorThrown){
alert("Error:\n" + status);
}
Hope this helps.
Cheers