Ajax to php - javascript events not firing - php

I'm sure this will be easy for you guys but I'm struggling with this one. Just trying to do a simple ajax post request to a php file here.
I can see that the ajax request is working because I get valid data back from my php script (I verified this by echoing the result to the page). However, my ajax callbacks are not firing. See below:
Javascript:
var request;
$(document).ready(function() {
$('#loginform').submit(function(e) {
if (request)
request.abort();
var $form = $(this);
var $inputs = $form.find("input, select, button");
$inputs.prop("disabled", true);
var serializedData = $form.serialize();
request = $.ajax({
url: "/login.php",
type: "post",
data: serializedData,
timeout: 10000,
success: function() {
alert("success");
// $("#result").html('Submitted successfully');
},
error: function() {
alert("failure");
// $("#result").html('There is error while submit');
}
});
});
PHP
<?php echo 'foo'; exit(); ?>
I almost feel stupid asking this considering the number of examples there are, but I cannot get this to work for the life of me. Suggestions?
EDIT
Included html (Most of the css classes are from bootstrap btw)
<div style='background-color: #193048; width: 100%; height: 500px; background-repeat: no-repeat; background-position: center center; background-size: cover;'>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title whiteFont">Sign in to continue</h1>
<div class="account-wall">
<div align='center'>
<img class="profile-img" align='center' src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
alt="">
</div>
<form id="loginform" class="form-signin" method="post" >
<input type="text" name='emailTxt' class="form-control" placeholder="Email" required autofocus>
<input type="password" name="passTxt" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="login" id="loginBtn" >
Sign in</button>
<label class="checkbox pull-left">
<input type="checkbox" value="remember-me" >
<label class="whiteFont">Remember me</label>
</label>
<label class="whiteFont">Need Help?</label><span class="clearfix"></span>
</form>
</div>
</div>
</div>
</div>

.submit is most likely causing a postback, canceling out your JS. Add preventDefault to the beginning of your function:
e.preventDefault();

You need to pass the data returned from the server as an argument to your callback
var request;
$(document).ready(function() {
$('#loginform').submit(function(e) {
if (request)
request.abort();
var $inputs = $form.find("input, select, button");
$inputs.prop("disabled", true);
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/login.php",
type: "post",
data: serializedData,
timeout: 10000,
success: function(data, status, xhr) { // <---- changes made here
alert("success");
// $("#result").html('Submitted successfully');
},
error: function() {
alert("failure");
// $("#result").html('There is error while submit');
}
});
});

Related

Ajax jquery(post) doesn't pass data to php [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}

Send Image file with Google reCaptcha v2 token to PHP via jQuery + Ajax

I want to POST and upload image via AJAX with Google reCaptcha v2 validation. but I am facing an issue that I am not not able to send image with caption text with google recaptcha token in Ajax. I coded two function as I know but both was not working. The function I made is the code snippet.
Please help me how I send Image with text in Ajax with reCaptcha token in PHP / jQuery/ AJAX.
$(document).ready(function() {
$("form#addbanner").unbind("submit").bind("submit", function(e) {
//debugger;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('MY_RECAPTCHA_CODE', {
action: 'add_web_banner'
}).then(function(token) {
/*let formData = {
imagehere : $('input[name="imagehere"]').val(),
bannertitle : $('input[name="bannertitle"]').val(),
action : 'add_web_banner',
type: 'add_web_banner'
};*/ //not working
/*let formData = {
var formData = new FormData($("form#addWeb-Banner")[0]);
formData.append('token': token);
};*/ //not working
//*POST Image sent in (binary way), I dont want to use JSON in types*//
$.ajax({
type: 'POST',
data: formData,
cache: false,
success: function(response) {
hide_loader();
if (response.status == "success") {
$("form#addWeb-Banner")[0].reset();
alert("Great");
} else {
alert("Ops!");
}
},
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="bs-example form-horizontal AddWebBanner" id="addbanner" enctype="multipart/form-data" method="POST">
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Upload Image</label>
<div class="col-lg-8">
<input type="file" class="form-control" title="Upload Photo" id="BannerImage" name="imagehere" accept="image/png,image/jpg,image/jpeg" />
</div>
</div>
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Caption of Banner</label>
<div class="col-lg-8">
<input type="text" class="form-control" title="Caption of Banner" name="bannertitle" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-lg-12">
<button type="submit" name="submit" class="btn btn-sm btn-default pull-right" id="addBannerBtn">POST</button>
</div>
</div>
</form>
Change your HTML and formData to the following
Give an id selector your caption banner.
<input type="text" class="form-control" id="caption_banner" title="Caption of Banner" name="bannertitle" />
Store using the formData like this and then sent formData via ajax
var formData = new FormData();
//Append Image
formData.append('file', $('#BannerImage')[0].files[0]);
//Append banner caption
formData.append('caption', $('#caption_banner').val());
You can also use jQuery .serialize method to send data to your backend via ajax
var formData = $('form#addbanner').serialize()
thank for #AlwaysHelping but there was one mistake but I has been fix that..below are the correct answer for future user troubles..
I not mentioned processData: false, contentType: false, in ajax.. so the final code will be..
var formData = new FormData();
formData.append('file', $('#BannerImage')[0].files[0]);
formData.append('caption', $('#caption_banner').val());
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (response) { ... }
peace :)

How to get CKEditor value in Codeigniter?

I Want to receive the values from the CKEditor. I Have written this HTML code
<div class="col-md-12">
<div class="form-group">
<label for="Image" class="control-label">Item Description </label>
<textarea id="item_description" name="item_description" rows="10" cols="80" style="resize:none"></textarea>
</div>
<!-- /.form-group -->
</div>
<div class="col-md-2">
<input type="submit" name="submit" id="Add" value="Add Items" class="btn btn-success">
</div>
This is the JQuery Code to get the value of the CKEditor
$("#Add").on("click", function(e) {
e.preventDefault();
var item_description = CKEDITOR.instances["item_description"].getData();
var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form
$.ajax({
url: "'.base_url().'Home/add_items",
type: "post",
data: formData,
success: function(output) {
alert('Added'):
}
});
});
And this the Home controller but when I here access the item_description
value is empty.
<?php
class Home extends MY_Controller
{
public function add_items()
{
echo $title = $this->input->post('item_description');
//$this->show('admin/add_items.php');
}
}
?>
Modify your javascript codes, like this :
$("#Add").on("click", function(e) {
e.preventDefault();
var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form
formData.append('item_description', CKEDITOR.instances['item_description'].getData());
$.ajax({
url: "<?=base_url()?>Home/add_items",
type: "post",
data: formData,
success: function(output) {
alert(output);
}
});
});

Auto refresh dropdown after send new value

i have a dropdown with this code:
and other block:
<script type="text/javascript">
/*Primo pulsante attributo*/
$(document).ready(function() {
$('#bloccoetapulsante').click(function() {
var dati = $("#campo").val();
$.ajax({
url: "database/bloccoattributi.php",
data: 'dati=' + dati,
method: "POST",
dataType: "HTML",
cache: false,
success: function(data) {
alert("Attributo inserito");
}
});
});
});
</script>
<div class="row">
<div class="col-lg-3">
<div class="input-group">
<input name="campo" id="campo" type="text" class="form-control" placeholder="Inserisci altro">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="bloccoetapulsante"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<!-- /input-group -->
How can i update dropdown, without reload page, after add a new value with button (bloccoetapulsante)?
Thanks
success: function (data) {
$("#id").html("Attributo inserito"); // #id as a dropdown Id
}
or
$("#id").append("Attributo inserito");
Simply add $('.selectpicker').selectpicker('refresh'); after ajax call. it will refresh Bootstrap selectbox

PHP: Echoing values of input fields

I am grabbing the values of several input fields with the help of an Ajax/JS function. The issue is that the values of the textbox are not being echoed. I checked with the firebug tool and it shows that the post is performed but there is a blank value. Why is the PHP not echoing the value when the JS function submits it?
EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
HTML
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
</form>
You need to use .serialize() on the form probably
Friend first understand the Javascript behaviour.
When you post a form, it becomes one request to the server. At the same time when you send an ajax to server it becomes another separate request to the server
So you should either do form post or ajax.
As you are using ajax here you, in the ajax request you have to pass data separately in data parameter
<script type="text/javascript">
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
data: $('#contact_form').serialize(), // check this line
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>

Categories