AJAX: send data from webpage to PHP API - javascript

I'm trying to send data to the server API from a webpage but it keeps falling to
'No Connection!' as you will see in the code.
Note:The server, database and the API are working, because I also use it on a phone application that do the same as I'm trying to do here which is post an event to the database.
Here is the webpage code:
function onAddEvent(){
var title = document.getElementById("title").value;
var desc = document.getElementById("desc").value;
var date = document.getElementById("date").value;
var userid = localStorage.getItem("userid");
$.ajax({
url: API_URL,
type: 'POST',
data: {eventname: title, eventdate: date, eventdesc: desc, user_id: userid},
async: true, // set the property here
success: function(data) {
if(data.result == "success"){
alert("Add Event Successfully!");
}
else{
alert("Can't add event");
}
},
error: function(xhr, error) {
//It is falling here
alert('No Connection!');
}
});
}
And here is the PHP API that it will connect to:
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}

Remove the code from the function or try calling the function in the API.
//Call the function from your API
addevent();
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}

Related

Converting fetch to ajax for use in stripe integration

I have a problem with fetch on mobile google chrome. I want to try to convert it to ajax. I am using it for stripe implementation in php. This what I have done using fetch :
var createCheckoutSession = function(planId) {
var plan = {
plan_id: planId
};
var data = new FormData();
// we call the create my session page by providing a Plan ID which in turn will return a session object whose ID will be useful later on to redirect to checkout.
data.append( "plan", JSON.stringify( plan ) );
return fetch("/create-my-session", {
method: "POST",
body: data
}).then(function(result) {
console.log(result);
return result.json();
});
};
in create-my-session page I have this code:
$stripeService = new StripeService();
$plan = json_decode($_POST["plan"]);
$planId = $plan->plan_id;
$session = $stripeService->createCheckoutSession($planId);
echo json_encode($session);
The above code is executed on click of this button :
$('#subscribe').on('click',function(e){
createCheckoutSession(MyChosenPlanID).then(function(data) {
stripe.redirectToCheckout({
//we redirect the user to a checkout page hosted by stripe that uses the session ID returned above
sessionId: data.id
}).then(handleResult);
});
});
what i have done so far in converting to ajax:
var createCheckoutSession = function(planId) {
var plan = {
plan_id: planId
};
var datastream = new FormData();
datastream.append( "plan", JSON.stringify( plan ) );
$.ajax({
type: "POST",
url: "/create-my-session",
data: {
'info': datastream,
},
dataType: 'json',
success: function(data){
var sessionobj = data;
},
error:function(response)
{
console.log("Data sending failed");
console.log(response);
}
});
return sessionobj ;
}).then(function(result) {
console.log(result);
return result.json();
});
};
and I kept everything else as it is.

post request on form with validation

