Parameter returning undefine and php select by id returning null - javascript

someone should pls help me out on this.
I need to select and update data by id from SQL database but i am not getting the appropriate result.
The php file is returning null. When i checked from my developer tool, i realised that the params code, this.props.match?.params.id is showing undefined. I guess it is not able to send the id parameter to the "$id" in the edit.php code.
Someone should please help me look into the codes. I want to be able to select and edit based on specific id from the database.
Thank you
Here is my code;
edit.php
<?php
require 'connect.php';
include_once("Core.php");
$id = $_GET['id'];
//Get by id
$sql = "SELECT * FROM `visitors` WHERE `id` ='{$id}' ";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
// print_r($row)
echo $json = json_encode($row);
exit;
The update code is bellow
update.php
<?php
include_once("Core.php");
require 'connect.php';
//Get the posted data
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
// Extract the data
$request = json_decode($postdata);
print_r($request);
// Sanitize
$id = $_GET['id'];
$lastName= $request -> lastName;
// Update
$sql = "UPDATE `visitors` SET `lastName` = '$lastName' WHERE `id` = '{$id}' LIMIT 1";
if(mysqli_query($con, $sql))
{
http_response_code(201);
}
else
{
http_response_code(422);
}
}
For the edit code
edit.js
import React, { Component } from "react";
import "./Edit.css";
import "react-datepicker/dist/react-datepicker.css";
import Axios from "axios";
export default class Edit extends Component {
constructor(props) {
super(props);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
firstName: "",
lastName: "",
};
}
componentDidMount() {
Axios.get(
"http://localhost/testing/edit.php?id=" + this.props.match?.params.id
)
.then((response) => {
this.setState({
firstName: response.data.firstName,
lastName: response.data.lastName,
});
})
.catch(function (error) {
console.log(error);
});
}
// }
onChangeLastName(e) {
this.setState({
lastName: e.target.value,
});
}
onSubmit(e) {
e.preventDefault();
const obj = {
lastName: this.state.lastName,
};
Axios.post(
"http://localhost/testing/update.php?id=" + this.props.match?.params.id,
obj
).then((res) => console.log(res.data));
this.setState({
lastName: "",
});
}
render() {
return (
<div className="edit">
<form onSubmit={this.onSubmit}>
<div className="edit__text">Date & Time Out:</div>
<label>
Last Name:
<input
name="last"
type="text"
value={this.state.lastName}
onChange={this.onChangeLastName}
/>
</label>
<button>Submit</button>
</form>
</div>
);
}
}

