Jquery post method - javascript

I have a jquery post method that sends name , password and email to register.php
function postData()
{
thisBtn = $(this);
parent = $(this).parent();
name = parent.data('name');
password = parent.data('password');
email =parent.data('email');
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) ;
parent.next('#message').html(data);
}
The button that performs the function onclick:
<button onclick = 'postData()' class='regular' name='save'>
However nothing seems to be happening when the button is cicked

Since you call postData with no associated object, inside the function this is the same as window so none of the elements you access are the ones you expect.
Don't use intrinsic event attributes, bind your handlers using JavaScript. Since you are already using jQuery you should use the methods it provides for that.

This syntax looks mangled
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) ;
parent.next('#message').html(data);
// no {} for function, no closing ) for $post, and premature ;
Try
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) {
parent.next('#message').html(data);
});

you have 2 options ...
either pass and object in the onclick :
<button onclick='postData(this)' class='regular' name='save'>
or attach the click handler using jQuery - preferred method when using jQuery :
$('input[name="save"]').click(function() {
// your post code here
}};
there would then be no need for the onclick='postData(this)'

Send the post data like this you will get proper output
name = 'demo';
password = '123456';
email = 'demo#gmail.com';
$.post('register.php',{ 'name': name, 'password': password, 'email': email},function(html){
alert(html);
},"html");
//register.php
echo $_POST['name'];

Use jQuery to bind to the button click as well if you want things to work properly. (EDIT: also, let's use a non-deprecated element)
<input type='button' class='regular' name='save' id='btnPost' value='Post' />
Javascript:
$(document).ready(function() {
$("#btnPost").on("click", function() {
var thisBtn = $(this);
var parent = thisBtn.parent();
// Replacing this by serializing the parent form -
// not sure what parent.data is going to give without seeing the rest
// of the html
// name = parent.data('name');
// password = parent.data('password');
// email =parent.data('email');
$.post('register.php', thisBtn.closest("form").serialize(),
function(data) {
parent.next('#message').html(data);
});
});
});
});

You could try this :
$(document).ready(function(){
var $this = $('id_of_button');
$this.click(function(){
//ajax logic here
$.ajax({
type: 'POST',
url: url,
data: data,//data to send to serverside
success: success, //function to call on success
dataType: dataType//datatype eg.text,json etc.
});
});
});

Related

JavaScript Multiple Forms [duplicate]

