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')";
Related
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
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";
}
So I'm making an Ajax call which will first check to see if that post ID has already been voted on.
Currently I'm just working on the PHP to first get the post id's, if it is empty set it or if it is not empty to append the ID.
Question here: Except when I use the implode or explode method it does not seem to make a call back to the javascript. Although if I was to refresh the page it does register the vote.
This is the PHP file. For user Id I've just set it to my admin id to start with.
function my_user_vote() {
$user_id = 1;
$pageVoted = $_REQUEST["post_id"];
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
if (empty($currentPosts)) {
// Empty create single array
$postsVotedOn[] = $pageVoted;
} else {
$postsVotedOn = explode('|', $currentPosts);
$postsVotedOn[] = $pageVoted;
}
$boo = implode("|", $pageVoted);
update_user_meta( $user_id, 'pages_voted_on', $boo);
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
This is the javascript.
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery(".vote_counter").html("Votes: " + response.vote_count);
jQuery(".voteUpButton").html('<div class="button btnGreen">Thank you!</div>');
alert("Cooommmon");
console.log(response.vote_count);
}
else {
alert("Your vote could not be added")
}
}
})
})
})
I just did a quick test with your code, and found a couple of issues that throw errors:
1. This line:
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
should be
$currentPosts = get_user_meta($user_id, 'pages_voted_on', true);
2. And I believe this line:
$boo = implode("|", $pageVoted);
should be
$boo = implode("|", $postsVotedOn);
Explanation:
Without the true argument get_user_meta returns an array. And you can't explode an array.
http://codex.wordpress.org/Function_Reference/get_user_meta
$pageVoted is the id of the page to add, while $postsVotedOn is the actual list you want it appended to.
I'm trying to use jQuery to check if the username that the user entered in a form is already taken. Below are the relevant codesnippets in Java, and existence.php.
*javascript*
var username = document.register.username.value;
usernameTaken = checkUserExistence(username, 'username');
function checkUserExistence(str, type){
var dataString = '?str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existence.php",
data: dataString,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
$("#submit").val('Succes!');
return 1;
}else{
$("#submit").val('Failure!');
return 0;
}
}
});
}
return false;
}
*/JavaScript*
<?php
include("inc/connect.php");
$data = $_POST["str"];
$type = $_POST["type"];
switch($type){
case "username":
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
break;
}
?>
What am I doing wrong?
My website is supposed to show live hints to the users, like 'your username is too short' etc. All hints are working, but the ones where it should say 'your username is already taken' won't show. The form gets processed to my PHP-register function, where usernames that are already taken get rejected, so somehow the checkUserExistence-function and the existence.php page are not working.
Edit:
For a live demonstration of my code, go to:
http://beta.somentus.nl/index.php
The usernames 'Admin', 'Somentus' and 'Rik' are already taken, try them out :)
$data = $_POST["data"];
should be:
$data = $_POST["str"];