I have the insertion of data using php, js, ajax. I'm getting the data from form and will send it to my controller using ajax as post method. My Controller will get all the data requested from my ajax and this data my php code will process to insert it on the database
So this is my way of getting the multiple value of checkboxes in javascript before sending it using ajax.
Here's my sample checkboxes
Html
<input id="chk_RegularShiftTable_rest_mon" class = "chk_RegularShiftTable_rest" type="checkbox" name="chk_RegularShiftTable_rest[]" value="1" disabled>
<input id="chk_RegularShiftTable_rest_mon" class = "chk_RegularShiftTable_rest" type="checkbox" name="chk_RegularShiftTable_rest[]" value="2" disabled>
This how I manage the 2 checkboxes using for
JavaScript
var chkRest = document.getElementsByName('chk_RegularShiftTable_rest[]');
var dataRest = [];
for (var x = 0; x < chkRest.length; x++){
if (chkRest[x].checked){
dataRest.push(chkRest[x].value);
}
}
and this is how I send my data using Ajax and this will go to the controller.
AJAX
$.ajax({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('save') }}",
method: "POST",
dataType: "json",
data: {
dataRest:dataRest
},
success:function(data)
{
if(data.error.length > 0){
alert(data.error[0]);
}
if(data.success.length > 0){
alert(data.success[0]);
refresh_Table();
}
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
Now When I get the data that was requested. The controller will validate which values are checked by the user.
The problem in this code is whenever I check the checkboxes it either checkbox 1 with the value of 1 or checkbox 2 with the value of 2 the controller identify which items are selected. Seems like the in_array of PHP doesn't checks if the value is in the array given from the ajax which is the $data_rest
My Controller (PHP)
public function save(Request $request)
{
$message = "";
$result = array();
$error = array();
$success = array();
$data_rest = array($request->dataRest);
if (in_array('1', $data_rest, true)){
$thu = "Success";
$success[] = $thu;
}
else
{
$thu = "Error";
$error[] = $thu;
}
if (in_array('2', $data_rest, true)){
$thu = "Success";
$success[] = $thu;
}
else
{
$thu = "Error";
$error[] = $thu;
}
$result = array(
'error'=>$error,
'success'=>$success,
);
echo json_encode($result);
}
This is the sample Output of array in javascript
Note: The problem is in my controller I'm using the code from the PHP Manual the if(in_array(value,arrayvariable, BOOLEAN)) which doesn't seems do its job to check if the value exist from the post array from ajax
Reference: https://www.php.net/manual/en/function.in-array.php
Related
I have to call this php file
<?php
session_start();
require 'connect.php';
//Prendo le tre variabili dalla form
if(isset($_POST['Titolo'])) {
$title_rew = $conn->real_escape_string($_POST['Titolo']);
}
if(isset($_POST['Voto'])) {
$voto_rew = $conn->real_escape_string($_POST['Voto']);
}
if(isset($_POST['Review'])) {
$review_rew = $conn->real_escape_string($_POST['Review']);
}
if(isset($_POST['ID_locale'])) {
$id_rew = $conn->real_escape_string($_POST['ID_locale']);
}
$current_date = date('Y-m-d');
$sql = "INSERT INTO recensione (Titolo_R, Voto_R, Commento_R, IDnegozio_R, Email_R, Utente_R, Data_R)
VALUES ('$title_rew', '$voto_rew', '$review_rew','$id_rew','".$_SESSION['emailSessione']."','".$_SESSION['usernameSessione']."','$current_date')";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//Chiudo la connessione
$conn->close();
header("location:..\locals_page.php");
?>
I've tried with this
$("#submit_review").unbind().click(function() {
var chx = document.getElementsByName("Voto");
for (var i=0; i<chx.length; i++) {
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
$.post("php/insert_comment.php" );
return true;
}
// End of the loop, return false
alert("Seleziona almeno il voto!");
return false;
});
But there it's not working. It's strange because with a button submit and a
<form role="form" id="review-form" method="post" action="php/insert_comment.php">
It was working.
But now I have to do this without a button type "Submit"
Thank you to all in advance
just try this
$.ajax({
url : "php/insert_comment.php",
type : "post",
data : $("#review-form").serialize();
success : function(data){
alert(data); // show when ajax return response from php script
}
})
for that registered onclick event on that button and send ajax request using jquery
$.ajax({
type:'POST',
url : "your url",
data : $('form').serializeArray(),
cache: false,
success:function(response){
console.log(response) // your result from php
}
})
Single quotes treat $ as a string
$sql = "INSERT INTO recensione (Titolo_R, Voto_R, Commento_R, IDnegozio_R, Email_R, Utente_R, Data_R)
VALUES ('".$title_rew."', '".$voto_rew."', '".$review_rew."','".$id_rew."','".$_SESSION['emailSessione']."','".$_SESSION['usernameSessione']."','$current_date')";
Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)
I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}
I have a form which submits it to the database using JQuery, AJAX and PHP. The problem is, whenever I click the submit button of the form, the JavaScript alert says that the record (data from the form) has successfully recorded (to the database). I would then check my database but the data is not recorded, leaving the database empty and no changes at all. My question is, there something wrong with the script? Or with the PHP code?
Here's the script addnew.js:
$(document).ready(function() {
$("#submit").click(function() {
var transMonth = $("#transMonth").val();
var transDay = $("#transDay").val();
var transYear = $("#transYear").val();
var voucherNum = $("#voucherNum").val();
var expType = $("#expType").val();
var acctsPayable = $("#acctsPayable").val();
var amount = $("#amount").val();
var dataString = 'transMonth1='+ transMonth + 'transDay1='+ transDay + 'transYear1='+ transYear + 'voucherNum1='+ voucherNum + 'expType1='+ expType + 'acctsPayable1='+ acctsPayable + 'amount1='+ amount;
if(voucherNum=='') {
alert("Please fill a valid voucher number.");
}
else {
$.ajax ({
type: "POST",
url: "addnew.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
Here's the PHP code addnew.php:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("mydb", $connection);
//fetch values
$transMonth2 = $_POST['transMonth1'];
$transDay2 = $_POST['transDay1'];
$transYear2 = $_POST['transYear1'];
$voucherNum2 = $_POST['voucherNum1'];
$expType2 = $_POST['expType1'];
$acctsPayable2 = $_POST['acctsPayable1'];
$amount2 = $_POST['amount1'];
//query
$query = mysql_query("insert into anotherSample(transMonth, transDay, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
echo "Record added successfully";
mysql_close($connection);
I think your dataString in addnew.js should be transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='...,
otherwise the $transDay2,$transYear2..would be null, if your transDay or more set NOT NULL in mysql, there will occur a mysql error. :)
You should check returned result. You can do this by the following code:
$result = mysql_query("insert into anotherSample(transMonth, transDay, transMonth, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
if (!$result) {
die('Invalid query: ' . mysql_error()); // only for development, in production you shouldn't print error to client!
}
echo "Record added successfully";
mysql_close($connection);
PS. Also, I advice you to read about SQL-injections, because your code is vulnerable.
I see a problem in insert statement, insert into anotherSample(transMonth, transDay, transMonth, transYear,....) values ('$transMonth2', '$transDay2', '$transYear2, .....) 'transMonth' is repeated twice and eight columns with seven values.
In your addnew.js file you should use an ampersand (&) between each key/value pair like this:
var dataString = 'transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='+ transYear + '&voucherNum1='+ voucherNum + '&expType1='+ expType + '&acctsPayable1='+ acctsPayable + '&amount1='+ amount;
This way you will ensure that each variable will have a value when you are reading them in your addnew.php file.
Check fetched values in addnew.php
and echo mysql_error($connection) to check if mysql error was occurred.
I'm making a web application and I'm trying to make it so when you enter the ID of a provider it automatically outputs them into a span, this is my AJAX/JS call
<script>
function showHint(str)
{
if (str.length == 0)
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../include/proveedores.php?q=" + str, true);
xmlhttp.send();
console.log(telfValor);
}
}
</script>
<span id="txtHint"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
And this is the .php it calls to make the search
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = $_REQUEST["q"];
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
// Output "no suggestion" if no hint was found or output correct values
echo $descrip === "" ? "no suggestion" : $descrip;
?>
Is there any way to accomplish this?
EDIT: This is to make an AJAX calls to return various values into spans with just 1 AJAX call
<script src="../js/jquery.js" type="text/javascript"></script>
<script>
function showHint(str)
{
// If there is nothing on the textbox, there is nothing in the spans
if (str.length === 0)
{
$('#Span Name').html("");
$('#Telephone').html("");
return;
}
$.ajax
({
//Here goes the file which contains the SQL call
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
// Here goes the data that goes into the spans
success: function (data, status, jqXhr)
{
$("#Span Name").html(data["Array Name"]);
$("#Telephone").html(data["Telephone"]);
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log("Error response:", jqXhr.responseText);
}
});
}
</script>
// This is the text input that will be sent to your query file
<input type="text" onkeyup="showHint(this.value)">
<span id="Span Name"></span>
<span id="Telephone"></span>
proveedores.php:
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL, this is what you have posted
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
if (isset($q) && $q !== "")
{
// THIS IS PRONE TO SQL INJECTION! USE INTERNALLY!
$sql = "SELECT * FROM PROVIDERS WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$Variable = $row['Column Name'];
$Telf = $row['Telef'];
$Direc = $row['Direc1'];
}
// This is the array to be encoded to AJAX
$values = array();
// Output "no suggestion" if no hint was found or output correct values
$values["ArrayName"] = ($Variable === "") ? "no suggestion" : $Variable;
$values["Telephone"] = ($Telf === "") ? "" : $Telf;
// Output the json data
print_r(json_encode($values));
?>
To start, you should use a javascript library like jQuery to handle all the tough AJAX lifting. It will make your life sooo much easier. If you want to use regular javascript, you can return a comma-separated string and then parse each value separated by a comma but that can get messy. With that being said, you can use jQuery AJAX and return your data in a JSON encoded data object.
.php
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
$values = array();
// Output "no suggestion" if no hint was found or output correct values
// NOTE: we're using the same "txtHint" here for the key as we do in the javascript function
$values["txtHint"] = ($descrip === "") ? "no suggestion" : $descrip;
// Set these to something useful
$values["txtPhone"] = "";
$values["txtAddress"] = "";
// Output the json data
print_r(json_encode($values));
?>
Now, for the jQuery implementation. The first thing you'll have to do is download the jQuery library from jQuery's website. I would recommend getting the most recent version (currently jQuery 2.x).
.html
<script src="/script/jquery.js" type="text/javascript"></script>
<script>
function showHint(str) {
if (str.length === 0) {
$('#txtHint').html("");
return;
}
$.ajax({
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
success: function (data, status, jqXhr) {
$("#txtHint").html(data["txtHint"]);
// You can do this same thing for the other data returned
$("#txtPhone").html(data["txtPhone"]);
$("#txtAddress").html(data["txtAddress"]);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}
});
// Not sure where this is defined. It might throw an error
console.log(telfValor);
}
</script>
<span id="txtHint"></span>
<span id="txtPhone"></span>
<span id="txtAddress"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
The obvious change is the call to $.ajax() instead of using the XmlHttpRequest() object. It is in and of itself fairly self-explanatory. One thing I would like to mention is that since we set the "type" to "GET", the key-value pairs in "data" will be appended to the url as a querystring in the form: "url?key1=value1&key2=value2&etc...". So the resulting url, in our case, would be "../include/proveedores.php?q=[VALUE_OF_STR]" where [VALUE_OF_STR] is the value of the str variable.
The other change worth noting is that jQuery has a very helpful way of selecting elements. If you want to get an element by an ID you can just use the syntax: $('#txtHint').
Where the '#' symbol denotes that we're looking for an element based on the ID and 'txtHint' is the ID of the element you're looking for. You can read more about jQuery selectors in the docs.