I asked yesterday a similar question and i resolved the answer myself in which i wanted to add data into the database using ajax to avoid refreshing the page.
Now, i wish to do the same thing, but update the data in the database.
Im not sure if the issue is caused by having 2 ajax script requests on the same page..
I am trying to submit this form:
I should probably tell you, this form is in a modal screen
<form id="editarticleform" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="blog-id" name="blog-id" value="<?php echo $list['id']; ?>">
</div>
<div class="form-group">
<label for="blog-title">Article title</label>
<input type="text" class="form-control" id="blog-title" name="blog-title" placeholder="Blog title" value="<?php echo $list['blog_title']; ?>" required>
</div>
<div class="form-group">
<label for="blog-content">Article content</label>
<textarea class="form-control" id="blog-content" name="blog-content" placeholder="Blog content" required><?php echo $list['blog_body']; ?></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Article image</label>
<input type="file" class="form-control-file" id="article-image" name="article-image" aria-describedby="fileHelp" value="<?php echo $list['blog_image']; ?>">
<small id="fileHelp" class="form-text text-muted">This is the image that will appear along side the article.</small>
</div>
<fieldset class="form-group">
<legend>Active</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="active-inactive" id="optionsRadios1" value="1" checked>
Article is active - Will be shown in the blog.
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="active-inactive" id="optionsRadios2" value="0">
Article is inactive - Will not show.
</label>
</div>
</fieldset>
<fieldset class="form-group">
<legend>Comments</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="enable-comments" id="enable-comments1" value="1" checked>
Enable comments - Users can post comments
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="enable-comments" id="enable-comments2" value="0" aria-describedby="disableComments">
Disable comments - Users cannot post comments
<small id="disableComments" class="form-text text-muted">If you disable comments for users, administrators will still be able to post comments.</small>
</label>
</div>
</fieldset>
<button type="submit" id="edit_article" name="edit_article" class="btn btn-primary">Save</button>
</form>
Updating the database using this script:
<?php
require_once("../../includes/database.class.php");
session_start();
$uid = $_SESSION['uid'];
$id = $_POST['blog-id'];
$title = $_POST['blog-title'];
$content = $_POST['blog-content'];
$image = $_POST['article-image'];
$active = $_POST['active-inactive'];
$comments = $_POST['enable-comments'];
$sql = "UPDATE blog_article SET blog_title = '$title', blog_body = '$content', blog_image = '$image', active = '$active', comments = '$comments' WHERE id = '$id'";
// print_r($sql);
$result = $database->query($sql);
if ($result) {
echo "Article updated.";
}else {
echo "Query failed" . print_r($sql);
}
?>
Via AJAX to avoid refreshing the page:
<script>
var submit = $('#edit_article');
submit.click(function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success:function(html){
update_div.html(html);
}
});
});
</script>
As with the last question, the script works perfectly fine if i directly set the form action to the editarticle.php script. When i implement the ajax script, it doesn't update the database.
I am unsure if its got something to do with the blog-id, but thats what my head immediately thinks it is.. Or it may be that i am being blind and its a tiny little issue..
I suspect that the click event isn't triggered. Perhaps try something like this:
<script>
// Wait for document ready
$(function(){
$(document).on('click', '#edit_article', function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success: function(html){
update_div.html(html);
}
});
});
});
</script>
Check the Network tab of your browser's developer tools to see that anything gets sent to the backend, and the request headers to see if all the necessary data is included.
I would do the following to debug;
Check what you are sending to the php file, to see if blog-id value is not empty. by doing var data = $("#editarticleform").serialize();
console.log(data);
Change your ajax url to url: 'editarticle.php' ,because it seems your ajax probably doesn't see the php file.
if you use modal bootstrap try this :
$('#myModal').on('shown.bs.modal', function () {
var submit = $('#edit_article');
submit.click(function () {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success: function (html) {
update_div.html(html);
}
});
});
})
check this
<script>
// Wait for document ready
$(document).ready(function(){
$("#edit_article").click(function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
url: 'editarticle.php',
type: 'post',
data: data,
success: function(html){
update_div.html(html);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
});
</script>
If still doesn't work try to send raw data with ajax and check if it works
data: "blog-id="+blog-id
Related
i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});
I want to call input value from javascript
My home page code :
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
....
javascript code :
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("form").serialize(),
success : function(data){
alert(data);
}
})
})
...calling page code :
<?php
include "db.php";
$fname = $_POST["f_name"];
$lname = $_POST["l_name"];
...
echo $fname;
...error while click button, only last name (input) value defined
<br />
<b>Notice</b>: Undefined index: f_name in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>7</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>8</b><br />
please someone help me?
I stuck like more than 4 hours on this. Im learning javascript n php, n still newbie. Please help. thanks.
You are missing a # You also have an error in your first input field.
<input name="f_name ">
shouldbe
<input name="f_name">
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
})
})
try this code
$(document).on('click', '#singup_btn', function() {
$.ajax({
url : "register.php",
type : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
});
});
Please remove type="submit" from submit button and add type="button". It will work!
Serializing the form with a space in name="f_name "id="f_name" forces a + to be appended to the serialized value. This is why its not being picked up correctly server side.
Expected server side value
f_name=asd&l_name=asd
Actual server side value
f_name+=asd&l_name=asd
see test below
$("button").click(function()
{
//output values before serialization
console.log( "Result of f_name");
console.log ($("#f_name").val() );
console.log( "Result of l_name");
console.log ($("#l_name").val() );
//output values after serialization
var serialized = $("form").serialize();
console.log( "Result: Notice how f_name has an appended + in its key");
console.log( "'" + serialized + "'");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
<button type="button"> test </button>
</form>
Credit to Chris
My code here works fine except image uploading. It inserts all data in database .
<input type="file" name="image2" class="file" id="imgInp"/>
But after adding file type input in php it is showing
Notice: Undefined index: image2 in C:\xampp\htdocs\upload\submit.php on line 18
How can I add image uploading function in my existing code.
<div id="form-content">
<form method="post" id="reg-form" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
</div>
// here is the problem
<input type="file" name="image2" class="file" id="imgInp"/>
//here is the problem
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...'); });
});
</script>
submit.php
<?php
$con = mysqli_connect("localhost","root","","table" ) or die
( "unable to connect to internet");
include ("connect.php");
include ("functions.php");
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
$post_image2 = $_FILES['image2']['name']; // this line shows error
$image_tmp2 = $_FILES['image2']['tmp_name'];
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments
(firstname,lastname,email,number,post_image) values('$fname','$lname','$email','$phno','$post_image2' ) ";
$run = mysqli_query($con,$insert);
?>
You can use FormData, also I suggest you can change the elements id of the form, now all of them have ('lname') Try this with your current:
In yout HTML, put an ID to your file input
<input type="file" name="image2" id="name="image2"" class="file" id="imgInp"/>
And change the id of the other input.
In your JavaScript:
var frmData = new FormData();
//for the input
frmData.append('image2', $('#image2')[0].files[0]);
//for all other input
$('#reg-form :input').each(function(){
if($(this).attr('id')!='image2' ){
frmData.append($(this).attr('name'), $(this).val() );
}
});
$.ajax( {
url: 'URLTOPOST',
type: 'POST',
data: frmData,
processData: false,
contentType: false
}).done(function( result ) {
//When done, maybe show success dialog from JSON
}).fail(function( result ) {
//When fail, maybe show an error dialog
}).always(function( result ) {
//always execute, for example hide loading screen
});
In your PHP code you can access the image with $_FILE and the input with $_POST
FormData() works on the modern browsers.If you want for older browser support use malsup/form plugin
Your Form
<form method="post" action="action.php" id="reg-form" enctype="multipart/form-data" autocomplete="off">
Javscript
<script type="text/javascript">
var frm = $('#reg-form');
frm.submit(function (ev) {
var ajaxData = new FormData(frm);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: ajaxData,
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
In php extract($_POST) to get all input data and $_FILE for files
I have a form in modal bootstrap. In codeigniter form, i left the form_open is blank, because I want the page is still not move to another page. The code is like this :
<div class="modal-body">
<?php
$properties = array('class' => 'form-horizontal', 'id' => 'myform', 'name' => 'myform');
echo form_open("", $properties);
?>
<fieldset>
<div class="control-group">
<label class="control-label">Jenis Request :</label>
<div class="controls" id="chekboxes">
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Login" value="Login" /> Login </label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Printer" value="Printer"/> Printer </label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Monitor" value="Monitor"/> Monitor</label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Computer" value="Computer"/> Computer</label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Network" value="Network"/> Network</label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Other" value="Lain-lain" /> Other</label>
</div>
</div>
<div class="control-group hidden-phone">
<label class="control-label" for="Keluhan" >Description: </label>
<div class="controls">
<textarea class="cleditor" name="keluhan" id="keluhan" rows="3" autofocus="autofocus"></textarea>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit">Kirim</button>
<button type="reset" class="btn" id="reset">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
</div>
See, I use jquery to insert a new data on my database like this :
$(document).on('submit', '#myform', function() {
$('#myform').block({
message: '<h2>Sedang mencari</h2>',
css: {border: '3px solid #a00'}
});
var request = $("input[name='request[]']:checked");
var keluhan = $("#keluhan").val();
$.ajax({
url: '<?php echo base_url() . 'direksi/control_direksi/mdRequest' ?>',
type: 'POST',
data: {request: request,
keluhan: keluhan},
dataType: 'json',
success: function(data) {
alert("Insert Success");
$("myModal").hide();
}
});
return false;
});
And this is the php action
public function mdRequest() {
var_dump($_POST);
}
My page just refreshed without affected. How to check if the POST was success ?
And how to passed multiple checkbox using jquery, am I wrong like on my code above ? Any help it so appreciated.
You can pass all the values by using array variable. Store checked element inside array variable like so :
var request = $("input[name='request[]']:checked").map(function(i,e) {
return $(this).val();
}).get();
To check POST request success or not, you can check via network tab for chrome browser, and see the ajax request success or not. Second, display output by using console.log(). This will print out the output of var_dump. :
success: function(data) {
console.log(data);
$("myModal").hide();
}
In server side, you can use this function as well :
public function mdRequest() {
print_r($this->input->post());
// or print_r($this->input->post('request'));
}
I'm trying to POST some JSON data to a local host and I keep getting a 404 Not Found error which is strange because the php file is located in the correct location as specified in the script. I would appreciate any feedback from anyone who has experience with this. Am I getting this error because the the server can not locate the ajax.php file for some unknown reason?
<div class="container">
<div class="header">
<h3 class="text-muted">AJAX JSON Data</h3>
</div>
<div id="data-div">
<form method="post" action="api/ajax.php" class="ajax">
<p><label for="firstname" class="contact-input-text">First Name</label> <br/>
<input id="first-name" name="firstname" type="text" maxlength="30" autofocus /></p><p><label for="lastName" class="contact-input-text">Last Name</label> <br/>
<input id="last-name" name="lastname" type="text" maxlength="30" autofocus /></p>
<p><input type="submit" id="submit-button" class="contact-input-text" value="submit" /></p>
</form>
</div>
</div>
<script>
$('form.ajax').on('submit', function(){
var jsondata = {};
$(this).find('[name]').each(function(i, data){
console.log(data);
var that = $(this);
var key = that.attr('name');
var value = that.val();
jsondata[key] = value;
});
console.log(jsondata);
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType: 'json',
data: jsondata,
success: function(response){
console.log(response);
},
error: function(xhr){
console.log(xhr);
}
});
return false;
</script>
Here is the ajax.php file....
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$json_string = json_encode($_POST,JSON_PRETTY_PRINT);
file_put_contents($file,$json_string,FILE_APPEND);
}
?>
This is the directory structure :
index.html (contains the form input fields and the ajax request)
ajax.php
/styles
/images
have you ensure with correct url in ajax?
maybe not thi:
url: 'ajax.php'
but this:
url: 'api/ajax.php'