I am trying to echo the contents of an input field on enter. I have a text input field that I create here:
echo '<form id="changePassForm" action="" method="post" enctype="multipart/form-data">
<div class="changePass">
<div class="changePassBtn">Change Password</div>
<input class = "passwordText" type="password" placeholder="Password" name="passwordText">
</div>';
The field calls this javascript function correctly:
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
datatype: 'text',
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) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
Which references password change.php here:
<?php
session_start();
echo "Hello world";
$pass=$_POST['passwordText']; //name of input
echo $pass;
/*$dbh = new PDO("mysql:host=localhost;dbname=sqlserver", 'username', 'password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkforpass = "SELECT password FROM sqlserver.accounts WHERE username='".$username."'";*/
?>
I'm not versed in PHP but Hello world is output to console. How can I output/store value of text field in $pass?
Untested, off the cuff:
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
var pass = $('#changePassForm input').val();
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: 'passwordText=' + pass, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
Note also that it is dataType: not datatype:, and that dataType only affects returning data not data being sent to PHP
So, get it working simply first (as above), then get fancy with $('#changePassForm').serialize() etc.
Try as follows
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
var postData = $('#changePassForm').serializeArray();
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: postData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
datatype: 'text',
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) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
If you want to use FormData, you can see from the manual that the FormData object constructor takes an optional <form> element and you're using this, which refers to $(".passwordText"), which is a jQuery object. You can pass a form element by doing:
var form = document.getElementById("changePassForm");
var fd = new FormData(form);
Putting this all together we would then have:
$(document).ready(function() {
$(".passwordText").keydown(function(event){
if(event.keyCode == 13){
event.preventDefault();
var form = document.getElementById("changePassForm");
var fd = new FormData(form);
$.ajax({
url: "../php/passwordchange.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: fd, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
dataType: 'text',
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) // A function to be called if request succeeds
{
console.log(data);
}});
console.log("WORKS!!");
}
});
});
As an alternative you can manually append any values you want to have sent in the ajax request like this:
var fd = new FormData();
fd.append($(this).attr("name"), $(this).attr("value"));
Disclaimer:
With that said, the FormData interface is only available in IE >= 10, so if you are worried about cross browser compatibility you may want to consider simply using jQuery's serialize() method to send the data. As an added bonus, it's only 1 line of code.:
data: $("#changePassForm").serialize()
Related
I'm trying to submit a form with ajax with the code below, but apparently doesn't seem to work.
Any suggestion to fix this problem?
$(".dialog-set-new-message").on('keyup', '.ctxtareados', function(b){
if(b.keyCode == 8){return false;}
if(b.keyCode == 13){
//
$("#submit_new_message_cbox").submit(function(eventmsg){
$(".loader-wait-gif-con").fadeIn(500);
eventmsg.preventDefault();
$.ajax({
url: "https://www.mypage.com/success/set_new_cbox_message.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$(".dialog-new-chat-open-con").load("../success/refresh_new_cbox.php", function(){
$(".loader-wait-gif-con").fadeOut(500);
$(".con-sub-nav-chat h3").html("Messages updated.");
$(".con-sub-nav-chat").css("display", "block");
$(".con-sub-nav-chat").fadeOut(7000);
$(".all-msg-new-chat-box").animate({scrollTop: $("#sldum").offset().top}, 1000);
});
$('#submit_new_message_cbox')[0].reset();
}
});
});
//
}
});
--FIXED--
I Added a input[submit] in the php file and modified the code as follow:
PHP Code added:
<input style="visibility: hidden;" id="submitnmcbox" type="submit">
JS Code Modified (same as above):
$(".dialog-set-new-message").on('keyup', '.ctxtareados', function(b){
if(b.keyCode == 8){return false;}
if(b.keyCode == 13){
$("#submitnmcbox").click();
}
});
//Set new msg chat
$("#submit_new_message_cbox").on('submit', function(eventmsg){
$(".loader-wait-gif-con").fadeIn(500);
eventmsg.preventDefault();
$.ajax({
url: "https://www.dudoby.com/success/set_new_cbox_message.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$(".dialog-new-chat-open-con").load("../success/refresh_new_cbox.php", function(){
$(".loader-wait-gif-con").fadeOut(500);
$(".con-sub-nav-chat h3").html("Se han actualizado los mensajes.");
$(".con-sub-nav-chat").css("display", "block");
$(".con-sub-nav-chat").fadeOut(7000);
$(".all-msg-new-chat-box").animate({scrollTop: $("#sldum").offset().top}, 1000);
});
$('#submit_new_message_cbox')[0].reset();
}
});
});
//
I think you are using FormData() constructor wrongly. According to MDN, FormData() constructor accept HTML DOM form element (optional). Example:
<form name="myForm">
<input type="text" name="text_field_1" value="test1" /><br /><br />
<input type="text" name="text_field_2" value="test2" /><br /><br />
<input type="text" name="text_field_3" value="test3" /><br />
</form>
<script type="text/javascript">
var myForm = document["myForm"];
var formData = new FormData(myForm);
console.log(formData.get("text_field_2")); // returns "test2"
</script>
I would like to get a form object and submit the data to server with a button click in Asp.net MVC.
This is my HTML code:
<form method="post" form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
This is my JS code:
$(document).on("click", "[form-sync='ajax']", function() {
var formdata = new FormData($(this).closest("form")),
url = $(this).data("url");
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(response) {
alert(response.message);
return false;
},
});
});
This is my MVC code:
var data = Request["InvtId"];
The problem is the data variable is empty
Any help would be greatly appreciated, thanks.
Your form-sync attribute is non standard so your HTML is invalid. You should make that a data attribute.
You need to hook to the submit event of the form, not click.
The FormData constructor expects a DOMElement, not a jQuery object as you are currently passing to it. You can just give the this reference as that is the DOMElement.
The form has no data-url attribute. I assume you want the action property instead, which will default to the current page as you haven't provided one explicitly.
The return statement in your success handler is redundant.
You need to stop the standard form submission (as you're submitting via AJAX instead) by calling preventDefault() on the passed submit event.
Here's a complete example with all the above fixes:
<form method="post" data-form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
$(document).on('submit', '[data-form-sync="ajax"]', function(e) {
e.preventDefault();
$.ajax({
url: this.action,
type: 'post',
data: new FormData(this),
processData: false,
contentType: false,
success: function (result) {
alert(result.message);
},
});
})
The problem is that you are passing in a jQuery element and NOT a DOM element.
For the FormData to actually return what you expect, you need to pass in a DOM element to its constructor.
Here, try this instead:
var formdata = new FormData($(this).closest("form")[0]);
Another problem is that the form has no data-url attribute.
Use the action property instead, it will return the url of the current page if you have not given a url yourself.
Here, use this instead:
var url = this.action; // or $(this).prop('action');
HTML
< button type="button" class="btn btn-primary"
onclick="saveData()">Save</button>
JS Code
Inside of function saveData()
var formData = new FormData();
get values with serializeArray
var formulario = $("#miFormulario").serializeArray();
if there are extra data or files
formulario.push({ "name": fileName, "value": file });
add information to formData
formulario.forEach((d) => {
formData.append(d.name, d.value); });
ajax request
$.ajax({
timeout: 0,
url: "/InfoController/savingInfo",
method: "post",
data: formData,
contentType: false,
processData: false,
success: function (result) { //do something }
});
Controller
[HttpPost] public JsonResult savingInfo() {
if (Request.Files.Count > 0)
{ ... }
var data = Request.Form;
var valor1 = data["dato1"];
return Json(true);
}
I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/
Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.
I have this ajax request that is sent from javascript in my page
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
async: false,
success: function(data) {
alert(data);
}
});
This returns an array of items with some text and ...
Now if the user clicks on a certain button the data needs to be copied to another place on the page(div)
Is there any way I can get the data again from the file (in the network tab "chrome") without resending the request?
Put the response in global variable (dataArray) and every time check that variable has value or not. So that request will not send further time. Also, you can use that global variable (dataArray) in other methods.
var dataArray = "";
function getData(){
if(dataArray != ""){
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
//async: false,
success: function(data) {
//alert(data);
dataArray = data;
}
});
}
}