React hook failed to call php server via ajax - php

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.

Related

React application failing to fetch once publicly hosted

can anyone help me with the following issue? This is all very new to me so I'm sorry for any incoveniences. I'm creating a ChatGPT tool which takes a text inputs from the user in the front end then passes that data into the back end which sends the user input to an open OpenAI API layer. The back end then receives a response back from the OpenAI layer and stores the text response into a text array and writes it back to the front end into a standard text area.
The website runs perfectly when it is hosted locally on localhost:3001 and port:3001. My issue stems when I deploy the website to firebase and attempt to submit a form request on another machine and different network it does not writing any text to the textarea. Below I have provided my code. I believe the issue has something to do with the localhost code in the handleSubmit function or could even be in the back end script i'm very unsure and would really appreciate any help I can get thanks to get this running publicly. Thanks for your time :)
Front End (App.js)
import React, { useState } from 'react';
import './App.css';
function App() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:3001', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({message}),
})
.then((res) => res.json())
.then((data) => setResponse(data.message));
};
return (
<body>
<div className="App">
<form onSubmit={handleSubmit}>
<div class="section"></div>
<header>
<nav>
<ul class="nav_links">
<li><a href='#'>Home</a></li>
<li><a href='#'>Pricing</a></li>
<li><a href='#'>About</a></li>
<li><a href='#'>Contact</a></li>
</ul>
</nav>
<button class="login">Login</button>
</header>
<input type="text" id="topic"
value={message}
onChange={(e) => setMessage(e.target.value)}
></input>
<textarea id="textarea" value={response} />
<div> <button id="generate" type="submit">Generate</button> </div>
</form>
</div>
</body>
);
}
Back End (Index.js)
const OpenAI = require('openai');
const { Configuration, OpenAIApi } = OpenAI;
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3001;
const configuration = new Configuration({
organization: "org-kEBxx4hVwFZ",
apiKey: "sk-jmYuTSCZvxCjidnbTpjFT3Blbk",
});
const openai = new OpenAIApi(configuration);
app.use(bodyParser.json());
app.use(cors());
app.post('/', async (req, res) => {
const { message } = req.body;
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: `${message}`,
max_tokens: 1000,
temperature: 0,
});
console.log(response.data)
if(response.data.choices[0].text){
res.json({message: response.data.choices[0].text})
}
});
app.listen(port, () => {
console.log("Listening...")
});
Since http://localhost:3001 is hardcoded into your code, even when you deploy it in production, the production website will still try to make a request to localhost:3001. To fix this, you need to dynamically set the url based on whether the code is in development or production. The recommended way to do this is using environment variables: https://create-react-app.dev/docs/adding-custom-environment-variables/, where you'd set the env variable to localhost:3001 during development and the url of the production server in production.

How to make Phonegap connect to localhost

I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.
html form and ajax call:
<form id="form1">
<input type="text" id="email" />
<input type="password" id="password" />
<input type="submit" name="login" id="login" value="Login">
</form>
<script type="text/javascript">
$("form").submit(function(){
var data= ("#form1").serialize();
$.post("http://localhost/securityapp/login.php",data,function(response){
alert(response);
});
});
</script>
php file:
<?php
include 'db.php';
session_start();
if ($_POST ) {
echo $_POST;
}
?>
Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined
This is how I solved this issue:
created a table on a database that holds the current URL/IP of the server
Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server
I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app
check-url.php
header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
require 'db.php';
$query= "SELECT url FROM settings";
$query= mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($query);
$row= $row['url'];
echo $row; //current IP exmaple:http://127.0.0.1:80/
connection.js
//check current server ip from database
export function check_url(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
httpRequest.send();
}
So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:
<script type="module">
import {check-url} from './connection.js';
check-url(function(result) {
var currentIP= result;
$.ajax({
type:"POST",
url: currentIP + "projectapp/login.php",
data:data,
success: function(data){
//do something
}
});
});
</script>
Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.

500 internal server error while posting data to database with laravel 5 and ajax

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*/ ]);
}

JQuery -> Ajax -> PHP -> 500 internal server error

I am struggling with a 500 internal server error. I have made just a basic script to test, but its just getting 500 anyways. Do you see a typo or logic errors? I am to blind right now to see an error.
AJAX
$("#select_kjede").change(function(){
var kjede = $("#select_kjede option:selected").val();
$.ajax({
type: "POST",
url: "bestilling/controller.php",
data: {
kjede: kjede
}
})
.done(function( msg ) {
alert(msg);
});
});
PHP
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$message = $_POST["kjede"];
echo "<script type='text/javascript'>console.log("."OLOL ".$message."</script>";
}
In the PHP-script i have tried a numerous methods, included if(isset($_POST['kjede'])
EDIT:
In Chrome console under the error -
send
b.extend.ajax
(anonymous function)
b.event.dispatch
v.handle
How can i console out the server errors?
I wanted to ask what your form looks like. But I could not comment. Your code works fine with the following form.
<form id="select_kjede">
<select>
<option>option_one</option>
<option>option_two</option>
<option>option_three</option>
</select>
<input type="submit" value="save"/>
</form>

Jquery Ajax no response

When I try to get the response from a php file using Jquery ajax, I just get (an empty string) (Accdg. to Firebug console using console.log(data))
Here's the Html code:
<form action="test.php" method="POST" id="ajax">
<input type="text" name="field" />
<input type="submit" value="submit" name="submit" />
</form>
Here's the Jquery code:
$('#ajax').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'test.php',
cache: false,
success: function(data) {
alert(data);
}
});
return false;
});
And the PHP code:
if ($_POST['submit'] == "submit")
{
echo 'Got your request';
}
Just basic. What frustrates me is that it's straightforward, I've done some research and still it doesn't work. I also want it to be as simple as possible.
Please enlighten me.
Don't check to see if you're in a POST situation by checking for fieldnames. That's incorrect - you might change your client-side form names and forget to update the PHP check.
The 100% reliable method is to use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Got your request";
}
However, since you just want to see if the server got pinged at all by your ajax call, why not do:
<?php
echo "Got your ", $_SERVER['REQUEST_METHOD'], " request";
Which'd just return Got your POST request or Got your GET request, etc...
As well, check your server log (or use HTTPFOX/Firebug Net tab, etc...) to see if that ajax request is actually going out and being received by the server.
The problem with the serialize() method is that it doesn't include the name of the button parameter which you use in your php script (submit=submit parameter). It doesn't do it because it doesn't know which button was clicked. This parameter is only included by the browser when you submit the form normally.
So one possibility is to manually attach this parameter as query string parameter:
url: 'test.php?submit=submit',
and in your PHP script:
if ($_GET['submit'] == "submit")
{
echo 'Got your request';
}

Categories