I want to submit a react form making an ajax call to php server. I have used react hook but since I am new to it, I cant not figure out error actually.
function App() {
const [name, setName] = useState("");
const [result, setResult] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
const handleSumbit = (e) => {
e.preventDefault();
const form = $(e.target);
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success(data) {
setResult(data);
}
});
};
return (
<div>
<form
action="server.php"
method="post"
onSubmit={(event) => handleSumbit(event)}
>
<label htmlFor="name">Name: </label>
<input
type="text"
id="name"
name="name"
value={name}
onChange={(event) => handleChange(event)}
/>
<br />
<button type="submit">Submit</button>
</form>
<h1>{result}</h1>
</div>
);
}
const header4 = ReactDOM.createRoot(document.getElementById('header4')) ;
header4.render(<App />);
I have skipped the import part. The above code runs without any error but when I click the button, nothing happens.
This is my php code:
<?php
header('Access-Control-Allow-Origin: http://localhost:3000');
$user = $_POST['name'];
echo ("Hello from server: $user");
?>
I verified that your react code is working fine, and if you check in network tab in developer tools in any browser, there is a POST request going to http://localhost:3000/server.php. The reason you see nothing happening is that this url might not be what you server is listening to.
If we don't provide the absolute url, relative path causes your request to be handled by react at http://localhost:3000/server.php and it errors out as there is no resource to handle it.
To fix the issue, change form action attribute to:
http://<serverhost>:<serverport>/server.php
This should work for localhost based servers. For production applications, you might consider making POST request to a server instead of form submission.
Please try and let me know if this fixes your issue.
I am a beginner, I unable to get the result from the database through ajax call in my PHP code.
Here is the sample php code with an ajax call.
<script>
$('.input').on('click',function(e){
e.preventDefault();
$.ajax({
method:'POST',
url:'',
data:{data_username:$('#username').val(),
data_lastname:$('#lastname').val()},
success:function(data){
var x =JSON.parse(data);
for(var index in x){ //here my error
console.log(x[index].username);
}
}
,error:function(){
alert("failed!!!!!");
}
});
});
</script>
Looking at the code you posted suggests that you are sending the ajax request to the same page which leads me to think that the error you are receiving is because there is other HTML content all mashed up with the JSON content that you want. To prevent this from happening eithe rsend the request to a different page or use ob_clean before you begin sending the ajax query response and ensuring that the script finishes at the point of sending the data. Perhaps the following might help.
There is also a spelling mistake $usernmae should be $username!
<?php
$use_live_db=false; # set to true to try running sql queries against db
if( isset( $_POST['data_username'], $_POST['data_lastname'] ) ){
/*
when sending ajax to the same page you must ensure that ONLY the
data you want is allowd to be sent - so using `ob_clean()` will
discard any previously generated content from appearing in the
output
*/
ob_clean();
/*
I appreciate this is probably for testing but this is
simply yielding data you already know...
*/
$username=$_POST['data_username'];
$lastname=$_POST['data_lastname'];
$sql='SELECT username, lastname FROM login where username=:one AND lastname=:two';
$results=array(
'username' => $username,
'lastname' => $lastname,
'sql' => $sql
);
if( $use_live_db ){
/* !!! CHANGE THIS TO THE APPROPRIATE FILE FOR YOUR SYSTEM !!! */
require '/path/to/db-pdo.php';
$results=array();
$stmt=$db->prepare( $sql );
if( $stmt ){
# think it should be bindParam rather than bindparam!
$stmt->bindParam(':one',$username,PDO::PARAM_STR);
$stmt->bindParam(':two',$lastname,PDO::PARAM_STR);
$stmt->execute();
while( $row=$stmt->fetch() ){
$results[]=$row;
}
}else{
exit('error: failed to prepare sql query');
}
}
/*
Similarly to using `ob_clean()` you must prevent the remainder of
the current page appearing as part of the ajax response -
so use `exit` or `die`
*/
header('Content-Type: application/json');
exit( json_encode( $results ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>jQuery & AJAX - POST request to PHP script to interrogate db</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<form>
<input type='text' id='username' name='username' value='mike' />
<input type='text' id='lastname' name='lastname' value='hunt' />
<input type='button' class='input' value='OK' />
</form>
<script>
$('.input').on('click',function(e){
e.preventDefault();
$.ajax({
method:'POST',
url:location.href,
/*
If you set the dataType
properties jQuery automagically ensures
the response is in the correct format- JSON
*/
dataType: 'json',
data:{
data_username:$('#username').val(),
data_lastname:$('#lastname').val()
},
success:function( json ){
console.info('username: %s\nlastname: %s\nSQL: %s', json.username, json.lastname, json.sql )
alert('ok')
},
error:function(){
alert('failed!!!!!');
}
});
});
</script>
</body>
</html>
I am learning to code and I made a simple php app that makes a phone call given a hard coded from and to number (it uses the Twilio api - www.twilio.com).
The code looks like below:
<?php
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$twilio = new Client($sid, $token);
$call = $twilio->calls
->create("+15558675310", // to
"+15017122661", // from
array("url" => "http://demo.twilio.com/docs/voice.xml")
);
print($call->sid);
The above php app works just fine.
What I want to now do is create an html page that takes a dynamic to number (static from number) and when I hit the submit button, the call should go through. However I have no clue how to make that happen except for the following snippet from the twilio documentation (https://www.twilio.com/docs/voice/api/call#create-a-call-resource)
Calls can be made via the REST API to phone numbers, SIP addresses, or client identifiers. To place a new outbound call, make an HTTP POST request to your account's Call resource.
From that, I understand that I have to make a post call via an html form page, but where do I start the post call to the URL as shown in the above documentation (https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Calls.json) and where do I keep the authentication details in the php app that I copy pasted above? The documentation says that I've to provide a for and to number when making the post call, again I am not sure where to provide that.
<html>
<body>
<form action="twilioCall.php" method="post">
From: <input type="number" name="from">
To: <input type="number" name="to">
<input type="submit">
</form>
</body>
</html>
Any help/pointers would be very helpful. Thanks in advance!
In order to place calls in your browser with your laptop/computer with Twilio you need Twilio Client library and you also need to install the Twilio PHP Library.
This assumes that you have already created a Twilio account and purchased a twilio number with voice and sms capabilities. I assumed that you have already installed Twilio PHP library.
When you will press on "makeCall" button, you will be prompted to use your microphone. Select whatever microphone you use to speak with your laptop. Put on some headphones and call yourself. Lots of fun!
Do this :
Find your Twilio Account SID and Primary Auth Token.
Create a TwiML APP and point the VOICE REQUEST URL to
https://EXAMPLEmywebsite.com/voice.php
voice.php
<?php
include '../twilio/Twilio/autoload.php';
use Twilio\Twiml;
$response = new Twiml;
//THE PHONE NUMBER YOU HAVE PURCHASED
$TWILIO_CALLER_ID = '';
// get the phone number from the page request parameters, if given
if (isset($_REQUEST['To']) && strlen($_REQUEST['To']) > 0) {
$number = htmlspecialchars($_REQUEST['To']);
$dial = $response->dial(array
('callerId' => $TWILIO_CALLER_ID,
'record' => 'record-from-answer'
));
if($number == "English Queue" || $number== "Spanish Queue") {
$dial->queue($number);
}
elseif (preg_match("/^[\d\+\-\(\) ]+$/", $number)) {
$dial->number($number);
} else {
$dial->client($number);
}
} else {
$response->say("Thanks for calling!");
}
header('Content-Type: text/xml');
echo $response;
dialpad.php
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Twilio Client IMPORTANT -->
<script src="https://media.twiliocdn.com/sdk/js/client/v1.6/twilio.min.js"></script>
//display phone logs
<div id="log"></div>
//simple basic dialpad
<input id="phoneScreen" placeholder="enter phone number">
//dial button
<button id="makeCall" class="btn btn-success btn-dial">
<img src="https://img.icons8.com/ios/25/000000/ringer-volume.png">
</button>
//hang up button
<button id="endCall" class="btn btn-danger btn-dial">
<img src="https://img.icons8.com/ios/25/000000/end-call.png">
</button>
//include twilioClient.js
<script src="twilioClient.js"></script>
twilioClient.js
$(function () {
log('Connecting Agent Station...');
$.getJSON('./token.php').done(function (data) {
log('Agent Station Connected.');
//console.log('Token: ' + data.token);
// Setup Twilio.Device
Twilio.Device.setup(data.token);
Twilio.Device.ready(function (device) {
log('Phone Ready For Call');
});
Twilio.Device.error(function (error) {
log('Agent Station Error: ' + error.message);
//update call log
});
Twilio.Device.connect(function (conn) {
log('Success! Call Established.');
});
Twilio.Device.disconnect(function (conn) {
log('Call ended.');
});
//bind button to answer incoming call?
document.getElementById('answerCall').onclick = function () {
// get the phone number to connect the call to
var queueName = document.getElementById('queuename').value;
var params = {
To: queueName
};
log('Connecting agent to ' + params.To + '...');
Twilio.Device.connect(params);
};
setClientNameUI(data.identity);
})
.fail(function () {
log('Could not connect agent station to server!');
});
// Bind button to make call
document.getElementById('makeCall').onclick = function () {
// get the phone number to connect the call to
var params = {
To: document.getElementById('phoneScreen').value
};
log('Calling ' + params.To + '...');
Twilio.Device.connect(params);
Twilio.Device.connect(function (connection) {
//retrieve call sid
var callSid = connection.parameters.CallSid;
//retrieve phone number
var phonenumber = $('#phoneScreen').val();
});
};
// Bind button to hangup call
document.getElementById('endCall').onclick = function () {
log('Hanging up...');
Twilio.Device.disconnectAll();
};
});
// Activity log
function log(message) {
var logDiv = document.getElementById('log');
logDiv.innerHTML += '<p>> ' + message + '</p>';
logDiv.scrollTop = logDiv.scrollHeight;
}
token.php
<?php
include '../twilio/Twilio/autoload.php';
use Twilio\Jwt\ClientToken;
// choose a random username for the connecting user
$identity = "Caller".rand(9, 99999).round(microtime(true) * 1000).date('Y');
//twilio account sid
$TWILIO_ACCOUNT_SID = 'YOUR_TWILIO_ACCOUNT_SID';
//twilio auth token
$TWILIO_AUTH_TOKEN = 'YOUR_TWILIO_AUTH_TOKEN';
//twilio app sid
$TWILIO_TWIML_APP_SID = 'YOUR_TWIMl_APP_SID';
$capability = new ClientToken($TWILIO_ACCOUNT_SID, $TWILIO_AUTH_TOKEN);
$capability->allowClientOutgoing($TWILIO_TWIML_APP_SID);
$capability->allowClientIncoming($identity);
$token = $capability->generateToken();
// return serialized token and the user's randomly generated ID
header('Content-Type: application/json');
echo json_encode(array(
'identity' => $identity,
'token' => $token,
));
Hi guys? am trying to post data to the database using laravel 5 and ajax..am also applying using csrf protection by adding
<meta name="_token" content="{!! csrf_token() !!}"/>
to my layout header and adding the following code to my footer:
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
This is my form:
<form action="{{action('QuizController#postQuiz')}}" method="POST">
<div id="name-group" class="form-group">
<label for="name">Please type your question here</label>
<input type="text" class="form-control" name="question">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
This is my JS code:
var formData = {
'question' : $('input[name=question]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'quiz',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console to see
console.log(data);
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
This is my route:
Route::post('create/quiz', array(
'as' => 'post-quiz',
'uses' => 'QuizController#postQuiz'
));
When my controller is like the following:
public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
$data['success'] = true;
$data['message'] = $question;
echo json_encode($data);
}
the ajax call works and it returns,
Object {success: true, message: "test question"}
but when I try posting data to the database using:
public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
DB::table('questions')->insert([
'question' => $question,
]);
}
I get the following from the console
POST http://localhost/leoschool-laravel5/public/create/quiz 500 (Internal Server Error)
and
Object {readyState: 4, responseText: "{"success":true,"message":"test question"}<!DOCTYPE htm…l>↵</div>↵↵ </div>↵ </body>↵</html>", status: 500, statusText: "Internal Server Error"}
What could be the problem? Thanks..
A good place to start is with Chrome Developer tools. Load your page with the tools open and fire the event that does the AJAX request.
Under the network tab of the tools, it will show you every request made and allow you to preview the response as if you were not using AJAX. This will show you the laravel stack trace. I think the problem is that you're using facades and they're not namespaced correctly.
Change your controller function to this and see if it works:
public function postQuiz()
{
if(\Request::ajax()) {
$question = \Request::get('question');
\DB::table('questions')->insert([
'question' => $question,
]);
}
With the above instruction on how to use dev tools and with the corrected code, you should be able to fix your problem. A better way to write this code would look like this though:
// assuming you have these models setup
// this uses dependency injection
public function postQuiz(Request $request, Question $question)
{
if($request->ajax()) {
$newQuestion = $request->get('question');
//add fields here to create new question with
$question->create([ /*stuff*/ ]);
}
I want to create a section in my site, where a user has a few simple update buttons.
Each of these update buttons will be going to the server, and will do a long crunching behind the scene.
While the server crunches data, I want the user to have a some kind of progress indicator, like progress bar or textual percentage.
I'm using jQuery as my JavaScript library, and CodeIgniter (PHP) as the server-side framework, if it's important...
What I was thinking about is using PHP's flush() function to report progress status to jQuery, but I'm not sure that jQuery's Ajax functions are reading the output before it's complete...
So any advice/explanation would be useful and helpful!
I'm going to give you an example using WebSync On-Demand, but the same approach would work regardless of your choice of server.
Here's what you do. First, kick off the long-running operation somehow; your user clicks the button to start this process (I'm going to assume an Ajax call, but whatever works), and you return to them some sort of identifier, we'll call that 'myId', give it a value of '1'. Whether you do that by invoking a process of some sort, etc, is up to you.
Then, in your callback from that invocation, you would write something like so:
var myId = 1; // this would be set somewhere else
client.initialize('api key');
client.connect();
client.subscribe({
channel: '/tasks/' + myId,
onReceive: function(args){
// update the progress bar
myProgressBar.update(args.data.progress);
}
});
What that'll do is subscribe your client to receive notification about updates to the task, so all that's left is to push out the updates, which you'd do in whatever process is actually running the task. That would look like (in PHP, using the SDK):
$publisher = new Publisher(
"11111111-1111-1111-1111-111111111111", // your api key again
"mydomain.com" // your domain
);
// publish data
$response = $publisher->publish(array(
array(
'channel' => '/tasks/' . $myId, //comes from somewhere
'data' => (object) array(
'progress' => '45' //45% complete
)
)
));
// success if empty (no error)
$success = empty($response);
That's it; as updates occur, they'll push out to your client in real-time.
It's pretty hard to get this right. What we've settled on for our system is a "faked" progress bar - it just animates over and over (which since it is an animated gif, you might expect!).
An alternative would be to submit to one script, and have that processing in the background (and outputting progress to a file) while making an Ajax request to another script whose only responsibility is to read that progress file and return how far through the process you are. This would work - it feels a little bit kludgy, but it would at least solve your immediate problem.
I know very little about Comet or the likes, so this is purely based on my current understanding.
3 years late, but here's a solution I came up with. Bonus: It works in IE7+
Uses:
jQuery 1.9.1
jQuery UI 1.10(quick dialog box and progress bar)
Remy's EventSource Polyfill
JSON2 polyfill
The event table:
create table updates(
evt_id int unsigned not null auto_increment,
user_id int unsigned not null,
evt_type enum('start','update','finish') not null,
evt_msg varchar(255) not null,
primary key (evt_id)
)
The HTML:
<?php
include 'libconfig.php';
session_write_close();
if(count($_POST)){
$db=db_get_connection();
$stm=new PDOStatementWrapper(db_prepare($db,'INSERT INTO bupdates VALUES (:event_id,:user_id,:type,:message)'));
if($stm->run(array(
':event_id'=>0,
':user_id'=>App::user()->getId(),
':type'=>$_POST['type'],
':message'=>$_POST['message']
)))echo 'Inserted';
return;
}
?>
<!doctype html>
<html>
<head>
<title>tester</title>
<link rel=stylesheet href="s/jquery-ui-1.10.3.custom.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="js/eventsource.js"></script>
<script src="js/json2.js"></script>
<script>
var MixerStatusMonitor=(function(){
var _src=null,
_handler={
onStart:function(e){
MixerStatus.setMax(parseInt(e.data));
},
onUpdate:function(e){
var data=JSON.parse(e.data);
MixerStatus.setValue(parseInt(data.progress));
MixerStatus.setStatus(data.message);
},
onFinish:function(e){
//var data=JSON.parse(e.data);
MixerStatus.hide();
_src.close();
}
};
return {
init:function(){
if(_src)_src.close();
_src=new EventSource('/daemon/updates.php?type=b');
_src.addEventListener('update',_handler.onUpdate,false);
_src.addEventListener('start',_handler.onStart,false);
_src.addEventListener('finish',_handler.onFinish,false);
MixerStatus.show();
}
};
})();
var MixerStatus=(function(){
var dialog=null,pbar=null,text=null;
return {
init:function(){
dialog=$('#buildStatus').dialog({autoOpen:false});
pbar=$('#buildStatus .progress').progressbar({value:false});
text=$('#buildStatus .text').progressbar();
},
setStatus:function(txt){
text.html(txt);
},
setMax:function(val){
pbar.progressbar('option','max',val);
},
setValue:function(val){
pbar.progressbar('option','value',val);
},
show:function(){
dialog.dialog('open');
},
hide:function(){
dialog.dialog('close');
}
};
})();
$(document).ready(function(){
MixerStatus.init();//build the UI
$('#updater').on('submit',function(){
$.ajax({
type:'post',
url:'test-updates.php',
data:$('#updater').serialize(),
beforeSend:function(){
if($('#updater select[name=type]').val()=='start'){
MixerStatusMonitor.init();
}
}
});
return false;
});
});
</script>
</head>
<body>
<p>Start event sets the max
<p>update event: {"progress":"","message":""}
<p>finish event: {"progress":"","message":""}
<form id=updater>
message: <input type=text name=message value="15"><br>
event type: <select name=type>
<option value=start>start</option>
<option value=update>update</option>
<option value=finish>finish</option>
</select><br>
<button>send message</button>
</form>
<div id=buildStatus title="Building">
<div class=text></div>
<div class=progress></div>
</div>
<div id=messages></div>
</body>
</html>
The PHP:
<?php
header('Content-Type: text/event-stream');
define('TYPE_BROADCAST','b');
define('MAX_FAILURES',30);//30 seconds
define('MAX_WAIT',30);//30 seconds
define('MAX_START_WAIT',6);//30 seconds
/*
* URL arguments:
* type
*/
include '../libconfig.php';
session_write_close();
if(!App::loggedIn() || !App::user()){
printEvent(0,'finish','Login session has expired.');
}
if($_GET['type']==TYPE_BROADCAST){//not needed;specific to the app I am creating
$db=db_get_connection();
$stm=new PDOStatementWrapper(db_prepare($db,'SELECT * FROM updates WHERE user_id=:user_id AND evt_id>:last_id'));
$args=array(':user_id'=>App::user()->getId(),':last_id'=>0);
$stm->bindParam(':user_id',$args[':user_id'],PDO::PARAM_INT);
$stm->bindParam(':last_id',$args[':last_id'],PDO::PARAM_INT);
$failures=0;
$nomsg=0;
if(!isset($_SERVER['HTTP_LAST_EVENT_ID'])){
$start=new PDOStatementWrapper(db_prepare($db,'SELECT * FROM updates WHERE user_id=:user_id ORDER BY evt_id DESC'));
$start->bindValue(':user_id',$args[':user_id'],PDO::PARAM_INT);
$startwait=0;
while(1){
if($startwait>MAX_START_WAIT){
printEvent(0,'finish','Timed out waiting for the process to start.');
return;
}
sleep(5);
$startwait++;
if(!$start->run()){
printEvent(0,'finish','DB error while getting the starting event.');
return;
}
while($start->loadNext()){
if($start->get('evt_type')=='finish')continue 2;
if($start->get('evt_type')=='start')break;
}
if($start->get('evt_type')=='start'){
$args[':last_id']=$start->get('evt_id');
printEvent($start->get('evt_id'),'start',$start->get('evt_msg'));
break;
}
}
}else
$args[':last_id']=$_SERVER['HTTP_LAST_EVENT_ID'];
if($args[':last_id']===0){
printEvent(0,'finish','ll');
exit;
}
while(1){
sleep(1);
if(!$stm->run()){
$failures++;
if($failures>MAX_FAILURES){
printEvent(0,'finish','Max failures reached.');
break;
}
}
if($stm->loadNext()){
$failures=0;
$nomsg=0;
do{
if($stm->get('evt_type')=='finish')break;
$args[':last_id']=$stm->get('evt_id');
printEvent($stm->get('evt_id'),$stm->get('evt_type'),$stm->get('evt_msg'));
}while($stm->loadNext());
if($stm->get('evt_type')=='finish'){
printEvent($args[':last_id'],'finish',$stm->get('evt_msg'));
break;
}
}else{
$nomsg++;
if($nomsg>MAX_WAIT){
exit;//TODO: test
}
}
}
}else{
printEvent(0,'close','Unknown event type.');
}
function printEvent($id,$name,$data){
echo "id: $id\nevent: $name\n";
if(is_array($data)){
foreach($data as $datum)
echo "data: $datum\n";
echo "\n";
}else
echo "data: $data\n\n";
flush();
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest')exit;//ajax request. Need to kill the connection.
}
In case you were wondering about PDOStatementWrapper the source for it is here. Sorry it doesn't include anything integrated with CodeIgniter.