I am trying to get the values of the first 9 clicked buttons and put them into an array named $u_input. I actually found this, but its in javascript.
my html:
<div>
<button name="btn1" type="submit" id="btn1" value="1" style="width:50%;height:40%;margin-left: auto;margin-right: auto; float:left" class="ui-btn"></button>
<button name="btn2" type="submit" id="btn2" value="2" style="width:50%;height:40%;margin-left: auto;margin-right: auto;float:right" class="ui-btn"></button>
</div> // I have up to 9 buttons, thats only a piece
my javascript:
$(document).ready(function(){
$('.ui-btn').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'escreen.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
});
my php:
if (isset($_POST['action'])) {
$u_input = array($_POST['action'](1), $_POST['action'](2), $_POST['action'](3), $_POST['action'](4));
echo $u_input;
}
Just loop through the buttons with the following code:
jQuery(document).ready(function($){
var ajaxurl = 'escreen.php',
$values = [];
$('button').each(function(){
$values.push($(this).val());
});
$.ajax({
url: ajaxurl,
type: 'post',
data: {
buttons: $values,
},
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
An even nicer way to do it would be to set a name for each property in your array:
jQuery(document).ready(function($){
var ajaxurl = 'escreen.php',
$values = [];
$('button').each(function(){
$values[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: ajaxurl,
type: 'post',
data: {
buttons: $values,
},
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
The array $values should contain the following:
[button1: "value1", button2: "value2", button3: "value3"]
So in your PHP file you can retreive it by using:
$_POST['buttons']['button1']
Related
Actually i just trying to get all input data from serialize but i get the values in int type like age & id but unable to get value of name.
following is my code.
<html>
<body>
<form id ="form" method="post" class= "form">
Name<input type = "text" name = "name" /><br>
Age<input type = "number" name = "age" /><br>
ID<input type = "number" name = "id" /><br>
<input type = "submit" name = "submit"><br/>
</form>
<p id="result"></p>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#form").submit(function () {
var data = $("#form").serialize();
insertStudent(data);
return false;
});
function insertStudent(data) {
$.ajax({
url: 'process.php',
data: data,
type: 'POST',
dataType: 'json',
success: function (data, textStatus) {
$("#result").html(data);
},
error: function () {
alert('Not OKay');
}
});
}
});
</script>
</body>
</html>
process.php
print_r($_POST);// give error but if i try to get id then
print_r($_POST["id"])// print value
print_r($_POST["name"])// doesn't print name
$(document).ready(function () {
$("#form").submit(function (e) {
//e.preventDefault();
var data =$(this).serialize();
insertStudent(data);
return false;
});
function insertStudent(data) {
$.ajax({
url: 'process.php',
data: data,
type: 'post',
dataType: 'html',
success: function (data, textStatus) {
$("#result").html(data);
// console.log(data);
},
error: function () {
alert('Not OKay');
}
});
}
});
I'm trying to submit a single value as following?
HTML:
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" name="frmanalyse" id="frmanalyse">
{{ csrf_field() }}
<label for="marginsource" style="float: left; width:150px; text-align:left;">Margin Source</label>
<input type="file" name="marginsource" id="marginsource" >
<br />
</form>
script:
<script type="text/javascript">
$( "#frmanalyse" ).submit(function(event) {
$.post( "marginanalyser", {username: "medo ampir"}, function( data ) {
alert(data);
});
event.preventDefault();
});
in laravel routes:
Route::post('marginanalyser',function(Request $request){
echo $request->input('username');
$file = $request->file('marginsource');
echo 'File Name: '.$file->getClientOriginalName();
});
nothing shows in the message at all.
Change your JavaScript to use FormData as you aren't submitting the file
$( "#frmanalyse" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('marginsource', $('#marginsource')[0].files[0]);
formData.append('username', "medo ampir");
$.ajax({
url : window.location.origin + "/marginanalyser",
type: "POST",
data : formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
});
I have been trying to upload an image with AJAX but somehow it's not working. CodeIgniter always throwing 'You have not selected any file'.
Thanks in advance.
Here's my Controller -
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index() {
$this->load->view('upload/upload');
}
public function upload_file() {
$config['upload_path'] = './uploads/Ajax/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
$title=$this->input->post('title');
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors()."<br>".$title;
}
else {
$data = $this->upload->data();
echo $data['file_name']." uploaded successfully";
}
}
}
/* end of file */
And here's the view
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX File Upload</title>
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js"> </script>
<script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js"> </script>
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" autocomplete="off">
</p>
<p>
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile">
</p>
<input type="submit" name="submit" id="submit">
</form>
<h2>Result</h2>
<span id="result"></span>
</body>
I have tested in Firefox 43, IE11 & Chrome 43
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
secureuri :false,
fileElementId :'userfile',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
You need to add xhr function in ajax request
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
url: $(this).attr('action'),
data:formData,
cache:false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
you can use
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
no plugin required for this, for easiness you can use ajaxForm jquery plugin and just use
$('#form-id').ajaxSubmit({
// same config as ajax call but dont use data option right here
});
have a look on http://malsup.com/jquery/form/ to for more information about plugin
Use this
$("#upload-form").on('submit' ,function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: new FormData(form[0]),
dataType: 'json',
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function(data){
}
});
});
Use $.ajaxFileUpload instead $.ajax, this should work, if not please let me see your AjaxFileUpload.js
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajaxFileUpload({
url :'./upload/upload_file/',
fileElementId : 'userfile', // your input file ID
dataType : 'json',
//
data : {
'title' : $('#title').val() // parse title input data
},
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
EDITED with UPDATED CODE: Im missing something here; the jQuery is working, but the variables arent passing to the query. Below is all of the updated code:
<span class="accepted"><input type="button" title="accept" value="Accept" /></span>
AJAX Script
<script type="text/javascript">
$(function() {
$(".accept").click(function(){
var element = $(this);
var del_id = element.attr("id");
var order_id = element.attr("data-order");
//if(confirm("Are you sure you want to delete this?"))
//{
$.ajax({
type: "POST",
url: "accept.php",
//data: info,
data: {id:del_id,order_id:order_id},
success: function(){}
//
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
//}
//return false;
});
});
</script>
new php file
include('db.php');
$id = $_POST['id'] ;
$name = $_POST['order_id'] ;
$sql = "UPDATE mgap_orders SET mgap_status = 1 WHERE mgap_ska_id = :id AND mgap_ska_report_category = :name";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':id' => '$id',
':name' => '$name'
));
Instead of using var info = 'id=' + del_id; and data: info, You should send variables like below:
data: {id:del_id}
Future more, if you want to pass more variables you can go like below:
data: {id:del_id,order:ORDER_ID}
Hope this helps.
do like this
$.ajax({
type: "POST",
url: "delete.php",
data: {id:del_id,order:order_variable},
success: function(){
}
Specify your Data as an object. Should be separated by comma for each variable.
data: {variablename1: value1, variablename2: value2}
So you code should look like:
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
//var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: { id: del_id, var2: var2, var3: var3 },
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("data-id");
var order_id = element.attr("data-order");
var info = 'id=' + del_id;
var order = 'order' + order_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "mod_accept.php", //Changed the processor file
data: {info, order},
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
Then in your html:
<span class="accepted"><input type="button" title="accept" value="Accept" /></span>
do something like
<span class="accepted">
<a href="#" class="delete" id="<?php echo $id1; ?>"
data-order="<?php echo $order_id;?>">
<input type="button" title="accept" value="Accept" /></a>
</span>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var order_id = element.attr("data-order");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: {id:del_id,order_id:order_id},
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>