Question :
I’m trying to send the data from this page to the server, but Js does not return the Message variable …
I know little of JS and would like some way to call the variable as soon as the server receives the data.
Answer :
Enable server-side CORS …
( link )
If you add an error to your ajax, you will notice that it drops there.
$.ajax({
type: "GET",
url: strUrl,
crossDomain: true,
dataType: 'jsonp',
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function(data)
{
if (data == "Realizado com sucesso.")
{
var Mensagem = "Obrigado por se cadastrar na BILLABONG!";
$("#divNewsLetterContainer").html("");
$("#divNewsLetterContainer").append("<span class='spnMensagemNewletter'>" + Mensagem + "</span>");
}
else
{
alert(data);
}
},
error: function(data) {
alert('Ocorreu um erro, olhe o console');
console.log(data);
}
});
Add an action to your form:
<form action="javascript:void(0);" id="divNewsLetterContainer" class="newsletter" onsubmit="EnviarNewsLetter();">
<input type="text" class="fitext" name="nome" id="nome" size="20" value="" placeholder="name" required="">
<input type="email" name="email" id="email" size="20" value="" placeholder="name@email.com" required="">
<input type="submit" id="btw-ok" value="assinar" class="btw-ok">
</form>
It seems to me that your problem lies in the variables:
var strNome = $("#nome").attr("value");
var strEmail = $("#email").attr("value");
Switch By:
var strNome = $("#nome").val();
var strEmail = $("#email").val();
As it is, they are being sent “empty”, so it does not return anything in Ajax.
Also change your form
by adding a onsubmit
, like this:
<form id="divNewsLetterContainer" class="newsletter" onsubmit="return EnviarNewsLetter()">
<input type="text" class="fitext" name="nome" id="nome" size="20" value="" placeholder="name" required/>
<input type="email" name="email" id="email" size="20" value="" placeholder="name@email.com" required/>
<input type="submit" id="btw-ok" value="assinar" class="btw-ok">
</form>
And in the script, add return false;
after Ajax (this prevents the page from being reloaded):
$.ajax({
...
});
return false;
Another thing … where it has:
if (data == "Realizado com sucesso."){
...
}
Maybe it’s better to use:
if (data.indexOf("Realizado com sucesso.") != -1){
...
}
Unless the return of the variable data
is a string EXACTLY equal to “Done successfully.” (without HTML tags etc).