Javascript AJAX request - check for success action - javascript

I have a Javascript that is called from a button which makes an HTTP GET request. At the moment when it encounters an error it shows a hidden div with the request error, which is all working well. Here's the script:
$("#callContact1").click(function() {
console.log('starting event');
$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET"
})
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
var httpStatus = status;
var httpResponseCode = (xhr.status);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var httpResponseCode = (xhr.getAllResponseHeaders);
var ajaxError = 'There was an requesting the event. HTTP Status: ' + httpStatus;
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
//make alert visible
$('#ajaxResponse1').html(ajaxError).show();
})
})
I now need to extend this slightly to, when it is successful, show a different hidden div with a success message, e.g.:
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
I'm just not sure how to extend this script - fairly new to JS and jQuery at this point.

There is a success function in JQuery AJAX:
Use it like so:
.success(function(response) {
//DO stuff here.
})
A better simpler code can be like:
$.ajax({
url: 'http://example.com',
method: 'GET',
success: function (response) {
},
error: function (e) {
}
});
View the full documentation of JQuery ajax functions is at
http://api.jquery.com/jquery.ajax/
OR at
https://www.w3schools.com/jquery/ajax_ajax.asp

$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET",
success : function(data)
{
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
},
error:function(xhr,status)
{
alert(xhr.statusText);
}
});
Using short form of ajax:
$.get("www.xyz.com/abc",{eventId: eventId},callbackFunction);

You are registering two callbacks with the Ajax call. You seem to know that fail is executed on error. That leaves that the .then callback is executed on success. Just add the call there:
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
$('#ajaxResponseSuccess1').html('Event Update in Progress').show(); // <--
// ...
})

Related

Jquery-ajax doesn't succeed

I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).

jQuery ajax POST request for log in

I am trying to write a .ajax request through a form to log in. When I submit my form, nothing happens with either the success or error functions. I notice that if I put an alert box after the .ajax call it does not work either. I would expect, that if I am just incorrectly putting the data, I would at least expect the error alert box to show up? Here is my code:
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
e.preventDefault();
});
});
I noticed you're already using JQuery. So perhaps use the built in post function. Example below:
Also side note: You've got a slight type in your variable: data: $(this).serialize() + "&client_type=" + clienttype, clienttype was declared with a capital T: clientType
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
e.preventDefault();
$.post("myurl",{data:$(this).serialize(),client_type:clientType},function(data){
console.log("Date returned from request:",data);
// Returns JSON Data. So data.clientType.
},'json');
});
});
If you add in a trigger to cancel the page from being submitted, it should work (return false;), take a look below.
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
return false;
});
});

Debugging jquery handlers

This question is a followup of this one. I have created a simple example to check how code is executed within the handler. For the form
<form id="calendar_id" method="post">
Insert date: <input id="date_id" type="text" name="l_date" required>
</form>
I'm trying to retrieve the fields using the following javascript:
function get_form_data_uid($form) {
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function (n, i) {
indexed_array[n['name']] = n['value'];
});
indexed_array['uid'] = 'badbfadbbfi';
return indexed_array;
}
$("#calendar_id").submit(function (e) {
var uri, method, formId, $form, form_data;
// Prevent default submit
e.preventDefault();
e.stopImmediatePropagation();
uri = "/";
method = "POST";
formId = "#calendar_id";
$form = $(formId);
form_data = get_form_data_uid($form);
alert("form_data " + form_data);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
// Setting async to false to give enough time to initialize the local storage with the "token" key
async: false,
dataType: "json",
data: form_data
};
// Make the request
$.ajax(request).done(function (data) { // Handle the response
// Attributes are retrieved as object.attribute_name
console.log("Data from change password from server: " + data);
alert(data.message);
}).fail(function (jqXHR, textStatus, errorThrown) { // Handle failure
console.log(JSON.stringify(jqXHR));
console.log("AJAX error on changing password: " + textStatus + ' : ' + errorThrown);
});
});
However, the code within the handler is not executed (the alert is not shown). Why?
Edit:
The code works jsfiddle but not in firefox.
At least, you are calling a function get_form_data_with_token() which is not defined anywhere in your posted code. Perhaps you meant to call your get_form_data_uid().
Would have just made this a comment, but apparently cannot.

PHP headers always give error Undefined Index even using $_SERVER global

I am performing an ajax request cross domain. I have been trying to use functions that return the headers in an array only to find that I get Undefined Index even though I can return their values in my ajax request and print them the screen.
I have found some posts on SO that said I should be using $_SERVER globals. So I switched to that method only to get the same results.
Here is my jQuery:
setTimeout(function() {
jQuery.ajax({
url: 'http://something.com',
type:"POST",
dataType:"json",
crossDomain:true,
contentType:"application/json",
data: jsonData,
processData:false,
cache:false,
beforeSend: function( xhr ) {
xhr.setRequestHeader("Authorization",api_key[index]);
xhr.setRequestHeader("Action","PUSH");
},
success: function(data) {
alert(data.action);
alert(data.platform + ' : ' + data.message + ' : ' + data.app_name );
if(data.message == 'success')
{
jQuery('#hollmanPNs_send_push div#hollmanPNs_progressbar' + index).progressbar("value",100);
//add message to the paragraph for app name
jQuery('#hollmanPNs_send_push p#hollmanPNs_paragraph' + index).append(': Complete');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert( 'We had an error: ' + textStatus + errorThrown );
}
}).fail(function() {
alert( 'We had a failed AJAX call.');
});//end ajax
}, index * 5000);//end timeout function
And here is what I am using for PHP:
if($_SERVER['HTTP_ACTION'] != '')
{
//Do Something
}
I have tried switching to:
xhr.setRequestHeader("X-Action","PUSH");
and
$_SERVER['HTTP_X_ACTION']
with the same results. Only I was not able to return them to my ajax request.
I am using PHP 5.3.3.
I am also using this function which I change depending on the different headers I am trying at the time:
header('Access-Control-Allow-Headers: Action, Authorization, Content-Type');
You'll want to get the headers a different way like so:
$headers = getallheaders();
if(array_key_exists('Action', $headers) && $headers['Action'] != '')
{
//Do Something
}

How to correctly post data with ajax into div?

Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}

Categories