0

I need to create a script that takes data from a form, send it to a server (there's some diabolical C# procedure on it, that's not my job...), the server resolves the string and reply me with 4 strings (yup, they are in spanish): 'pendiente', 'verificada', 'rechazada', and finally 'error' Now, I have to get that response and properly show the correct message (hidden-inline html). All this procedure shouldn't "refresh" the actual page, so I'm using AJAX for this.

Have in mind I'm a newbie :) I've learned Jquery just for this task, and I have to say I'm quite happy with this.

The problem

I don't really know how to handle or "manipulate" that request using Jquery... I figured how to send the data to the server, but I think I'm handling incorrectly the response.

The code:

In this case I've adapted the script, every different response should get its own border color, I'm using conditionals (they are wrong for sure) to add CSS clases to an #ajax div.

So, it might have silly errors...

$(document).ready(function () {
    $('#enviar').click(function (event) {
        event.preventDefault(); //avoid page refresh

       var consulta = $('#string').val();
       $("#normal").text(consulta);

//Start AJAX!        
        $.ajax({
            async: true,
            cache: false,
            type: 'post',
            url: 'http://184.22.97.218:8081/chequeostatusdonation', //la del servr
            data: {
                html: consulta
            },
            dataType: 'html',
            beforeSend: function () {
                console.log('Sending...');
            },
            success: function (data) {
                console.log('Just sent -'+data+'- with success dooh');
                $('#ajax').html(data);
                //start conditional
        if (data == pendiente) {
            $("#ajax").addClass(pendiente);
        } else if (data == verificada) {
            $("#ajax").addClass(verificada);
        } else if (data == rechazada) {
            $("#ajax").addClass(rechazada);
        } else {
            $("#ajax").html('<h1>error</h1>');
        }
            //end condicional
            },
            complete: function () {
                console.log('Listo el pollo');
            }
        });
    });
});

Here is the JSFiddle


Edit: Now, I just found these two links learn.jquery.com/code-organization/concepts/ learn.jquery.com/code-organization/beware-anonymous-functions/

Screw my code! :D

4
  • 2
    Do you mean to be using if (data === 'pendiente') where you're comparing to a particular string value? Commented Jun 16, 2014 at 23:22
  • with that "statement" I'm trying to say if "server returned the string 'pendiente' (textually)" then execute this code... I don't know if its ok, I've tried to change the script with what you wrote but doesn't work. That 'data' is taken from the $.ajax function, I don't know if I can do that tho ^^ Commented Jun 16, 2014 at 23:30
  • Unless pendiente is a javascript variable you've defined, then if you want to compare to a string value, you have to put the comparison string in quotes. You probably have other issues too. You SHOULD be looking in the browser error console to see what script errors you have. That's the first place to look when your script isn't working. FYI, your addClass() also needs the string in quotes. Commented Jun 16, 2014 at 23:32
  • Thanks... check the JSFiddle at the main post, I've declared the variables and changed a bit of code... seems to be working now :) Commented Jun 17, 2014 at 0:15

1 Answer 1

1

Async is by default "true", so you don't need to mention that one in your code.

You included a link to the server (in the URL-field), but what is the file you are trying to open? You will need to include the path to where you will get the data from (file / script). To make Ajax work, you will need to respect the "same origin policy", so you can insert a relative path to the file / script.

Is the response of your call always a short string with one of those key words ('pendiente', 'verificada', 'rechazada' or 'error)? In that case I would recomment using "text" instead of "html" as dataType, as jQuery will try to parse it to a DOM-structure, which is not what you want here.

Your if-statements (and class-assignments as well) aren't working because you try to compare it to a non-excisting variable instead of the string with that value. You should use " or ' around your string to solve that.

This code should be working. If not, let me know. Include the error given in the console of the browser.

$(document).ready(function () {
    $('#enviar').click(function (event) {
        event.preventDefault(); //avoid page refresh

       var consulta = $('#string').val();
       $("#normal").text(consulta);

        //Start AJAX!        
        $.ajax({
            type: 'POST',
            cache: false,
            url: 'RELATIVE_PATH_HERE', //la del servr
            data: {
                html: consulta
            },
            dataType: 'text',
            beforeSend: function () {
                console.log('Sending...');
            },
            success: function (data) {
                console.log('Just sent -'+data+'- with success dooh');
                $('#ajax').html(data);
                //start conditional
             if (data === 'pendiente') {
               $("#ajax").addClass('pendiente');
             } else if (data === 'verificada') {
               $("#ajax").addClass('verificada');
             } else if (data === 'rechazada') {
               $("#ajax").addClass('rechazada');
             } else {
               $("#ajax").html('<h1>error</h1>');
            }
            //end condicional
            },
            complete: function () {
                console.log('Listo el pollo');
            },
            error: function() {
                console.log('Problem with XHR-request');
        });
    });
});

Be careful with .addClass if you process multiple Ajax-calls as they will add on each other.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Mathias, I did what @jfriend00 told me about the variables, I've declared them, you have the JSFiddle here jsfiddle.net/Frondor/uvD4N and seems to be working, I also fixed that about the async method and dataType, but still.. I think there is some better way to do what I want :D Regarding to the url, there's some C# code running in a server on which I'm doing the requests, that's why I have to use that url, that server is the one sending me the 4 requests you mention, what's wrong about that?
If you try to perform an Ajax-call from another domain (for example on JSfiddle to your own server or locally via file://), most browsers will block that request (= same origin policy). So if your document (the one you are trying to call via Ajax) is hosted on example.com, your document should be on example.com as well. I'm not sure what you mean with the C#-program though. I will add an error-method to my code, so that you can detect whether that is the problem or not. If not, please share the input of the console of your browser.
Are you talking about MLHttpRequest cannot load http://184.22.97.218:8081/chequeostatusdonation. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access. XMLHttpRequest ? I got that error and my mate fixed it with the following code in his program: pastebin.com/77a4h27k It's a software (written in C#) he made to manage donations/payments, I'm building a web application in html/jQuery to check payments status. Here is the final fiddle jsfiddle.net/Frondor/R5zH6 Also added your error-method
That IS what I mean with "same origin policy". ;) You mentioned that your friend fixed the problem. Does that mean it is working now?
Anyway, I just noticed something about crossDomain option for ajax methods with jQuery I didn't know... I'm pretty sure the script can, and SHOULD be improved/optimized (don't know how), but it seems to be working: jsfiddle.net/Frondor/R5zH6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.