i built a registration form and validated it using javaScript. but i want after a user filled the form, it should post to the server. i am confused on where to place my httpRequest function. i don't know if its after validation or inside the validation function
This is my validation function
function formregister(e){
if (first_name.value=== "" || last_name.value=== "" || user_id.value==="" || id_type.value=== ""
|| id_no.value=== "" || address.value==="" || !terms.checked) {
var fPassResult = '1';
} else{
var fPassResult = '0';
}
if(fPassResult === "1") {
window.location = "register.html";
}else{
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}
).then(function(){
window.location="Login.html";
})
}
e.preventDefault();
};
**And this is my post request function**
function registerationApiCall(e){
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
fetch("jehvah/api",{
type : 'POST',
data : data,
dataType : 'JSON',
encode : true,
success: function (response, status, xhr) {
if (result==="OK") {
console.log("success");
}else{
console.log("bad");
}
},
error: function (xhr, status, error) {
console.log("something went wrong");
}
});
}
Please kindly check my post request function, i dont know if i am doing it the right way
Hi ✌ when fPassResult === "0" in this case inside else{} call registerationApiCall()
you tell the user it's a success after you get OK from the server which is Asynchronous call
& inside fetch response you call swal.fire
for this code to work your server when checks the database & every thing is ok returns a msg like this {"msg":"OK"}
CODE:
else{
registerationApiCall()
}
function registerationApiCall becomes
fetch('jehvah/api',
{ method: 'POST',headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
if (result.msg="OK") {
console.log("success");
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}).then(function(){window.location="Login.html";})
}else{ console.log("usres exsists / etc");}
})
.catch((error) => {
console.log("something went wrong");
});
}
Also in the request payload you sent a group of strings not the variables containing the form values
Here
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
Change that to
var data = {
"user_id":user_id.value,
"user_pin": user_pin.value,
"first_name":first_name.value,
"last_name":last_name.value,
"address":address.value
};
Looking at the fetch documentation (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), success and error does not exists.
The fetch function returns a Promise, so you can handle results as any Promise should do:
fetch("jehvah/api", {
method: 'POST',
body : JSON.stringify(myDataObject)
})
.then(blob => blob .json())
.then(result => console.log('Success!!))
.catch(e => console.log('Failure :('))

Stripe - Payment Intents (3d secure issue)

I did implement Payment intents on my website and now works perfectly with this testing card 4242 4242 4242 4242, but for other cards that need 3d secure methods, I take this error "Invalid PaymentIntent status".
the Code that I have used is the same standard code that exists on the Stripe documentation-flow enriched with some code to manage mysql, emails, metadata etc.
Where do I go wrong? Thanks in Advance.
simplified js code connected to index.php
var stripe = Stripe('pk_test_xxx');
var elements = stripe.elements();
var cardElement = elements.create('card', {style: style});
cardElement.mount('#card-element');
var cardholderName = document.getElementById('cardholder-name');
var cardButton = document.getElementById('card-button');
var amount = $('#amount').val();
cardButton.addEventListener('click', function(ev) {
ev.preventDefault();
stripe.createPaymentMethod('card', cardElement, {
billing_details: {name: cardholderName.value}
}).then(function(result) {
if (result.error) {
} else {
$body.addClass("loading");
fetch('https://test.com/server.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payment_method_id: result.paymentMethod.id,
amount: amount
})
}).then(function(result) {
// Handle server response (see Step 3)
result.json().then(function(json) {
handleServerResponse(json);
})
});
}
});
});
function handleServerResponse(response) {
if (response.error) {
} else if (response.requires_action) {
stripe.handleCardAction(
response.payment_intent_client_secret
).then(function(result) {
if (result.error) {
} else {
// The card action has been handled
// The PaymentIntent can be confirmed again on the server
fetch('https://test.com/server.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payment_method_id: result.paymentMethod.id,
amount: amount
})
}).then(function(confirmResult) {
console.log(confirmResult);
return confirmResult.json();
}).then(handleServerResponse);
}
});
} else {
}
}
simplified code on server.php
<?php
# vendor using composer
require_once('stripe6400/init.php');
\Stripe\Stripe::setApiKey('sk_test_xxx');
header('Content-Type: application/json');
# retrieve json from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$paymentid = $json_obj->payment_method_id;
$amount = $json_obj->amount;
$intent = null;
try {
if (isset($json_obj->payment_method_id)) {
# Create the PaymentIntent
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $json_obj->payment_method_id,
'amount' => $json_obj->amount,
'payment_method_types' => ["card"],
'currency' => 'gbp',
'confirmation_method' => 'manual',
'confirm' => true,
]);
}
if (isset($json_obj->payment_intent_id)) {
$intent = \Stripe\PaymentIntent::retrieve(
$json_obj->payment_intent_id
);
$intent->confirm();
}
generatePaymentResponse($intent);
} catch (\Stripe\Error\Base $e) {
# Display error on client
echo json_encode([
'error' => $e->getMessage()
]);
}
function generatePaymentResponse($intent) {
if ($intent->status == 'requires_action' &&
$intent->next_action->type == 'use_stripe_sdk') {
echo json_encode([
'requires_action' => true,
'payment_intent_client_secret' => $intent->client_secret
]);
} else if ($intent->status == 'succeeded') {
Stripe\Customer::create([
"email" => $email,
"name" => $customer_name,
"source" => "tok_visa" // obtained with Stripe.js
]);
echo json_encode([
"success" => true
]);
} else {
# Invalid status
http_response_code(500);
echo json_encode(['error' => 'Invalid PaymentIntent status']);
}
}
?>
It looks like you might have the same error I just had. The status of the response from stripe is requires_source_action not requires_action so your if statement falls through to Invalid PaymentIntent status.
// change this
// $intent->status == 'requires_action'
// to this
$intent->status == 'requires_source_action'
In my case I'm checking for both so my code is ready for when I do update the stripe SDK.
https://stripe.com/docs/payments/payment-intents/quickstart#confirm-again
(line 33 in the code)
Also on Customer::create your source attribute "tok_visa" must be a real token.id from create token in javascript https://stripe.com/docs/stripe-js/reference#stripe-create-token

