FETCH JavaScript PHP process the data on the server sent with fetch - javascript

I have this doubt of how to process the data brought from my form, I am using javascript with a fetch to receive the data of the form, but I have the doubt of how I should process them in php, nor is the click event of the send button working, the problem is that the server seems not to be receiving the array sent from javascript with the data, agradesco if you give me any source to delve into the topic of fetch api, I am new to javascript and php
my Javascript
registrar.addEventListener("click", () => {
fetch("../add.php", {
method: "post",
body: new FormData(frm) //frm es el id del formulario
}).then(response => response.text()).then
(response => {
// console.log(response);
// si la respuesta sel servidor es "ok" arroja una alerta personalizada
if (response == "ok") {
Swal.fire({
icon: 'success',
title: 'Registrado',
showConfirmButton: false,
timer: 1500
})
frm.reset();
}
}
)
})
<form action="" method="post" id="frm">
<div class="form-group">
<br>
<div class="form-group">
<div class="form-group">
<input type="text" name="name_usu" id="name_usu" class="form-control form-control-md" placeholder="Nombre completo" required >
</div>
<input type="text" name="phone_usu" id="phone_usu" class="form-control form-control-md" placeholder="Numero de teléfono" required>
</div>
<input type="email" name="nom_usu" id="nom_usu" class="form-control form-control-md" placeholder="Email" required></div>
<input type="text" name='torreApto' id="Torre_apto" class="form-control form-control-md" placeholder="Torre y apartamento" required>
<label for="FormControlSelect1" class="text-light">Escoja tipo de residente</label>
<select class="form-control" name="sel_apto" id="sel_apto" required>
<option selected>Propietario</option>
<option selected>Arrendado</option>
<option selected>Otro</option>
</select>
<div class="form-group">
<label for="Textarea1" class="text-light">Mensaje a enviar</label>
<textarea class="form-control" name="mensaje" id="Textarea1" rows="3"></textarea>
</div>
<br>
<input type="button" class="btn btn-outline-light btn-block border-light text-light font-weight-bold" value="registrar" id="registrar">
</form>
addRegister.php
enter if (isset($_POST)) {
$nombre = $_POST['name_usu'];
$telefono = $_POST['phone_usu'];
$email = $_POST['nom_usu'];
$torreApto = $_POST['torreApto'];
$arrendado = $_POST['sel_apto'];
$mensaje = $_POST['mensaje'];
require("connect.php");
// script guardando en la base de datos
$query = $con->prepare("INSERT INTO informacion(nombre,telefono,email,torreApto,arrendado,mensaje) VALUES (:nom, :tel, :ema, :torr, :arr, :men)");
$query->bindParam(":nom", $nombre);
$query->bindParam(":tel", $telefono);
$query->bindParam(":ema", $email);
$query->bindParam(":torr", $torreApto);
$query->bindParam(":arr", $arrendado);
$query->bindParam(":men", $mensaje);
//ejecuta el script
$query->execute();
$con = null;
echo "ok";
}

Try to add
$_POST = file_get_contents('php://input');
at the beginning of your file.

You are not initializing the FormData correctly. To fill it with the data of a form you have to pass in a reference to the form. Currently you are passing in an undefined variable, that just happens to be the same as the ID of the form.
You need to get a reference to the form using, for example, getElementById:
new FormData(document.getElementById("frm"))

Related

Can't send a submit fetch request