If I have a form like this,
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>
how can I submit it without redirecting to another view by JavaScript/jQuery?
I read plenty of answers from Stack Overflow, but all of them redirect me to the view returned by the POST function.
You can achieve that by redirecting the form's action to an invisible <iframe>. It doesn't require any JavaScript or any other type of scripts.
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form action="submitscript.php" target="dummyframe">
<!-- Form body here -->
</form>
In order to achieve what you want, you need to use jQuery Ajax as below:
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: '/Car/Edit/17/',
type: 'post',
data:$('#myForm').serialize(),
success:function(){
// Whatever you want to do after the form is successfully submitted
}
});
});
Also try this one:
function SubForm(e){
e.preventDefault();
var url = $(this).closest('form').attr('action'),
data = $(this).closest('form').serialize();
$.ajax({
url: url,
type: 'post',
data: data,
success: function(){
// Whatever you want to do after the form is successfully submitted
}
});
}
Final solution
This worked flawlessly. I call this function from Html.ActionLink(...)
function SubForm (){
$.ajax({
url: '/Person/Edit/#Model.Id/',
type: 'post',
data: $('#myForm').serialize(),
success: function(){
alert("worked");
}
});
}
Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:
function formSubmit(event) {
var url = "/post/url/here";
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.onload = function() { // request successful
// we can use server response to our request now
console.log(request.responseText);
};
request.onerror = function() {
// request failed
};
request.send(new FormData(event.target)); // create FormData from form that triggered event
event.preventDefault();
}
// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
document.getElementById(formId).addEventListener("submit", formSubmit);
}
Place a hidden iFrame at the bottom of your page and target it in your form:
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>
Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.
So you really should be using Ajax to future-proof.
Okay, I'm not going to tell you a magical way of doing it because there isn't.
If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"
In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...
One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:
<form onsubmit='return false'>
<!-- ... -->
</form>
You need Ajax to make it happen. Something like this:
$(document).ready(function(){
$("#myform").on('submit', function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(name=='' || email=='' || password=='' || contact=='')
{
alert("Please fill in all fields");
}
else
{
// Ajax code to submit form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
See jQuery's post function.
I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.
Also, see the preventDefault function, of jQuery!
The desired effect can also be achieved by moving the submit button outside of the form as described here:
Prevent page reload and redirect on form submit ajax/jquery
Like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
function submitForm(form, successFn){
if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
var id = form.getAttribute("id");
} else {
console.log("Form id attribute was not set; the form cannot be serialized");
}
$.ajax({
type: form.method,
url: form.action,
data: $(id).serializeArray(),
dataType: "json",
success: successFn,
//error: errorFn(data)
});
}
And then just do:
var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
console.log("Form submitted");
});
Fire and forget vanilla js + svelte
function handleSubmit(e) {
const request = new Request(`/products/${item.ItemCode}?_method=PUT`, {
method: 'POST',
body: new FormData(e.target),
});
fetch(request)
}
Used in Svelte:
<form method="post" on:submit|preventDefault={handleSubmit}>
If you control the back end, then use something like response.redirect instead of response.send.
You can create custom HTML pages for this or just redirect to something you already have.
In Express.js:
const handler = (req, res) => {
const { body } = req
handleResponse(body)
.then(data => {
console.log(data)
res.redirect('https://yoursite.com/ok.html')
})
.catch(err => {
console.log(err)
res.redirect('https://yoursite.com/err.html')
})
}
...
app.post('/endpoint', handler)

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

submitting form with parameter from a link in jquery

I am trying to save data in database in background through a link, and to give download functionality to that link in front end. but it gives an error.
my script is -
<script>
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(me);
});
function saveData(me){
$.ajax({
type: "POST",
url: "download_counter.php",
data: { client_id: "<? echo $client_id;?>", candidate_id: me }
});
}
});
</script>
this is the link (It looks fine)
<button name="download"></button>
download_counter.php looks like -
<?
if (isset($_POST['candidate_id'])) { // Form has been submitted.
$candidate_id = $_POST['candidate_id'];
$client_id= $_POST['client_id'];
$date = date("Y-m-d");
echo "client - ".$client_id;
echo "candidate - ".$candidate_id;
$query = "INSERT INTO `downloads`(`client_id`, `candidate_id`, `download_date`) VALUES ('".$client_id."', '".$candidate_id."', '".$date."')";
$result = mysql_query($query);
}
?>
when i click the link, it lets download the file but database do not updates.
Please help.
There is an error with passing parameter to function saveData, so your ajax request not occur:
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(data); // was me
});
Check jquery click event handler, which says
// say your selector and click handler is somewhat as in the example
$("some selector").click({param1: "Hello", param2: "World"}, some_function);
// then in the called function, grab the event object and use the parameters like this--
function some_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
database is updating now, but it is not getting value of candidate_id.
i did this -
<script>
$(document).ready(function(){
$("#download").click(function(){
$("#count").hide();
var me = $(this), data = me.data('params');
saveData(data); // was me
});
function saveData(data){
$.ajax({
type: "POST",
url: "counter.php",
data: { client_id: "2", candidate_id: data.ca_id }
});
}
});
</script>
I think on click the data you are reading is a string and in the given format.
And you are passing that as data, but since it is not an valid id,
that value in the database is not updated.
Check this out

JQuery Ajax Type error in success callback

I create a button that when clickes do something with Ajax in server and when come back from server color of the button and its text will change (something like +1 add friend in facebook) here is my code in .js:
$(".blue").on("click", function(){
var firstName = $(this).prev().prev().text();
var lastName = $(this).prev().text();
$(this).text("Add Friend...");
var data={
firstName: firstName,
lastName: lastName
};
$.ajax({
url: '/ajax/friendRequest',
data: data,
dataType: 'json',
success:function(){
alert(123);
$(this).removeClass("glass blue");
$(this).addClass("greenStatic");
$(this).text("Request sent");
}
});
});
every thing is OK and request will successfully change the database but when it comeback to the success callback I only see the alert(123); on the browser and 3 below lines don't run and my chrome developer tools throw exception of typeError I search SO and change $ sign to jQuery but still I have same problem
In your success callback $(this) doesn't refer to the button, cache it outside of the success callback, like
$(".blue").on("click", function(){
var btn = $(this);
...
....
success:function(){
...
btn.addClass("greenStatic");
...
}
});
$(this).removeClass("glass blue");
$(this).addClass("greenStatic");
$(this).text("Request sent");
Here this does not refer to the control, rather it refers to the Ajax request object. So, replace this by the control id. It should work.
Something like below...
$("#controlId").removeClass("glass blue");
$("#controlId").addClass("greenStatic");
$("#controlId").text("Request sent");

Categories

Resources