I'm doing a contact form and I'm trying to use AJAX. I've followed some youtube guide, but the code didn't work for me. I believe the problem is with the datosEnviados object, but I don't know how to fix it. I tried using parse function but it didn't work either.
The error I get is the following
SyntaxError: Unexpected token < in JSON at position 0 (...)
The code of my JS function is:
function ejecutarAjax(event) {
var datosEnviados = {
"nombre":$('#nombres').val(),
"email":$('#email').val(),
"comentario":$('#comentario').val()
}
$.ajax({
type : 'POST',
url : '../php/enviar_contacto.php',
data : datosEnviados,
dataType: 'json',
encode : true
})
.done(function() {
alert("ok");
})
.fail(function(jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText);
});
event.preventDefault();
}
Is there anything wrong with my syntax when defining datosEnviados or is it something else?
Thanks in advance
Try this
function ejecutarAjax(event) {
event.preventDefault(); //This should be at top
var datosEnviados = {
//Try with replace "nombre" to nombre(Remove "")
number : $('#nombres').val(),
email : $('#email').val(),
comentario : $('#comentario').val()
}
$.ajax({
type : 'POST',
url : '../php/enviar_contacto.php',
data : datosEnviados,
dataType: 'json',
encode : true
})
Alternative
function ejecutarAjax(event) {
event.preventDefault(); //This should be at top
$.ajax({
type : 'POST',
url : '../php/enviar_contacto.php',
data : {
nombre : $('#nombres').val(),
email : $('#email').val(),
comentario : $('#comentario').val()
},
success: function(data){
//Your code goes here
}
})
Hopefully, this will work
Related
Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error.
var user = $('.username').value();
var pass = $('.password').value();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username': user,
'password': pass
},
beforeSend: function() {
$("#Loading").show();
},
success : function(response) {
if(response=="success" && response!=="fail") {
$('.status').html("Success! Now logging in ......");
setTimeout(' window.location.href = "index.php"; ',4000);
} else {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(' window.location.href = "login.php"; ',4000);
}
}
});
Can anyone points me out?
The reason you are getting error is because your javascript is getting break(giving error) at $('.username').value(); as there is no value() function. If you open console you get this error. So because of this rest of script is not working. So change $('.username').value(); to this $('.username').val(); and same for the var pass = $('.password').value(); change to var pass = $('.password').val(); and also you don't need if condition as mention in comment. Your final code will be something like this.
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type: 'POST',
url: //some url
data: {
'username': user,
'password': pass,
},
beforeSend: function() {
//some code
},
success: function(response) {
// some code which you want to excute on success of api
},
error: function(xhr, status, error) {
// some code which you want to excute on failure of api
}
});
I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username':user,
'password':pass,
},
beforeSend: function()
{
$("#Loading").show();
},
success : function(response)
{
$('.status').html("Success! Now logging in ......");
setTimeout(()=>{ window.location.href = "index.php"; },4000);
},
error: function(xhr, status, error) {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(()=>{ window.location.href = "login.php"},4000);
}
});
Your response needs to be a PHP echo that returns a string with a value of either ”success” or ”fail”.
Your PHP response after successful login:
echo(‘success’);
Your PHP response after failed login:
echo(‘fail’);
I am working on form updation with ajax. It works fine when i use GET method in ajax but it throws error 405 method not allowed when i use Post method. I am testing this on Localhost. I have done this before in localhost and it worked fine. And by the way i am using Laravel 5.2 for this.
here is my ajax code.
$('#update-modal').on('click',function(){
$.ajax({
method : "POST",
url : updateURL,
data : { client_id : $('#client_id').val(),
client_name : $('#client_name').val(),
client_business : $('#client_business').val(),
client_ref : $('#client_ref').val(),
gmail_mail : $('#gmail_mail').val(),
gmail_pass : $('#gmail_pass').val(),
client_dob : $('#client_dob').val(),
client_addr : $('#client_addr').val(),
client_no1 : $('#client_no1').val(),
client_no2 : $('#client_no2').val(),
domain_name : $('#domain_name').val(),
domain_p_date : $('#domain_p_date').val(),
domain_reg : $('#domain_reg').val(),
domain_ex_date : $('#domain_ex_date').val(),
domain_acc_email : $('#domain_acc_email').val(),
domain_acc_pass : $('#domain_acc_pass').val()},
_token : token
})
.done(function(msg){
console.log(msg['message']);
});
});
Here is my script used inside the view
<script>
var updateURL = '{{ route('updateDomain') }}';
var token = '{{Session::token()}}';
</script>
here is my route
Route::post('/updateDomainModal' ,function(\Illuminate\Http\Request $request){
return response()->json(['message'=> $request['client_name']]);
})->name('updateDomain');
When the method inside ajax function and Route is changed to GET, It print the client's name passed in the console But when the same is done with POST method it throws the error This is the error details
jquery.min.js:2 GET http://localhost:8000/updateDomainModal?client_id=4&client_name=ABCD&client…2+15%3A01%3A40&domain_acc_email=abc123%40gmail.com&domain_acc_pass=123456 405 (Method Not Allowed)
You are wrongly using an } in the line starting with domain_acc_pass. You should use that '}' after assigning the token value. Now, the token won't send to the target, which is required.
Use type "POST'
$.ajax({
type : 'POST',
url : updateURL,
data : { client_id : $('#client_id').val(),
client_name : $('#client_name').val(),
client_business : $('#client_business').val(),
client_ref : $('#client_ref').val(),
gmail_mail : $('#gmail_mail').val(),
gmail_pass : $('#gmail_pass').val(),
client_dob : $('#client_dob').val(),
client_addr : $('#client_addr').val(),
client_no1 : $('#client_no1').val(),
client_no2 : $('#client_no2').val(),
domain_name : $('#domain_name').val(),
domain_p_date : $('#domain_p_date').val(),
domain_reg : $('#domain_reg').val(),
domain_ex_date : $('#domain_ex_date').val(),
domain_acc_email : $('#domain_acc_email').val(),
domain_acc_pass : $('#domain_acc_pass').val()},
_token : token
});
If you submit form
$("#form-name" ).submit(function(ev) {
ev.preventDefault();
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR)
{
location.reload();
},
error: function(jqXHR, textStatus, errorThrown)
{
consonle.log("error");
}
});
});
I have this function in my UsersController. I created this JSON response by using the _serialize key:
public function test() {
$arrEmail = $this->User->find('first');
$this->set('foo', $arrEmail);
$this->set('_serialize', array('foo') );
}
Now in the client side, in my phonegap application, I am trying to access this data. So I put the following:
<script>
$( document ).ready(function() {
alert(1);
$.ajax({
url : "http://localhost/database/users/" + 'test.json',
async : false,
cache : false,
crossDomain: true,
dataType : 'json',
type : 'post',
success : function(result) {
alert('success');
alert(JSON.stringify(result));
},
error : function(xhr, status, err) {
//con failed
alert(err+' '+xhr+' '+status);
}
});
});
</script>
The alert gives me the following .
Now I need to access to the username and the other attributes. I tried result.attributename but i always get undefined as a response.
EDIT:
`result.foo.User.id` solved the issue.
I was looking for that error in stack but didn't find anything about it (exept listeners). So I have code like this:
<a onclick="startDownload(447, '63dc7ed1010d3c3b8269faf0ba7491d4', 217)">
and my Js is:
function startDownload(modId, secret, file){
var transfer = {
id : modId,
secret : secret,
file : file
};
$.ajax({
url: "download/index",
type: 'POST',
dataType: 'json',
data: transfer,
success: function(data) {
if(data.redirect_failed){
location.href = data.redirect_failed;
} else if(data.redirect_success){
location.href = data.redirect_success;
}
}
});
};
so why this not working with IE? how to fix it?
I am trying to get data from ajax call by cross domain.
Here is code
function GetMaxWULen() {
var x;
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).done(function(result) {
console.log('done result');
x = result;
console.log(x);
});
console.log('function end');
console.log(x);}
At the end of the function, x variable is undefined but in done event value is correct.
Could anyone can help me or tell what is wrong in this code?
This happens because your AJAX request is done asynchronously. It means the rest of your code won't wait your response be ready to continue.
If you need to use the data returned from AJAX outside your function, you might want to create a parameter to serve as a callback when the response is ready. For example:
function yourFunction(callback) {
$.ajax({
/* your options here */
}).done(function(result) {
/* do something with the result here */
callback(result); // invokes the callback function passed as parameter
});
}
And then call it:
yourFunction(function(result) {
console.log('Result: ', result);
});
Fiddle: http://jsfiddle.net/9duek/
try
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).success(function(result) {
var datareturned = result.d;
console.log('done' + datareturned);
x = datareturned;
console.log(x);
});