I searched for a long time without results about this question. The problem is that when I try to send an asynchronous request to another web page I don't have any response. I think the problem is where the FormData takes its values but I don't know why... Here is the code:
const addBooking_form = document.getElementById("form_addResa");
addBooking_form.addEventListener("submit", (event) => {
event.preventDefault();
// Send asynchronous request to /api/booking/new
const formData = new FormData(addBooking_form);
const searchParams = new URLSearchParams(formData);
console.log(formData);
console.log(searchParams);
const asyncReqAdd = fetch("api/booking/new", {
method: "POST",
body: formData
});
asyncReqAdd.then(response => {
return console.log(response.text() == 'undefined' ? 'Fetch reponse <=> undefined' : response);
}).then((response) => {
console.log(response)
table.innerHTML = response;
});
return console.log('New booking submited');
})
I know that the link and the form id are correct...
HTML FORM :
<form id="form_addResa">
<div class="fieldset flexCol-around">
<label for="input_lieu">Lieu *</label>
<select id="input_lieu" name="place">
<option value="none">< Séléctionner un lieu ></option>
<option value="Salammbô">Salammbô</option>
<option value="Pergola">Pergola</option>
<option value="Salon Jaune">Salon Jaune</option>
<option value="1001 Bougies">1001 bougies</option>
</select>
<div class="flexRow-around">
<div class="flexCol-around">
<label for="input_date">Date *</label>
<input id="input_date" type="date" name="date">
</div>
<div class="flexCol-around">
<label for="input_time">Heure *</label>
<input id="input_time" type="time" name="time">
</div>
</div>
<label for="input_nom">Nom *</label>
<input id="input_nom" type="text" name="name">
<label for="input_prenom">Prénom *</label>
<input id="input_prenom" type="text" name="firstName">
</div>
<div class="fieldset flexCol-around">
<label for="input_couverts">Nombre de couverts *</label>
<input id="input_couverts" type="number" name="coverts">
<label for="input_intExt">Client interne / externe *</label>
<select name="intExt" id="input_intExt">
<option value="ext">Externe</option>
<option value="int">Interne</option>
</select>
<label for="input_contacte">Contacter le client *</label>
<input id="input_contacte" type="text" placeholder="Numéro de chambre / téléphone / E-mail" name="contact">
</div>
<div class="fieldset">
<textarea id="input_note" placeholder="Note :" name="notes"></textarea>
</div>
<div class="flexRow-around">
<input type="reset" value="Annuler" style="background: white;">
<input type="submit" onclick="unselectBooking();">
</div>
</form>
Can you give me a solution for this?
You could use async/await with a try catch block to see what goes wrong.
Something like this (pseudo):
addBooking_form.addEventListener("submit", async (event) => {
event.preventDefault();
const { date, time, name, place } = Object.fromEntries(new FormData(event.target))
try {
const respone = await fetch("api/booking/new", {
method: "POST",
body: { date, time, name, place }
});
const data = await response.json()
// do something with data
console.log(data)
} catch(e) {
// do some error handling
console.log('error', e)
}
})
Update: you can use Object.formEntries on FormData to get the values of your named input fields and then pass them to the body. This way, you should have valid JSON data.
I also removed the element selector since you already got the element via event

Why my Ajax request isn't working with post method?

