jQuery ajax POST request for log in - javascript

I am trying to write a .ajax request through a form to log in. When I submit my form, nothing happens with either the success or error functions. I notice that if I put an alert box after the .ajax call it does not work either. I would expect, that if I am just incorrectly putting the data, I would at least expect the error alert box to show up? Here is my code:
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
e.preventDefault();
});
});

I noticed you're already using JQuery. So perhaps use the built in post function. Example below:
Also side note: You've got a slight type in your variable: data: $(this).serialize() + "&client_type=" + clienttype, clienttype was declared with a capital T: clientType
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
e.preventDefault();
$.post("myurl",{data:$(this).serialize(),client_type:clientType},function(data){
console.log("Date returned from request:",data);
// Returns JSON Data. So data.clientType.
},'json');
});
});

If you add in a trigger to cancel the page from being submitted, it should work (return false;), take a look below.
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
return false;
});
});

Related

Cant print validation errors values into view with jquery

So I'm trying to show validation errors after jquery ajax call, but for some reason instead of printing the actual messagge I'm getting either +value+ or +data.success+, am I appending the values wrong?
This is my code:
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').append('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(key , value){
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">+ value +</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Yes you are appending the values incorrectly as shown by the syntax coloring: the whole text is in dark red.
Your String is starting with a single quote ' so you need to end the string with ' too before your + value + :
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
Answer given by #pyb and original code will almost always work. However, I can see that the DIV will keep appending the errors even though the form has been reset or triggered multiple times.
Below is the code which I prefer:
NOTE: I have used html function in the success block container which will NOT append the success message always.
NOTE: I have cleared the form_error_container using html function before printing the error messages, so that it will not keep appending the error messages even though the form is reset or triggered multiple times.
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').html('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$('.form_error_container').html("");
$.each(errors , function(key, value) {
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
});
}
});
Thanks.

jquery window.location.assign() not working

I'm sending form data via jquery and cannot get the window.location.assign() to fire off. I am getting a successful submission. I've also tried window.location.href =
<form>
<div>
<a id="submitDesk" type="button" class="btn submitDesk">Submit Request</a>
</div>
</form>
$( document ).ready(function() {
$( "#submitDesk" ).click(function() {
var firstname = document.querySelector('#firstname').value;
var lastname = document.querySelector('#lastname').value;
var email = document.querySelector('#email').value;
$.ajax({
type: "POST",
url: "http://foo.com/desk.php",
dataType: 'json',
data: 'firstname='+ firstname + '&lastname='+ lastname+ '&email=' + email + '&location='+ location,
success: function(data) {
console.log(data);
window.location.assign('/thank-you/');
}
});
});
});
Kindly use below. data parameter string was not proper, String was getting break, SO i have added " ' " to make it a proper string.
$.ajax({
type: "POST",
url: "http://foo.com/desk.php",
dataType: 'json',
data: 'firstname='+ firstname + '&lastname='+ lastname+ '&email='+ email+ '&location='+ location,
success: function(data) {
console.log(data);
window.location.assign('http://foo.com/thank-you/');
}
});
The backend file was sending incorrect responses causing there to always be an error even though the form was a success.

Form submit Ajax using jQuery sometimes does not works

I am doing form data submit using Ajax with jQuery.
When I submit form on popup window, I refresh the parent page.
My code:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webapp/addSpeedDataAction.do",
data: $(this).serialize(),
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
However page gets refreshed on success of callback but i can not see update on my parent page. Sometimes I can see updates and sometimes not. What is the issue? I also need to know how I can write it in native javascript and submit form using ajax javascript.
Maybe your getting this error due the fact that javascript is async and your code will proceed even when you have yet no response from the request.
Try this:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webfdms/addSpeedDataAction.do",
data: $(this).serialize(),
async: false, // This will only proceed after getting the response from the ajax request.
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});

JavaScript AJAX passing mutltiple variables confusion

Hi all I have a AJAX query which I am calling using an onclick function as seen below, the query successfully POSTs the data from the form I have on my page - and I can use the data on my php script without an issue:
function tempFunction(obj){
var no= $(obj).attr('id');
$.ajax({
type: "POST",
url: "/tempproject/main/changepage",
data: $('form').serialize(),
success: function(msg){
alert( "success: " + msg ); //Anything you want
}
});
window.alert(no);
}
However I wish to also send the variable no along with the form data, I am a complete newbie when it comes to JS so could someone point me in the right direction of how to send the variable along with the serialized form data? can I append the serial data somehow? I feel this is probably really easy but I'm to new to JS
try this
function tempFunction(obj) {
var data = $('form').serializeArray();
data.push(
{
no: $(obj).attr('id')
}
);
$.ajax({
type: "POST",
url: "/tempproject/main/changepage",
data: data,
success: function (msg) {
alert("success: " + msg); //Anything you want
}
});
window.alert(no);
}
You may try to use jQuery Form plugin.
It allows ajax submitting form transparently, without worrying about serizalization.
Plugin: http://malsup.com/jquery/form/
Your code:
$('#form').ajaxSubmit({
data: { no: $(obj).attr('id') },
url: "/tempproject/main/changepage",
success: function(msg){
alert( "success: " + msg ); //Anything you want
}
});

How to connect to the Parse Javascript API? (502 error)

I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});

Categories