jQuery Ajax POST request - javascript

I am trying to get the following code to send variables to a PHP page via POST. I am not quite sure how to do it. This is my code sending data via GET and receiving it via JSON encoding. What do I need to change to pass variables to process_parts.php via POST?
function imagething(){
var done = false,
offset = 0,
limit = 20;
if(!done) {
var url = "process_parts.php?offset=" + offset + "&limit=" + limit;
$.ajax({
//async: false, defaults to async
url: url
}).done(function(response) {
if (response.processed !== limit) {
// asked to process 20, only processed <=19 - there aren't any more
done = true;
}
offset += response.processed;
$("#mybox").html("<span class=\"color_blue\">Processed a total of " + offset + " parts.</span>");
alert(response.table_row);
console.log(response);
imagething(); //<--------------------------recursive call
}).fail(function(jqXHR, textStatus) {
$("#mybox").html("Error after processing " + offset + " parts. Error: " + textStatus);
done = true;
});
}
}
imagething();

The default method is GET, to change that, use the type parameter. You can also provide your querystring properties as an object so that they are not immediately obvious in the URL:
var url = "process_parts.php";
$.ajax({
url: url,
type: 'POST',
data: {
offset: offset,
limit: limit
}
}).done(function() {
// rest of your code...
});

Try This
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(ty),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});

Related

How do I need to convert this to plain javascript or jquery?

I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sending data from JQuery to C#, ASP.Net

I have a canvas in my .aspx form page where one can sign a signature, I would like to send the base64 data from the JQuery client side to the C# Asp.Net side. Here I want to upload this base64 data to a database.
(a couple things I tried)
Jquery:
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: '{ data: "' + base64 + '"}',
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 }); // another thing i tried
C#:
var d = Request.Params["data"];
The variable d is null when i put a breakpoint at it.
Does anybody see how I can tackle this hurdle, or make it easier?
(note: I do not have a lot of experience with JQuery)
Your JSON with base64 could be available as request body.
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
string text = reader.ReadToEnd();
}
If you replace
url: 'EvaluatieForm.aspx'
by
url: 'EvaluatieForm.aspx?data=' + base64
and remove
data: '{ data: "' + base64 + '"}',
then it will work.
Try this:
Just a small change in your existing code, used JSON.stringify to post data.
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
var objectToPasss = {data: base64};
var postData =JSON.stringify(objectToPasss );
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: postData,
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 });
Try this:
$("#savebtn").bind("click", function () {
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: {
sketch: $('#sketch')[0].toDataURL("image\png")
},
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
where
var d = Request.Params["sketch"];
The data argument in the jQuery ajax() function works in conjunction with the contentType. As you are setting it to application/json, then it stands to reason that data will be serialized, so setting the sketch variable seems about right.
With ajax you can try xhr.
maybe this thread helps you out! :)
How can I upload files asynchronously?

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Jquery append multiple PHP responses in real time

basically I want a Jquery function to call a PHP script multiple times, and every single time, load the response into a div, this is the code I have now:
images = 10;
while(images > 0)
{
$.ajax({
type: "POST",
url: "processimage.php",
data: { image : 1 },
async: false,
success: function(data) {
$( "#logger" ).append(data+ '<br />');
}
});
images--;
}
What this code is doing is processing all the images and then appending the full response, but I want it to append the response for every single image. Somehow the while block is entirely being processed before updating the #logger div. Am I missing something?
you must remove the async: false. which in turn allows the requests to complete and be appended as they finish. However, you'll then realize that they are being appended out of order! to fix that, we can use promise objects and .then.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: images
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
images--;
}
Now, there's still one more possible issue. if you needed to pass the current value of images with each request, the previous code will send all requests after the first with the last value of images. To fix that, we can use an iffe.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
(function(i){
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: i
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
})(images);
images--;
}
And then you can make it DRYer as suggested below by storing the options in a separate variable:
images = 10;
var ajaxOpts = {
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
};
var req = $.ajax(ajaxOpts);
images--;
while (images > 0) {
(function(i){
req.then(function(){
ajaxOpts.data.image = i;
return $.ajax(ajaxOpts);
});
})(images);
images--;
}

Javascript newbie creating objects with ajax

I have the following code and want to use it as an object.
How to i access the properties of the object? currently i am always getting undefined!
function getLoggerInfo()
{
$.ajax({
url: "data.json",
type: "GET",
data: {emGetInfo: "logger"},
dataType: "json",
success: function(response){
//alert("1: " + this.loggerName);
loggerName = response.emGetInfo[0].loggerName;
protocol = response.emGetInfo[0].protocolVersion;
$("#console").text("Logger Name: " + loggerName + " - Protocol Version: " + protocol);
return;
},
error: function(jqXHR, textStatus, errorThrown){
$("#console").text("ERROR: AJAX errors. " + jqXHR + " : " + textStatus + " : " + errorThrown);
return;
},
statusCode: {
404: function() {
$("#console").text("404: The requested JSON file was not found.");
return;
}
}
});
}
// get loggerName...
$(document).ready(function () {
// Get logger info event...
$("#ajax").click(function() {
var loggerInfo = new getLoggerInfo();
alert("Loggername: "+ loggerInfo.loggerName);
});
});
AJAX is asynchronous - so it does not return data ... the following is a (rough) outline of what happens when you use the $.ajax() function
The data is sent to the url
The browser continues - executing other code as required
When the url (called in step 1) finishes being processed the success callback is executed.
Step 3 could be 1 second, 10 seconds, 5 minutes later
you should process the request in the success callback :
$.ajax({
url: "data.json",
type: "GET",
data: {emGetInfo: "logger"},
dataType: "json",
success: function(response){
// process here
loggerName = response.emGetInfo[0].loggerName;
alert(loggerName);
}
});

Categories