I come to ask for help because I have a problem that persists for three days and I can't understand where the problem is. I have a form on an HTML page here :
<form id="contactformpage">
<div class="messages"></div>
<div class="form-group row">
<label for="societepage" class="col-sm-6 col-form-label">Société</label>
<div class="col-sm-6 champ">
<input type="text" name="societe" class="form-control" id="societepage" placeholder="Nom de la société" aria-describedby="indicsocietepage">
<small id="indicsociete" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="adressepage" class="col-sm-6 col-form-label" >Adresse</label>
<div class="col-sm-6 champ">
<input type="text" name="adresse" class="form-control" id="adressepage" placeholder="Adresse">
</div>
</div>
<div class="form-group row">
<label for="codepostaletvillepage" class="col-sm-6 col-form-label" >Code postal & ville</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="codepostaletville" id="codepostaletvillepage" placeholder="Code postal & ville">
</div>
</div>
<div class="form-group row">
<label for="contactpage" class="col-sm-6 col-form-label">Nom du contact</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="contact" id="contactpage" placeholder="Nom du contact">
</div>
</div>
<div class="form-group row">
<label for="telephonepage" class="col-sm-6 col-form-label">Téléphone</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="téléphone" id="telephonepage" placeholder="Numéro de téléphone" aria-describedby="indictelephonepage">
<small id="indictelephonepage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="mailpage" class="col-sm-6 col-form-label">Adresse mail</label>
<div class="col-sm-6 champ">
<input type="email" class="form-control" name="mail" id="mailpage" placeholder="Entrez votre adresse mail" aria-describedby="indicmailpage">
<small id="indicmailpage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="selecmarque" aria-describedby="indicmarquepage"> Marque du véhicule </label>
<div class="col-sm-6 champ">
<select class="form-control" name="marque" style="height:20px;padding-bottom:0;padding-top:1;" onchange="generechoixmodele('selecmarque','apreschoixmarquepage','apreschoixmodelepage','nommodelepage','choixmodelepage','choixtypepage');" id="selecmarque">
<option selected> Séléctionnez </option>
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmarquepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix de la marque -->
<label class="col-sm-6 col-form-label" for="apreschoixmarquepage" aria-describedby="indicmarque" id="nommodelepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="modele" style="height:20px;padding-bottom:0;padding-top:1;" id="choixmodelepage" onchange="generechoixtype('selecmarque','choixmodelepage','apreschoixmodelepage','nomtypepage','choixtypepage');">
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmodelepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix du modèle -->
<label class="col-sm-6 col-form-label" for="apreschoixmodelepage" aria-describedby="indicmarque" id="nomtypepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="type" style="height:20px;padding-bottom:0;padding-top:1;" id="choixtypepage">
</select>
</div>
</div>
<p> Je souhaite recevoir les catalogues suivants (dynamique)</p>
<div id="choixcataloguepage">
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="commentairepage">Commentaire</label>
<div class="col-sm-6 champ">
<textarea class="form-control" name="commentaire" id="commentairepage" rows="1"></textarea>
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-6 col-form-label">Captcha</label>
<div class="col-sm-6 champ">
<h6> Captcha à rajouter après </h6>
</div>
</div>
<input type="submit" class="btn" id="submitpage">
</form>
And when I click on the button of this form, I send the data entered by the user thanks to an Ajax request on a php page:
$(document).ready(function(){
$("#submitpage").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'sendform.php',
dataType: "JSON",
data: {
societe : $("#societepage").val(),
adresse : $("#adressepage").val(),
codepostaletville : $("#codepostaletvillepage").val(),
contact : $("#contactpage").val(),
telephone : $("#telephonepage").val(),
mail : $("#mailpage").val(),
marqueclient : $("#selecmarque").val(),
modeleclient : $("#choixmodelepage").val(),
typeclient : $("#choixtypepage").val(),
commentaire : $("#commentairepage").val()
},
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contactformpage').find('.messages').html(alertBox);
// empty the form
$('#contactformpage')[0].reset();
}
}
})
});
});
I know it's possible to do $(this).serialize() for forms directly but I'd like to do that already. Here is the PHP script in question, so I send my data with the POST method, the problem is that this script tells me all the time "Form is empty" which means that the data was not sent with POST (since $ _POST is empty). And when I try to make an echo ($_SERVER['HTTP_X_REQUESTED_WITH']), the php script returns an empty string, which means that the Ajax request was not made.
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
AND ALSO SMTP TO SEND THE EMAILS
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer/PHPMailer-master/src/Exception.php';
require 'PHPMailer/PHPMailer-master/src/SMTP.php';
require 'PHPMailer/PHPMailer-master/src/OAuth.php';
require 'PHPMailer/PHPMailer-master/src/POP3.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'lyes.tifoun#hotmail.fr';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'lyestfn#gmail.com';
$sendToName = 'Lyes Tifoun';
// subject of the email
$subject = 'New message from contact form';
// smtp credentials and server
$smtpHost = 'smtp.gmail.com';
$smtpUsername = 'nom_utilisateur';
$smtpPassword = 'mdp';
$fields = array('societe' => 'Société', 'adresse' => 'Adresse', 'codepostaletville' => 'Code postal et ville', 'contact' => 'Nom du contact', 'téléphone' => 'Numéro de téléphone', 'mail' => 'Adresse mail', 'marque' => 'Marque du véhicule', 'modele' => 'Modèle du véhicule', 'type' => 'Type du véhicule', 'commentaire' => 'Commentaire');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
error_reporting(E_ALL & ~E_NOTICE);
try {
if (count($_POST) == 0) {
throw new \Exception('Form is empty');
}
$emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = gethostbyname($smtpHost);
$mail->Port = 587;
$mail->isHTML(true);
$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->Subject = $subject;
$mail->Body = 'test';//$emailTextHtml;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
$mail->Debugoutput = 'html';
if (!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (\Exception $e) {
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
I would like to understand why my request doesn't work because I don't think I made any syntax or other errors.
Here is the script used for the JQuery library in my HTML file.
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
And I use WAMPServer to run my site locally, I already did my research but could the problem come from there by chance?
Thank you in advance
I come back to you to inform you that my data is finally sent with $_POST as shown by the network panel:
enter image description here
I've also made a var_dump($_SERVER) and the $_SERVER['HTTP_X_REQUESTED_WITH'] value is "XML HTTPREQUEST" which indicates that the Ajax request has been launched. Now I have an other problem : I don't have a client-side response: currently the program seems to validate the condition if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') and I have an echo($encoded) in JSON format as shown below :
enter image description here
Therefore I should have a client-side response, which is not the case actually.
Thanks a lot for your responses and sorry for my bad english.

Ajax form submit doesn't work on 1 page

I've a form that I submit with JQuery AJAX. But after I clicked submit, my page is redirect to my form submit.php. I've tried almost everything, but I can't find the bug...
The PHP script is working fine. I only echo once,
HTML:
<form class="offerte-form" method="post">
<div class="col-sm-6">
<input type="text" class="name" id="naamofferte" name="naam" placeholder="Naam*" required="" style="border-radius: 4px;">
<input type="text" class="name" id="naambedrijf" name="naambedrijf" placeholder="Naam bedrijf" style="border-radius: 4px;">
<input type="text" class="name" id="adresofferte" name="adres" placeholder="Adres" style="border-radius: 4px;">
<input type="text" class="name" id="vestplaats" name="vestplaats" placeholder="Vestigingsplaats" style="border-radius: 4px;">
<input type="text" class="name" id="postcode" name="postcode" placeholder="Postcode" style="border-radius: 4px;">
<input type="email" class="name" id="emailofferte" name="email" placeholder="Emailadres*" required="" style="border-radius: 4px;">
</div>
<div class="col-sm-6">
<input type="text" class="name" id="telnrofferte" name="telnr" placeholder="Telefoonnummer*" required="" style="border-radius: 4px;">
<select class="name" name="offertevoor" id="offertevoor" style="border-radius: 4px;" required>
<option value="none">
Selecteer een optie
</option>
<option value="pallets aanbieden">
Ik wil pallets aanbieden
</option>
<option value="pallets kopen">
Ik wil pallets kopen
</option>
<option value="containerservice">
Containerservice
</option>
</select>
<textarea placeholder="Uw opmerkingen" id="messageofferte" name="message" required="" style="border-radius: 4px;"></textarea>
<input type="submit" value="Verstuur">
</div>
</form>
JS:
$(function() {
// Get the form.
var form3 = $('.offerte-form');
// Get the messages div.
var formMessages3 = $('.offerte-form-message');
$(form3).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData3 = $(form3).serialize();
console.log(formData3);
$.ajax({
type: 'POST',
url: $(form3).attr('action'),
data: formData3
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages3).removeClass('alert alert-danger');
$(formMessages3).addClass('alert alert-success');
// Set the message text.
$(formMessages3).text(response);
// Clear the form.
$('#naamofferte').val('');
$('#naambedrijf').val('');
$('#adresofferte').val('');
$('#vestplaats').val('');
$('#postcode').val('');
$('#emailofferte').val('');
$('#telnrofferte').val('');
$('#offertevoor').val('');
$('#messageofferte').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages3).removeClass('alert alert-success');
$(formMessages3).addClass('alert alert-danger');
// Set the message text.
if (data.responseText !== '') {
$(formMessages3).text(data.responseText);
} else {
$(formMessages3).text('Helaas, er ging iets fout, probeer het opnieuw');
}
});
});
Sorry for these lines, I needed to add more 'details' but I don't have them.
Thanks in advance!
ajax url u call to attr('action') of .offerte-form but I cant see action in your form.check it please.
<form class="offerte-form" method="post" action="submit.php">

Issue posting form via AJAX

I have the following form which I then send upon submit via AJAX to insert to a MySQL DB through Ajax. All inputbox in form have their own Id and I get them all in my .php process file except the ones "cas" and "dat" that do not seem to go through the AJAX posting process.
The form:
<form id="form">
<div class="form-group">
<label class="lab" for="nm">id</label>
<input disabled type="text" id="id" name="id" class="form-control" placeholder="Id">
</div>
<div class="form-group">
<input type="text" class="form-control" name="cas" id="cas" value="2">
<input type="text" class="form-control" name="dat" id="dat" value="2017-11-30">
</div>
<div class="form-group">
<label class="lab" for="nm">Product</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM product_family order by product_type_id ASC","form-control","nm","nm","Select Product", "product_family", "product_family");?>
</div>
<div class="form-group">
<label class="lab" for="em">Win</label>
<input type="text" id="em" name="em" class="form-control allow_decimal" placeholder="Win">
</div>
<div class="form-group">
<label class="lab" for="hp">Drop</label>
<input type="text" id="hp" name="hp" class="form-control allow_decimal" placeholder="Drop">
</div>
<div class="form-group">
<label class="lab" for="ad">Currency</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM currency order by id ASC","form-control","ad","ad","Select Currency", "currency", "currency");?>
</div>
<button type="button" id="save" class="btn btn-success" onclick="saveData()">Save</button>
<button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>
</form>
I then have the following JavaScript code triggering the Insert upon "save data" click in order to post the different inputbox values to my .php processing file:
function saveData(){
var id = $('#id').val();
var name = $('#nm').val();
var email = $('#em').val();
var phone = $('#hp').val();
var address = $('#ad').val();
var casino = $("#cas").val()
var date = $("#dat").val();
$.post('server.php?p=add', {id:id, nm:name, em:email, hp:phone, ad:address, cas:casino, dat:date}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function viewData(){
$.get('server.php', function(data){
$('tbody').html(data)
})
}
Then I try to read my "$_post" values on the PHP side:
if($page=='add'){
try{
$id = $_POST['id'];
$nm = $_POST['nm'];
$em = $_POST['em'];
$hp = $_POST['hp'];
$ad = $_POST['ad'];
$casino_id = $_POST['cas'];
$date = $_POST['dat'];
}
I perfectly get all variables except the dat and cas posts that do no appear in the $_post list. Listing all $_Post the following way:
$myfile = fopen("LOGPOST.txt", "w") or die("Unable to open file!");
foreach ($_POST as $key => $value){
$txt= $txt."{$key} = {$value}//";
gives the following output: id = //nm = F&B Sales//em = 1000//hp = 500//ad = EUR//
What am I doing wrong?

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

Categories

Resources