In Ajax response my if condition is not working - javascript

Check the jquery code bellow. Here after process post request the response returning no_file_found but if condition not meeting and not hitting alert(). Whats wrong i am doing here?
$("#btnFoo").on("click", function () {
var file_data = $('#formUploadImg').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('ProId', $(this).attr("img-upload-product-id"));
$.ajax({
url: '/mycontroller/upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
console.log(typeof response);//it returns string
if (response == "no_file_found") {
alert("this not hits");//this alert not hits
}
},
error: function (response) {
alert("Error");
}
});
});
Please note i am using c# mvc5 and the response is comming from mvc5 controller. Mvc5 example bellow:
[HttpPost]
public JsonResult upload()
{
return Json("no_file_found");
}

You need to use .trim() function to make sure all unseen spaces are removed from the response to be able to match the exact comparison== of no_file_found.
Edit: The reason it is not working is because you are returning "no_file_found" with double quotes "" added. But on the front end you are checking simply no_file_found - You need to use replace function to make sure all the double quotes are deleted from the response.
var response = '"no_file_found"';
if (response.replace(/["']/g, "").trim() == "no_file_found") {
alert("this hits"); //this alert hits
}

The problem here is that you are returning a Json value - but your ajax is set to have a dataType: 'text'.
If you change dataType: 'json' all works as expeceted.

Related

JQuery AJAX request not working.

I am using AJAX for the first time and I am not sure if I have the correct syntax down. Basically I have a method in the behind code that takes in 2 string parameters and executes an updates the users password. But it keeps coming back as failed.
Here is my current asp button:
<td><asp:Button ID="Button1" runat="server" Text="Add Password" alt="Add Password" /></td>
This is the code that executes once the user hits the Add Password button on the form:
$("#edit_password_form").submit(function (e) {
e.preventDefault();
var finalValue = value2.value;
<%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%>
var custNoString = <%=inputCust%>
$.ajax({
url: 'reciept.aspx/Button1_Click',
method: 'post',
contentType: 'application/json',
data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}',
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
});;
Any ideas on why it could be failing? Mayb I am missing an ajax key or my syntax could be off.
Let me know! Thanks.
Data parameters need properly created JSON. You are missing out on some single quotes here and there.
Instead of manually creating the JSON string, try creating an object first, then stringify it for data. Refer to the code below:
$("#edit_password_form").submit(function (e) {
e.preventDefault();
var finalValue = value2.value;
<%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%>
var custNoString = <%=inputCust%>
var dataObj = {};
dataObj.custID = custNoString;
dataObj.tempPass2 = finalValue;
$.ajax({
url: 'reciept.aspx/Button1_Click',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(dataObj),
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
});;
it is not correct syntax to post data: data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}'
try to pass your data by json format this way data: { custID: custNoString, tempPass2: finalValue }
otherwise it should not work .
more check this link http://www.json.org/JSONRequest.html
(Posted as answer on behalf of the OP).
This is what ended up working for me:
// Create the data object for the 2 parameters for the c# Method
var dataObj = { custID1: custNoString, tempPass2: finalValue };
// AJAX request for run the function
$.ajax({
type: 'post',
url: 'reciept.aspx/Button1_Click',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataObj),
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
Creating the data object first was the key. Thank you for all your help and suggestions!

Check if $.ajax has already been sent and if so then retrieve data without resending

I have this ajax request that is sent from javascript in my page
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
async: false,
success: function(data) {
alert(data);
}
});
This returns an array of items with some text and ...
Now if the user clicks on a certain button the data needs to be copied to another place on the page(div)
Is there any way I can get the data again from the file (in the network tab "chrome") without resending the request?
Put the response in global variable (dataArray) and every time check that variable has value or not. So that request will not send further time. Also, you can use that global variable (dataArray) in other methods.
var dataArray = "";
function getData(){
if(dataArray != ""){
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
//async: false,
success: function(data) {
//alert(data);
dataArray = data;
}
});
}
}

Pass javascript function from .Net code behind shared function or web method to page

I need to send a script to the page from WebMethod used by Ajax that fires when click HTML link. I couldn't use the script manager with "Me" or "Page" control and can't reference any controls.
I just need to return that session is nothing , Any Ideas?
The button clicked to send Ajax is HTML link and all I need to check if session expired (which I can check it on load) so if it's expired want to alert user since I already don't complete the process after checking it in code behind
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
''''' my code
''''''''''''''''''''''
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Return "Success"
Else
Return "noSession"
End If
Catch ex As Exception
Return "failure"
End Try
Else
ScriptManager.RegisterStartupScript(Me, GetType(String), "Checkeng", [String].Format("LevelsMsg();"), True)
End If
End Function
JQuery Ajax
It's more complecated but I thinkk this is the main part:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
},
error: function() {
alert("There is a problem in saving data");
}
});
});
Your WebMethodis a Shared function which is equivalent to a Static function in C#. This means you will not be able to access any variables other than those declared inside of this Shared function. However, the nature of WebMethods allow a return to "its" caller via "Success" or "error" which can be "intercepted". Thus, no need to use ScriptManager.RegisterStartupScript since your POST will return to AJAX realm anyway, which means you can call any JavaScript function there.
You could Change your code this way:
VB.NET Code-Behind:
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
' YOUR CODE
Return "Success"
Catch ex As Exception
Return "Failure"
End Try
Else
Return "NoSession";
End If
End Function
JavaScript:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
/* since we put "NoSession", then we should check for it here */
if(response.d == "NoSession") {
/* This is where you "replace" the use of RegisterStartupScript
by safely calling any JS function here */
LevelsMsg();
}
},
error: function() {
alert("There is a problem in saving data");
}
});
});

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

Categories

Resources