Issue with preventDefault. Submitting form - javascript

I have created this jQuery AJAX script for submitting a form:
$(document).ready(function() {
// process the form
$('#reviewForm').submit(function(e) {
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
Sadly the form submits though the normal way and not though the AJAX. Im at a loss to what the issue can be. I have tried the return false and such but that didn't work at all.

I think you are missing e.preventDefault(); at the begining of the submit(); and to use e.
$(document).ready(function(e) {
// process the form
$('#reviewForm').submit(function(e) {
e.preventDefault();
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
});
});
Hope this Helps.

$(document).ready(function() {
// process the form
$('#reviewForm').click(function(e) {
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
Use 'Click' event instead of 'Submit' will work definatly

Related

how to consolelog all the the parsed data in json

$.ajax(
{ type : "POST"
, url : "my url link"
, data : fd
, dataType : 'json'
, contentType : false // The content type used when sending data to the server.
, cache : false // To unable request pages to be cached
, processData : false // To send DOMDocument or non processed data file it is set to false
, success: function(data, textStatus, jqXHR)
{
reset_info(true);
msg = "<strong>SUCCESS: </strong>";
if (!(data.sa === null))
{
//add and update case forceDelete=> !(data.notice===null)
msg = "<strong>Submitted Successfully</strong><br/>Your Application ID is: " + data.sa;
}
$("#name").val('');
}
How to console log all the data that i sent through this form?
multiple user fill this form and submit. and get a registration id.

Trying to submit form action via ajax, getting undefined

I have the following code which is returning a undefined value for the .prop('action')
I am not quite sure why
Any thoughts?
$(function() {
$('#generalContactForm').submit(function(event) {
var formEl = this;
var submitButton = $('input[type=submit]', formEl);
var formData = {
'firstName' : $('input[name=firstName]').val(),
'lastName' : $('input[name=lastName]').val(),
'phoneNumber' : $('input[name=phoneNumber]').val(),
'email' : $('input[name=email]').val(),
'numberofGuests': $('input[name=numberofGuests]').val(),
'eventType': $('input[name=eventType]').val(),
'alcohol': $('input[name=alcohol]').val(),
'contactTime': $('input[name=contactTime]').val(),
'eventDate': $('input[name=eventDate]').val(),
'contactTextarea': $('input[name=contactTextarea]').val(),
};
$.ajax({
type : 'POST',
url : formEl.prop('action'),
data : formData,
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
});
event.preventDefault();
});
});
You should call the function on a jquery object
$(formEl).prop('action')

How to get return value from php to ajax

-- Ajax Code
var User = function(){
return {
init : function(){
document.getElementById('login').addEventListener('click', this.login);
},
login : function(){
var username = $("#username").val(),
password = $("#password").val();
$.ajax({
url : 'http://localhost/oc2/user_info/login',
method : 'post',
dataType : 'json',
data : {
username : username,
password : password
},
success : function(response){
alert('h'); <-- add the php return value id here.
window.location.href = "main.html";
},
error : function(response){
alert(response.responseText);
}
});
}
};
}();
-- PHP CodeIgniter
public function login()
{
$post = $this->input->post();
$where = array(
'email_address' => $post['username'], //"turbobpo.johnrey#gmail.com",
'password' => md5($post['password']) //"e10adc3949ba59abbe56e057f20f883e"
);
$user_info = $this->get_by($where);
if(isset($user_info['id']))
{
$this->session->set_userdata('user_info', $user_info);
$response = array(
'id' => $user_info['id'], <-- this i want to pass to my ajax
'success' => TRUE
);
}
else
{
$response = array(
'success' => FALSE
);
}
print json_encode($response);
}
Hello can you help me for this part i already management to went far on this php ajax i'm not used in creating this application please i need help i place a comment on the codes to see where i wanna retrieve the value from php to my ajax code so i can use it on my next retrieving of file where i use the id of a login user to get his available access in a grid form. it would be a plus if you can also show me how can i use that data to pass it back in php again the id after retrieving it on the success ajax return array value.
var User = function(){
return {
init : function(){
document.getElementById('login').addEventListener('click', this.login);
},
login : function(){
var username = $("#username").val(),
password = $("#password").val();
$.ajax({
url : 'http://localhost/oc2/user_info/login',
method : 'post',
dataType : 'json',
data : {
username : username,
password : password
},
success : function(response){
response.id; // Here is the id JQuery parses JSON for you
window.location.href = "main.html";
},
error : function(response){
alert(response.responseText);
}
});
}
};
}();

How can I set this value using ajax

I was wondering what was the correct way to do this ajax function using javascript. Here is the code:
$.ajax({
'url' : '',
'type' : 'POST',
'data' : last_time,
'data' : "last_time=yes",
'beforeSend' : function () {
},
How can I set 2 data values?
PHP:
if(isset($_POST['last_time'])){
jQuery's $.ajax method expects either
a querystring last_time=yes
or a JSON object {last_time: "yes"}
Not both. Like so...
Query string:
var dataString = "last_time=yes&date=4162014&action=last_time";
$.ajax({
'url' : 'localhost/actions/last_time.php',
'type' : 'POST',
'data' : dataString,
'beforeSend' : function () {
},
or
JSON:
var data = {
action: "last_time",
last_time: "yes",
date: "4162014"
};
$.ajax({
'url' : 'localhost/actions/last_time.php',
'type' : 'POST',
'data' : data,
'beforeSend' : function () {
},
With a simple php backend
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['action']}) {
case 'last_value':
$return_array = array(
"status" => "great!",
"message" => "Hey there!"
);
die(json_encode($return_array));
break;
default:
$return_array = array(
"status" => "default"
);
die(json_encode($return_array));
break;
}
} else {
die("access denied");
}
You could only have one property with name data (object keys must be unique, you could think javascript object as a hash map struct).
It should be a query string like 'foo=yes&bar=no' or an object {foo: 'yes', bar: 'no'}.

MVC - Pass value to controller via JS

I have a drop down
<%=Html.DropDownList("genre", Model.genres, "", new { #onchange = ChangeMovie()" })%>
The JavaScript looks like (incomplete)
function ChangeMovie() {
var genreSelection = container.find( '#genre' ).val();
$.ajax({
"url" : "/Movies/GetGenre" ,
"type" : "get" ,
"dataType" : "json" ,
"data" : { "selectedValue" : $( "#genre").val() },
"success" : function (data) {}
});
};
Conrtroller code
public ActionResult GetGenre(string genreName)
{
//Need to get the `genreName` from the JavaScript function above.. which is
// in turn coming from the selected value of the drop down in the beginning.
}
I want to pass the selected value of the drop down to the action result in the controller code via the js function. I need help manipulating the JavaScript code and the AJAX call code so the correct value is passed onto the controller.
You have a lot of unnecessary quotes as well not returning JSON in your action
$.ajax({
url: "/Movies/GetGenre/",
dataType: "json",
cache: false,
type: 'GET',
data: {genreName: $("#genre").val() },
success: function (result) {
if(result.Success) {
alert(result.Genre);
}
}
});
Plus your controller isn't returning Json, modify your action to this
public JsonResult GetGenre(string genreName) {
// do what you need to with genreName here
return Json(new { Success = true, Genre = genreName }, JsonRequestBehavior.AllowGet);
}
For model binding to function correctly, field names of passed json object should match parameter names of your controller action. So, this should work
"data" : { "genreName" : $( "#genre").val() },
The parameter name of the value you're posting in the Ajax request does not match the Action parameter name. selectedValue should be genreName.
Change this:
"data" : { "selectedValue" : $( "#genre").val() },
to this:
data : { genreName : $("#genre").val() },

Categories