this.props.match.id
This code is no longer valid in react,
It has been replaced by useParams hook
...
const id = useParams();
componentDidMount() {
Axios.get(
"http://localhost/testing/edit.php?id=" + id;
)
...
This should work, and you need to import the hook too.

Related

POST http://127.0.0.1:8000/broadcasting/auth 403 (Forbidden) ,How i can resolve this error

app.js :
import './bootstrap';
Echo.private('App.Models.Company.' + companyId)
.notification((notification) => {
console.log(notification);
});
channel.php :
Broadcast::channel('App.Models.Company.{id}', function ($company, $id) {
return (int) $company->id === (int) $id;
});
blade page :
<script>
let companyId = '{{ Auth::id() }}';
</script>
#vite(['resources/js/app.js'])
This problem has been solved, because I am using guards in my system, it does not recognize any guards other than the default guard
I defined the guard in the channel route such as :
Broadcast::channel('App.Models.Company.{id}', function ($company, $id) {
return (int) $company->id === (int) $id;
},['guards'=>['company']]);

Trying to implement a comments system with laravel

Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
Route::get('/tip/select','TipController#select');
Route::post('/tip/select', 'TipController#addComment');
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;
class Comment extends Model
{
protected $guarded = [];
protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
{
$response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
'comment' => $comment,
'limit' => -3,
])->json();
if ($response['commentate']) {
abort(400, "Comment not allowed");
}
}
public function tip(){
return $this->belongsTo('App\Tip');
}
public function user(){
return $this->belongsTo('App\model\User');
}
}
Controller
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;
class TipController extends Controller
{
public function select(){
//$db=DB::table('tips')->orderBy('created_at','desc');
$data=Tip::get();
$url = Storage::disk('s3');
//$data=Tip::paginate(10);
//$data=$db->get();
// dd($data);
$comments = Comment::orderBy('id')->get();
return view('tip', compact('data', 'url','comments'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create(){
$categories=Category::all();
$cities=City::all();
return view('tip.create',compact('categories','cities'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request, City $city, Category $category){
$this->validate($request, [
'image' => 'image|nullable|max:1999']);
$tipsnew = new Tip;
$tipsnew->title = $request->title;
$tipsnew->description = $request->description;
$tipsnew->category_id = $request->category;
$tipsnew->city_id = $request->city;
$tipsnew->user_id = auth()->id();
$tipsnew->url = $request->url;
if ($request->hasFile('image')) {
try{
$file = $request->file('image');
$name = time() . '.' . $file->getClientOriginalExtension();
$img = \Image::make($file->getRealPath());
$img->fit(1080);
$img->stream();
Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
$tipsnew->image = 'tip'.'/'.$name;
}
catch (\Exception $e)
{
$response = [
'information' => 'Error. Something went wrong. Please try again',
];
$statusCode = 400;
return response()->json($response, $statusCode);
}
}
$tipsnew->save();
return redirect ('tip/create')->with('status','your tip is created');
}
public function edit($id){
$tip=Tip::whereId($id)->firstOrFail();
$categories=Category::all();
$selectedCategories=$tip->categories->lists('id')->toArray();
return view('tip.edit',compact('tip','categories','selectedCategories'));
}
public function search(Request $request, City $city, Category $category, User $user){
$q = $request->get('q');
if ($q != ""){
$tips = Tip::where('title','LIKE','%'.$q.'%')
->orWhere('description','LIKE','%'.$q.'%')
->orWhereHas('user', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('city', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('category', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->get();
if(count($tips) > 0)
return view('tip.search', ['tips' => $tips]);
}
}
public function addComment(Request $request)
{
$data = $request;
Comment::moderate($data['text']);
$comment = Comment::create($data);
Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
//add creation of new comment to DB
$commentnew = new Comment;
$commentnew->user_id = Auth::user()->id();
//$commentnew->tip_id= $request->post(['tip_id']);
$commentnew->body = $request->text;
$commentnew->save();
return $comment;
}
}
Snippet of the blade
<h3>Comments</h3>
<form onsubmit="addComment(event);">
<input type="text" placeholder="Add a comment" name="text" id="text" required>
<input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
<input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
<button id="addCommentBtn">Comment</button>
</form>
<div class="alert" id="alert" style="display: none;"></div>
<br>
<div id="comments">
#foreach($comments as $comment)
<div>
<small>{{ $comment->username }}</small>
<br>
{{ $comment->text }}
</div>
#endforeach
</div>
<!--jQuery script used to be here -->
<script>
function displayComment(data) {
let $comment = $('<div>').text(data['text']).prepend($('<small>').html(data['username'] + "<br>"));
$('#comments').prepend($comment);
}
function addComment(event) {
function showAlert(message) {
let $alert = $('#alert');
$alert.text(message).show();
setTimeout(() => $alert.hide(), 4000);
}
event.preventDefault();
$('#addCommentBtn').attr('disabled', 'disabled');
var data = {
text: $('#text').val(),
username: $('#username').val(),
tipid: $('#tip_id').val(),
};
fetch('/tip/select', {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
'x-socket-id': window.socketId
},
method: 'POST',
mode: 'cors',
}).then(response => {
$('#addCommentBtn').removeAttr('disabled');
displayComment(data);
showAlert('Comment posted!');
})
}
</script>

How would I successfully re-direct to my .js file (reactjs) instead of my php file upon submitting info?

As of now, I'm successfully inserting information into the database (SQL, phpMyAdmin) via Home.js but the problem is that every time the user enters information & hits submit, it gets redirected to my demo.php file instead of Next.js.
In other words, how can I make it so that upon the user information successfully entering the database and go to the next page? (Next.js)?
I know <form action="http://localhost/demo_react/api/demo.php" method={"POST"} encType="multipart/form-data"> will inevitably take me to demo.php but if I don't use this, then nothing gets submitted to my db.
What am I doing wrong and how can I fix this?
Here's Home.js:
import React, { Component } from 'react';
import Next from '../Home/Next';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
show: false
};
this.getPHP = this.getPHP.bind(this);
}
getPHP(e) {
this.setState({show: true});
let formData = new FormData();
fetch(`http://localhost/demo_react/api/demo.php`, {
method: 'POST',
body: formData
}).then(res => res.json())
.then(response => {
console.log('response');
console.log(response);
e.preventDefault();
});
}
render() {
const goNext = this.state.show;
if(goNext) {
return <Next/>;
}
return (
<div>
<form action="http://localhost/demo_react/api/demo.php" method={"POST"} encType="multipart/form-data">
<div className="form-group">
<label htmlFor="username">Email</label>
<input className="form-control" type="text" name="username"/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input className="form-control" type="password" name="password"/>
</div>
<input className="btn btn-primary" type="submit" value="Login" onSubmit={e => this.getPHP(e)} name={"submit"}/>
</form>
</div>
);
}
}
export default Home;
Here's demo.php:
$connection = mysqli_connect("localhost", "root", "", "loginapp");
$username = $_POST['username'];
$password = $_POST['password'];
if(isset($_POST['submit'])) {
$query = "INSERT INTO users(username, password) ";
$query .= " VALUES('$username', '$password')";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Query failed" . mysqli_error($connection));
} else {
echo "check database";
}
}
Do not use a type="submit" button. Use a type="button" or a <button>. If your form didn't have a submit, the problem is solved.
Obviously, in your JS code you need to send the information. You can collect it and send to demo.php without triggering form submit. I'll show you a basic example for doing it.
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
var user = (document.getElementById(form).username) ? encodeURIComponent(document.getElementById(form).username.value) : '';
var pass = (document.getElementById(form).password) ? encodeURIComponent(document.getElementById(form).password.value) : '';
var data = 'username=' + user + '&password=' + pass;
request.open('POST', document.getElementById(form).action, false);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset:UTF-8");
request.setRequestHeader("Content-length", data.length);
request.send(data);
if (request.status == 200) {
alert('Send OK.');
} else {
alert('Send error.');
}
The included snippet get the URL to send information from the form action itself. You can optimize the code a lot probably, but it's a starting point. This code uses plain JS, you can change it to jQuery for example (jQuery version its shorter for example).
Also, if you need to eventually do a redirect, use a JS redirect instead.

How to call a specific php function inside a class through ajax?

I want to know how I can call the function ajax_check_login available in my User class, this class exists in user.php.
This is the basic content:
class User extends {
/**
* Class Constructor
*/
public function __construct() {
}
public function ajax_check_login() {
try {
if (!isset($_POST['username']) || !isset($_POST['password'])) {
throw new Exception('Invalid credentials given!');
}
$this->load->model('user_model');
$user_data = $this->user_model->check_login($_POST['username'], $_POST['password']);
if ($user_data) {
$this->session->set_userdata($user_data); // Save data on user's session.
echo json_encode(AJAX_SUCCESS);
} else {
echo json_encode(AJAX_FAILURE);
}
} catch(Exception $exc) {
echo json_encode(array(
'exceptions' => array(exceptionToJavaScript($exc))
));
}
}
}
and this is my ajax request:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// Some stuff..
});
How you can see I want call the function ajax_check_login available in the user.php file. But I can't access directly to this function 'cause is located inside the User class, so I should create another file to bounce the request or I can do it in the same file user.php file?
You have a typo:
class User extends {
Extends what?
Add this to user.php (outside of the class):
$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
$user = new User();
$user->$func();
}

Autocompleting a form in PHP/Javascript

I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.

Categories

Resources