3

Okay here's my situation.

I have a php file that contains a simple form asking for name, number, etc. Now when I click submit, I have the form action set to a URL for an API that process those variables.

The problem is that when I submit the form, it takes me to a page where the API website confirms the submission with some jibberish xml text.

What I wanna do is be able to let the user fill the form data, secretly submit that data to the API URL, and display a thank you page for the user. I don't want the user to be aware of the confirmation page of the API, just a form submission, which takes him directly to a thank you page.

The API accepts requests in the following form

"MY-API-URL.com/json?api_key=KEY&api_secret=SECRET&login=LOGIN&password=PASSWORD"

This is the form header..

<form action="MY-API-URL.com" class="login">

Any help is appreciated!

Omran
  • 95
  • 2
  • 12

1 Answers1

2

Make an ajax call to submit your form.

Make a self submitting form action="" like this:

<form id="login" name="login" action="" method="POST">
    <input type="text" name="login" value="">
    <input type="password" name="password" value="">
    <input type="submit" name="submit" value="Log in">
</form>

Handle your form's submit event with jQuery:

<script>
$(function(){
    $("form#login").submit(function(){
        var login = $("input[name=login]").val();
        var password = $("input[name=password]").val();

        $.ajax({
            url: "MY-API-URL.com/json", 
            type: "POST",
            data: {"api_key":"KEY", "api_secret":"SECRET", "login":login, "password":password},
            dataType: "jsonp",
            cache: false,
            success: function (data) {              
                //make your redirect here or just display a message on the same page
                window.location = "congrats.html";
            },
            error: function(jqXHR, textStatus, errorThrown){
                // handle your error here
                alert("It's a failure!");
            }       
        });
        //cancel the submit default behavior
        return false;
    });
});
</script>

Update:
As far as I understand nexmo doesn't support jsonp and you can't use json because you are making cross-domain call. There are plenty of posts about it here. For example json Uncaught SyntaxError: Unexpected token :

As a work around you can use proxy. You can read about it here and download simple proxy here.

If you would use a proxy mentioned above your code would look like:

<script> 
$(function(){ 
    $("form#sms").submit(function(){ 
        var from = $("input[name=from]").val(); 
        var to = $("input[name=to]").val(); 
        var text = $("input[name=text]").val(); 

        var url = "http://rest.nexmo.com/sms/json?api_key=key&api_secret=secret" + "&from=" + from + "&to=" + to + "&text=" + text; 
        $.ajax({ 
            url: "simple-proxy.php", 
            type: "GET", 
            data: {"url": url}, 
            dataType: "json", 
            cache: false, 
            success: function (data) {               
                //make your redirect here or just display a message on the same page 
                console.log(data); 
                if (data && data.contents && data.contents.messages && data.contents.messages.length) {
                    alert("The status is: " + data.contents.messages[0].status);
                }
                alert("SMS sent!"); 
            }, 
            error: function(jqXHR, textStatus, errorThrown){ 
                // handle your error here 
                alert("textStatus: " + textStatus + "\n" + "errorThrown: " + errorThrown); 
            }       
        }); 
        //cancel the submit default behavior 
        return false; 
    }); 
}); 
</script> 

I made it work on my machine, and it returned proper json response.

Community
  • 1
  • 1
peterm
  • 91,357
  • 15
  • 148
  • 157
  • Well my API uses a www.apiwebsite.com/json?variable1=something&variable2=something .. And I'm having trouble using ajax to submit that string to the remote server.. Any ides? – Omran Dec 23 '12 at 21:17
  • If it's a different domain from yours you need to use `dataType: "jsonp"`. For more information see [jQuery.ajax()](http://api.jquery.com/jQuery.ajax/) – peterm Dec 23 '12 at 21:22
  • Well, I tried the above, didn't work.. the page just refreshes! Any ideas? Here's my code so far .. http://pastebin.com/ivL9XVNV – Omran Dec 23 '12 at 21:40
  • That's because you didn't include a link to jQuery. Sorry, thought that was obvious. To do that you need put following line `` right after ``. I've added it to your patebin. – peterm Dec 24 '12 at 01:50
  • peterm, it works but I have a problem with the success reply, it always gives a failure although the message is sent. This is the reply I get from the API server: {"message-count":"1","messages":[{"to":"number","message-price":"price","status":"0","message-id":"msgid","remaining-balance":"balance","network":"network"}]} The status part is the one that replies success as 0 and failure as any other number. Any ideas? – Omran Dec 24 '12 at 18:21
  • And thank you so much for the previous help, works like a charm! :) – Omran Dec 24 '12 at 18:21
  • If I understand you correctly you end up in a $.ajax success handler, but always get negative result in a reply from your API server. If that is the case in order to help you I need more information about that API. – peterm Dec 24 '12 at 18:35
  • What actual status do you get? – peterm Dec 25 '12 at 01:35
  • I just get it's a failure from the script you sent me! – Omran Dec 25 '12 at 01:36
  • Well, I've created the proxy.php file in the same domain as the script, and yes I changed the file name in the script as well, now it just gives SMS Sent! for every request, even with empty fields. – Omran Dec 25 '12 at 07:46
  • That's right. It's because nexmo returns valid json in response even if you don't supply anything. Just take a look at data variable in the success handler. I `console.log` it specifically for that. For me it returns `{"status":{"http_code":200},"contents":{"message-count":"1","messages":[{"error-text":"Bad Credentials","status":"4"}]}}` because I don't have any valid credentials to authenticate. Long story short - analyze returned data. – peterm Dec 25 '12 at 08:03
  • I can't seem to get it to work, I can't seem to understand the output of the console.log. I also found this part in the API documentation, maybe it's helpful? http://nexmo.com/documentation/index.html#dlr Oh, and the console.log just shows a http_code = 200 on every request! – Omran Dec 25 '12 at 08:26
  • You need to try a bit harder. Any major browser allows you visually traverse through the logged object. If you can't do it for any reason you can just `alert` any property of `data` object. See revised answer for that. – peterm Dec 25 '12 at 08:45
  • Thank you for that, now it shows the error status numbers, I'm guessing I need to edit the [alert("textStatus: " + textStatus + "\n" + "errorThrown: " + errorThrown);] part to fire a message on each different error code, correct? If so, would I just need to change the errorThrown and the testStatus? – Omran Dec 25 '12 at 08:54
  • Just implement whatever logic you need based on the JSON response from your API server, that you successfully getting now. According to the API documentation the status=0 is success, so make your redirect on that. If you get something other then 0, then probably you need to tell that to the user or log that event... – peterm Dec 26 '12 at 08:00