I don't know how to write a proper question. But please let me explain this. I sent from with ajax and return with json. Each json value contain its status. So I need to test/evaluate the status and do something with it.
JSON
{url:"error",email:"ok",name:"ok"}
JS
//new port
$('#pflBtn').on('click',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'inc/wcont8_port_db.php',
data :$(this).closest('form').serialize(),
dataType: 'json',
success: function(data){
if(data.url=="err"){//if url=error
$('#plf_url').addClass('error');//will add .error into #plf_url class
}else{
$('#plf_url').addClass('success');
}
}
})//ajax
})
html
<form class="pflForm">
<div class="form-group form-float">
<div class="form-line" id="pfl_url">
<input type="text" class="form-control" name="pfl_url" value="URL" required />
<label class="form-label">URL (www.domain.com)</label>
</div>
</div><!-- form-group form-float -->
<button type="submit" id="pflBtn">Save</button>
</form>
There are two mistakes you have made, check my comments with the code and try again by changing them:
$('#pflBtn').on('click',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'inc/wcont8_port_db.php',
data :$(this).closest('form').serialize(),
dataType: 'json',
success: function(data){
if(data.url=="error"){// url has value 'error', but this was checking 'err'
$('#plf_url').addClass('error');//will add .error into #plf_url class but the class is not available in your html,
}else{
$('#plf_url').addClass('success');
}
}
})//ajax
})
Related
I am following a link to allow a person to reset a password, however, everything that I have done so far isn't working and I can't figure out why as I am following the tutorial closely. I am using javascript and html so far, but there are no errors in the console so i am unsure what is wrong.
HTML
<div class="container-forgotPassword">
<div class ="row justify-content-center">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<img id="logologin" src="../img/logo1.png" alt="logo"/>
<input class="formPassword" id="email" placeholder="Please enter your Email Address">
<input type="button" class="btn-forgotPassword" value="Reset Password">
</div>
</div>
</div>
</div><!-- /container -->
jQuery
var email = $("#email");
$(document).ready(function () {
$('.btn-forgotPassword').on('click', function () {
if (email.val() != "") {
email.css('border', '1px solid green');
$.ajax({
url: 'php/forgotPassword.php',
method: 'POST',
dataType: 'text',
data: {
email: email.val()
}, success: function (response) {
console.log(response);
}
});
} else
email.css('border', '1px solid red');
});
});
In the tutorial so far he has gotten the input box to turn green/ red and when he enters text into the input field and then clicks the button it will create a response in the console log. But as I said mine is doing nothing, does anyone know how I can fix this? Not sure what I am doing wrong
you need error callback in ajax to show you the error
you miss write. there is no parameter named method in jquery ajax. this should be type
.
$.ajax({
url: 'php/forgotPassword.php',
type: 'POST', //not method
dataType: 'text',
data: {
email: email.val()
}, success: function (response) {
console.log('success');
console.log(response);
}, error: function(response){
console.log('error');
console.log(response); //get all error response
console.log(response.responseText);//get error responseText
}
});
Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!
Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']
Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input
Hello everyone I want to parse array to Codeigniter controller but my code is not working can you please tell me where is a mistake in this code. I am a new in jQuery I know it is a very basic mistake.
jQuery Code:
$("#add_state").click(function(){
var addstate = {
State: $.trim($('#statename').val()
}
$.ajax({
type: "POST",
url: "<?php echo base_url()?>/index.php/geo/add_state",
data: addstate,
success: function(response){
alert(response);
}
});
event.preventDefault();
});
HTML Code:
<form role="form">
<div class="form-group">
<label for="exampleInputEmail1">State Name</label>
<input type="text" name="State" class="form-control" id="statename" placeholder="Enter State Name">
</div>
<button type="submit" class="btn btn-info" id="add_state">Submit</button>
</form>
trim is not closed properly
it suppose to be like this
$("#add_state").click(function(){
var addstate = {
State: $.trim($('#statename').val())
}
$.ajax({
type: "POST",
url: "<?php echo base_url()?>/index.php/geo/add_state",
data: addstate,
success: function(response){
alert(response);
}
});
event.preventDefault();
});
Missing ) in State: $.trim($('#statename').val(). Change it to State: $.trim($('#statename').val()).
Use $(document).on('click', '#add_state', function() { instead$("#add_state").click(function(){. Because first solution will work, if you add script before dom element was created.
Check url, maybe it's incorrect.
I plan to POST my text content to http://language.cs.usm.my/synthesis/read.php form's textarea which is third party web page, below is the form that i get from the URL.
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100">Malaysia ialah sebuah negara raja berperlembagaan persekutuan di Asia Tenggara yang terdiri daripada 13 negeri dan tiga wilayah persekutuan. Ia menduduki bumi berkeluasan 329,847 kilometer persegi.</textarea>
<input type="submit" value="OK" name="submit" />
</form>
The method i use to post data as below:
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:"Nama saya ialah Ali"
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
How can i replace the content in the existing textarea with my data?
Thanks
you have to add ng-model on the input or textarea
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100" ng-model="yourtextarea"></textarea>
<input type="submit" value="OK" name="submit" />
</form>
and in the controller get him with $scope.yourVarName
$scope.yourtextarea ;
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:$scope.yourtextarea
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
You need to use ng-model
<textarea name="malayText" rows="4" cols="100" ng-model="malayText">
and then you can readily access it in your controller
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test: $scope.malayText
}
I used ajax method to solve this problem with auto submit the form when i perform the POST action. Below is my code and solution:
$.ajax({
type: 'POST',
url: 'your url',
data: {'submit': 'submit', 'malayText' : "data that wish to POST"}, // you can use as much as data you want to send,
dataType: 'JSON' // so you can use the json_encode php function
});
I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.