db inserting with script help. (Mvc ) - javascript

I'm a bit lost and getting real short in time.
I need to create something like this script
$(function () {
var i = 0;
$('#addButton').click(function () {
$('#form1').append
('<div class="clearfix">Ingredient Item <div id="editor2"><input style="float:left;" type="text" name="Ingredient[' + i + '].IngredientItem"/></div><div id="editor3"> Item Amount<input style="float:left;" type="text" name="Ingredient[' + i + '].ItemAmount"/></div>');
//Dif table..
('<div class="clearfix1">Instructions <div id="editor3"><input style="float:left;" type="text" name="Instructions[' + i + '].IntrusionStep"/></div><div id="editor4"> Cooking Time<input style="float:left;" type="text" name="Instructions[' + i + '].CookingTime"/></div>');
//& one more diff table here
i++;
});
});
I know this is not a good approach and far from best practice I didn’t find any example of using any better way to do it ( I'm complete novice as far as JavaScript or any scripting for this matter).

What i have understood is that you need to post your form from java-script code. You can make use of a jQuery post or an ajax post method here.
$.ajax({
url: '<%=Url.Action("Create","YourController") %>',
type: 'post',
data: $(form).serialize(),
datatype: 'json',
success: function (result) {
// Handle code for success post
},
error : function (result) {
// Error condition
}
});
Now make your controller action accordingly to return json value back to your java-script code in the view

Related

POST Form Submission in JQuery/AJAX and PHP

I'm a bit new to working with form submissions in JQuery/AJAX and PHP, so I've been trying to follow some tutorials online and have run into a few issues.
I am trying to build a form that handles submissions through PHP. Here's what I have for my index.html file.
<body>
<h1>Food Preference</h1>
<p>Please let us know what types of foods you would like to see on the menu.</p>
<form id="food-form">
<label for="appetizer">Appetizer</label>
<input type="text" id="appetizer" required>
<label for="entree">Entree</label>
<input name="entree" type="entree" id="entree" required>
<label for="dessert">Dessert</label>
<textarea name="dessert" id="dessert" required></textarea>
<button id="submit_button" type="submit">Send</button>
<p id="form_content">
</p>
</form>
And here is my index.js file
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val() +
"&entree=" + $("#entree").val() +
"&dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
And here is handler.php
<?php
class runForm {
public function handle_food_form($request) {
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
print "<p class='success'>Thank you for your opinion.</p>";
return array('post_id' => $new_post_id );
}
}
}
runForm();
?>
It doesn't seem like my submission saves anywhere, or if it does, I'm not sure how to find it. Can anyone give any pointers for anything I might be doing wrong?
I am wondering if this line in handler.php is correct, since I haven't really defined "opinion".
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"]))
You have many issues in this code snippet, and you should first check the errors that PHP shows to you and try to resolve them first.
The PHP file (handler.php)
opinion() function is not defined.
runForm() is not a function , it's a name of a class, if you want to call handle_food_form() function, then you can make it a static function and call it like this runForm::handle_food_form();
The final version of your PHP file should be something like this
<?php
class RunForm {
public static function opinion($appetizer, $entree, $dessert)
{
// do your logic here and return true or false
return true;
}
public static function handle_food_form() {
if (!isset($_POST["appetizer"])) $_POST["appetizer"] = null;
if (!isset($_POST["appeentreetizer"])) $_POST["entree"] = null;
if (!isset($_POST["dessert"])) $_POST["dessert"] = null;
if(SELF::opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
$htmlMsg = "<p class='success'>Thank you for your opinion.</p>";
/*
$con is a MySQLI object
$con->query("insert into table ........");
$new_post_id = $con->insert_id;
*/
return array('post_id' => $new_post_id, 'htmlMsg' => $htmlMsg );
} else {
return array('post_id' => null , 'htmlMsg' => "");
}
}
}
echo RunForm::handle_food_form()['htmlMsg'];
The client side
You should use encodeURIComponent() to encode the paramters of the URL to prevent something like this dessert=cheesecake&pancake from corrupting the URL, or pass an object of the parameters as the data to ajax function and jquery will do the encoding for you internally
jQuery.ajax({
url: "handler.php",
data: {
appetizer: $("#appetizer").val(),
entree: $("#entree").val(),
dessert: $("#dessert").val()
},
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
Separate the variables with commas.
In jQuery.ajax, do as like:
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val(),
"entree=" + $("#entree").val(),
"dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});

Calling same controller's method using ajax GET and POST type

Hi I am a newbie to Grails and Groovy. Please help me to solve the below issue related to calling controller's method using ajax call.
The scenario behind the code is to recover the password using the username whenever the user is unable to remember the password. I have explained the code flow in detail below.
Application begins with the below auth.gsp page:
<form action='${postUrl}' method='POST' id='loginForm' autocomplete='off'>
<input type='text' name='j_username' id='username'/>
<input type='password' name='j_password' id='password'/>
<input type='submit' id="submit" value='${message(code: "default.button.login")}'/>
<g:message code="etranscripts.forgotPassword"/>
</form>
When I click on the Forgot password link of the anchor tag, it will call the below ajax method:
<script>
$(document).ready(function () {
$('#recovery-link').click(function () {
var url = $(this).attr('recovery-url')
$.ajax({
url: url,
dataType: "html"
}).done(function (html) {
$('#loginForm').replaceWith(html)
$('#sign-in-instruct').text('<g:message code="js.resetEnterName"/>')
}).fail(function (jqXHR, textStatus) {
console.log("Request for url failed: " + url)
})
event.preventDefault()
return false
});
});
The controller method for the above call is as below.
def recoverPassword = {
println "RecoverPassword method of ctrl....."
if (!request.post) {
// show the form
render(template: "recoverPassword" )
return
}
//some other stuff based on the input conditions.
The successful output template for the above ajax call is:
<div id="recover-password" >
<ul>
<li>
<span><g:textField name="username" id="username" value="" /></span>
<input type='submit' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>
</li>
</ul>
Till here my code works perfect. But the issue begins from here.
i.e When I enter some value in the username field of the template and click on submit, it should call the below ajax method.
$(document).on('click', '#submit-username-link', function (event) {
var url = $(this).attr('recovery-url')
var username = $('input#username').val();
$.ajax({
url: url,
type: "POST",
data: {username:username},
dataType: "json"
}).done(function (responseJson) {
$('#sign-in-instruct').text(responseJson.message)
$('div.copyright').css('margin','74px 0px 0px 140px')
$('#home-link').show()
if ( responseJson.status == 'success') {
$('#recover-password').remove()
}
}).fail(function (jqXHR, textStatus) {
$('#recover-password').remove()
$('#sign-in-instruct').text(textStatus)
console.log("Failed to send the email " + textStatus)
})
event.preventDefault()
return false
});
The thing is, url refers to the same method of the controller but the only change is POST type is used and that will be taken into consideration inside the method using if conditions.(i.e some other stuff of the controller)
These GET and POST type of method calls are configured as shown below in the URLMappings.groovy file.
"/recoverPassword/recoverPassword"(controller: 'recoverPassword') {
action = [GET: "recoverPassword", POST: "recoverPassword"]
}
The whole summary of this question is, for the same method of controller, GET request is working but POST type of ajax call is not able to reach the controller's method.
Am I doing anything wrong over here? Please help me to solve this issue. Thanks in advance :-)
Overcomplicated. Why don't you use separate function in controller for GET (rendering the form) and separate function for POST (for handling the recovering the password)?
Check out also https://en.wikipedia.org/wiki/KISS_principle
Change input Type submit to button
<input type='button' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>

Why does my AJAX data load then disappear?

I am loading JSON data from a movie database API. The AJAX loads within a search function, it works fine but then disappears. Here's the code:
<div class="form-group">
<label for="movie">inserisci film:</label>
<input type="text" class="form-control" id="movie" type="text"></input>
</div>
<button type="submit" onclick="search()" class="btn btn-default">cerca</button>
Then I call the function
function search() {
var film = document.getElementById('movie').value;
var key = '?api_key=somekey';
alert(film + key);
$.ajax({
type: 'GET',
url : 'http://api.themoviedb.org/3/search/movie'+key+'&query='+film,
async: false,
data: {
format: 'json'
},
success: function(data){
$('#titolo').append(data.results[0].original_title);
$('#immagine').append('<img src=' + url + key + ata.results[0].poster_path + '></img>');
console.log(data);
},
});
};
there is something wrong? thank you
You click the submit button
The JavaScript runs
The ajax request is sent
Because async: false the entire UI locks up until the JS is done
The DOM is updated by the success function
The form submits
The browser loads a new page
If you are going to use intrinsic event attributes (which you shouldn't), then you need to return false from the function to stop the normal behaviour of the event from occurring.
onclick="search(); return false;"
Its because you submitting form
You Called search() function and then after execution form will get submitted as normal flow and redirected to new url. You have to return false when submitted.You can do something like this:
complete: function(data){
return false;
}

Using ajax to post a form to php without refresh

I have this written up for send a few variables to a php script:
$(function() {
$('a[class="removeUnread"]').click(function(){
var markedtopicid = $(this).attr("id");
var sessionvar = \'', $context['session_var'], '\';
var sessionid = \'', $context['session_id'], '\';
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
});
});
});
I think this is the correct way to send post data via ajax, but it doesn't appear to be sending. Was I right to wrap the code in the ready function?
I can tell you right off the bat you should not have a semicolon between quickmod and board in your URL. I'm answering here because i cannot post comments yet. One good tool to use in web development ESPECIALLY with GET and POST requests is googles PostMan app. Its free to use and what it does is it will show you the exact output of any link you send it. So you can try putting the link that you make via javascript into postman and see what errors it spits out.
In this example i'm pretty sure your URL is all kinds of screwed up though. Try this instead...
"index.php?action=quickmod&?board="+$context['current_board']
fyi, i did not test that link so it may not work. If it doesnt work, google some ajax examples and javascript string concatenation. You're string is not suitable for ajax.
is should be like this...
$.ajax({
url :'index.php',
type : 'POST',
data : { sessionvar: sessionid, topics:markedtopicid},
success : function (data) {
},
error : function () {
}
Try handling the error:
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});

jquery ajax calls conflict?

On my site i am loading shopping products with the "add to cart"-button dynamically with a jquery ajax call. For the shopping cart itself, I use jcart, jquery plugin.
When I then add an item to the cart, jcart calls a php-file with ajax and POST. All works fine, the products are correctly added to the cart, but the page reloads every time I add an item to the cart.
When I don't use the ajax call to load the products (e.g. load them directly in the page), all works fine, so there must be a conflict somewhere.
Any clues?
This is my products-function and the html.
...
<script>
function loadProducts(str) {
$.ajax({
type: 'GET',
async: true,
url: 'ajax/load.php',
data: {'max-id' : str},
cache: false,
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
});
}
</script>
<script>
$(document).ready(function() {
var n = '';
loadProducts(n);
});
</script>
<script src="jcart/js/jcart.js"></script>
</body>
</html>
The jcart-Plugin with its ajax-call can befound here:
http://conceptlogic.com/jcart/standalone-demo/jcart/js/jcart.js
Here are the functions from jcart.js.
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php',
cache: false,
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
error: function(x, e) {
...
}
});
...
function add(form) {
// Input values for use in Ajax post
var itemQty = form.find('[name=' + config.item.qty + ']'),
itemAdd = form.find('[name=' + config.item.add + ']');
// Add the item and refresh cart display
$.ajax({
data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
success: function(response) {
// Momentarily display tooltip over the add-to-cart button
if (itemQty.val() > 0 && tip.css('display') === 'none') {
tip.fadeIn('100').delay('400').fadeOut('100');
}
container.html(response);
$('#jcart-buttons').remove();
}
});
}
...
// Add an item to the cart
// is called from the submit-buttons within each product picture
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
The "loadProducts()" function puts this into #products container for each item:
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="SDK12345" />
<input type="hidden" name="my-item-name" value="Product Name" />
<input type="hidden" name="my-item-price" value="1.00" />
<input type="hidden" name="my-item-qty" value="1" />
<ul>
<li><img src="product-image.jpg"/></li>
<li>1.00 Dollar</li>
</ul>
<input type="submit" name="my-add-button" value="Add to cart" class="button" />
</fieldset>
</form>
I'm guessing you are calling the loadProducts() function in a binded click action on your add to cart button. If you are using an element with a default click behavior. You might want to prevent that with a 'return false;' on the last line of your binded click function.
like this:
$('a.addtocart').bind('click', function(){
//logic here (ajax)
return false;
});
After your success function there's also a comma that might get messy in IE:
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
Remove the comma
I think there's an error in your ajax call, try to work it out... i cant see the logic of your php file that adds products to your basket. but if you want to send the data of your form (quantity, itemid), serializing your form data should be enough. No need to pass extra get variables.
function add(form) {
$.ajax({
data: form.serializeArray(),
url: 'yourfile.php',
success: function(response) {
// logic
}
});
}
Ok, I found the solution.
As the forms are loaded via ajax, they were no correctly interpreted by jcart.js (though the functions all worked fine for themselves).
"bind" didn't work, but "live" fixed it:
$('.jcart').live('submit',function(e) {
add($(this));
e.preventDefault();
});

Categories

Resources