Delete a users post using ajax and js in laravel 5.4

I'm new to Laravel. I am trying to create a common social network.
Now I want to be able to delete a user's post. At the moment when you try to submit the form it loads the ajax
but can not delete the data.
Here is my code:
$("#_global_modal").delegate('#modal_form_delete', 'submit',
function(event)
{
// To stop a form default behaviour
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
})
.done(function(response){
if(response.delete == "success"){
window.location.href = response.redirect_route
}else{
console.log(response);
}
})
.fail(function(){
console.log("error");
})
.always(function(){
console.log("complete");
});
});
Route:
Route::post('delete','crude#delete')->name('delete');
My controller part:
public function delete(Request $request)
{
if($request->ajax()){
$user = Auth::user();
$user->post()->delete(['post' => $request->post]);
return response()->json([
'delete' => 'success',
'redirect_route' => route('profile')
]);
}else{
return response()->json([
'delete' => 'ERROR',
'ERROR_MSG' => 'ERROR MSG'
]);
dd("Sorry you have to send your form information by using ajax
request");
}
}
So how can I solve this problem?
Your delete statement is wrong.
public function delete(Request $request)
{
if($request->ajax()) {
Post::where('id', $request->post)
->where('user_id', auth()->id())
->delete();
return response()->json([
'delete' => 'success',
'redirect_route' => route('profile')
]);
}
return response()->json([
'delete' => 'ERROR',
'ERROR_MSG' => 'ERROR MSG'
]);
}

AJAX call and getting return data in Node

I'm wanting to make an ajax call from the client to the backend. I get a successful call from the success function, however, I can't understand how I get data from the server to return from the client.
currently my error trying to use res.send is:
Error: Can't set headers after they are sent.
AJAX
function getProfessorResults() {
var textData = $('#inputsm').val();
var data = {user:"gopal#gmail.com"};
$.ajax({
url: 'http://localhost:3000',
data: { theme: "somevalue", snippet: { name: "somename", content: "somevalue" } },
method: 'POST',
async: false,
cache: false,
timeout: 5000,
contentType: "application/json",
success: function(data) {
console.log("success");
},
complete: function(data) {
console.log("completed");
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown);
}
});
}
JS Backend
exports.home = function(req, res) {
function passList(profArray, callback) {
setTimeout(function () {
callback(profArray);
}, 1000);
}
function getProfs(teacher_name, successCallback) {
google.resultsPerPage = 10
var nextCounter = 0
google(teacher_name, function (err, res){
if (err) console.error(err)
var teacher_results = []; //Hold all the teachers returned from the function
for (var i = 0; i < res.links.length; ++i) {
var link = res.links[i];
if (!link.title.includes('Add') || !link.title.includes('RATINGS') || !link.title.includes("Hint")) {
teacher_results.push(link.title);
}//End if for comparisons ||
} //End For
successCallback(teacher_results);
}); //End google function
teacher_results = ['tester1', 'tester2'];
successCallback(teacher_results);
} //End searchForProfessor
getProfs(teacher_name, function(data) {
prof_list = data;
console.log(prof_list);
return true;
});
if (req.method == 'POST'){
console.log("true");
// dataReceived = JSON.parse(req);
// console.log(dataReceived);
var obj = {
tid: 'ryan'
};
res.send(JSON.stringify(obj));
}
res.render('home', {
profs: prof_list,
dataStuff : dataReceived
});
};
In the backend, you should have some route where your AJAX call lands. In there, you can invoke send on your response.
In node.js/express, this would look something like
app.get('/ajaxURL', function (req, res) {
res.send('I want this string to return to the client');
});
To access the data from the frontend, access it in your AJAX callback:
$.ajax({url: '/ajaxURL'}).done(function (data) {
console.log(data);
});
I am not getting the context properly but you can figure out by this example .
Sending data from server
response.send("Your data");
Access this data in your client in success method of AJAX:
success:function(data){console.log(data)};

Categories