I want to display a message after a record has been successfully deleted. I tried everything but without success.
I have an external js file from which I call a PHP file that deletes the record.
JS file:-
// Delete records
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data, status) {
// reload goals
ShowGoals();
}
);
var jsuccess = $("#myPhpValue").val();
console.log(jsuccess);
}
PHP file:-
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
// include Database connection file
require('../../login_system/db.php');
$userid = $_POST['userid'];
$goal_id = $_POST['goalid'];
// $query = "DELETE from goals where user_id = '$userid' AND goal_id='$goal_id'";
// if (!$result = $mysqli->query($query)) {
// exit(mysqli_error($mysqli));
// }
$success = "true";
echo '<form><input type="hidden" id="myPhpValue" value="'.$success.'"/></form>';
mysqli_close($mysqli);
}
?>
I tried to send the $success variable back to js file with several ways but none worked. It seems that any output command (echo, alert, console.log) doesn't display anything and I don't know why.
I would appreciate any help!
You could simply return using echo and display the response directly :
a.php:
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
...
echo true;
}
?>
A.js:
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (response) {
if( response ){
// reload goals
ShowGoals();
console.log("Success message");
}
}
);
}
You could return a json format what gives you the ability to return multiple info like :
A.js:
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data) {
var response = $.parseJSON(data);
if( response.success ){
// reload goals
ShowGoals();
console.log(response.message);
}
}
);
}
a.php:
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
echo jdon_encode(['success'=>true,"message"=>"Deleted Successfully"]);
}
?>
finally I did it!
PHP file
<?php
if(isset($_POST['userid']) && isset($_POST['goalid']))
{
// include Database connection file
require('../../login_system/db.php');
$userid = $_POST['userid'];
$goalid = $_POST['goalid'];
$query = 'DELETE from goals where userid ='.$userid.' AND goal_id='.$goalid;
if (!$result = $mysqli->query($query)) {
exit(mysqli_error($mysqli));
}
$data = true;
echo($data);
mysqli_close($mysqli);
}
?>
JS file
// Delete records
function DeleteGoal(ids) {
$.post("ajax/deletegoal.php", {
userid: ids.user_id,
goalid: ids.goal_id
},
function (data, status) {
// reload goals
if (data==true && status =="success")
ShowGoals();
else
alert("Problem");
}
);
}
So, I return what happen using data variable.
Related
I tried researching a lot before posting here.
There are two files login.php and login-validation.php
Login.php file contains code including login form and jQuery AJAX script to call login.validation.php
--- Code of login.php ---
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
mobile_no = $('#mobile_no').val();
upassword = $('#upassword').val();
console.log(mobile_no, upassword);
$.ajax({
type: "POST",
url: "server/login-validation.php",
data: {
Mobile_no: mobile_no,
Password: upassword
},
cache: false,
dataType:'json',
success: function(response) {
console.log("Data gone successfully");
if(response["type"] == 'LoginSuccess'){
$('#success-message').text(response); // This works but not below ones
}
if(response["type"] == 'WrongCredentials'){
$('#success-message').text(response);
}
else{
$('#success-message').text(response);
}
},
error: function(xhr, textStatus, errorThrown){
console.log(xhr.responseText); Shows my echo message i.e. Wrong credentials for wrong credentials
console.log(textStatus); // Shows parseError
console.log(errorThrown); // Shows SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
}
});
});
});
</script>
---Code of login.validation.php---
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
echo "Wrong credentials". $mysqlconnect->error;
}
}
else{
$message["type"] = 'WrongMobile';
echo "Mobile number doesn't exists";
}
header('Content-type: application/json');
echo json_encode($message);
?>
Tried dataType: 'json' - Didn't work
Tried without dataType - Didn't work
Php script is running properly with right error messages for different "if" statements but AJAX responses goes to error:function() rather than success: function()
In the network tab - The response type is JSON and it displays [type] i.e [WrongCredentials]
Not understanding what is wrong here. Any help would be appreciated.
You need to parse the JSON response using jQuery.parseJSON()
var data = jQuery.parseJSON(response);
Now, you can check it
if(data.type == "LoginSuccess"){
// do something
}elseif(data.type == "Wrong Password"){
// do something else
}
And remove echo from your php code
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
}
}
else{
$message["type"] = 'WrongMobile';
}
header('Content-type: application/json');
echo json_encode($message);
?>
Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!
Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend
I was making a form to post data, combined with Ajax. Below is all code associated with it. The problem is that when filling the form in and submitting, on the first click it does the XHR request, and get's a success call back so changes the button to Done!.
But the results don't appear in the database. When clicking the submit button again, it does another XHR request that DOES get through. Any ideas what could cause this? Thanks!
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
} catch (Exception $e) {
echo $e->getMessage();
}
} ?>
// Backend for the authenication and validation (where the form posts to)
<?php
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if( isset($post_title) && isset($post_content) && isset($post_id) ){
if( empty($post_title) ){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if( !$login->updatePost($post_id, $post_title, $post_content) ){
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>
// JS for the Ajax request itself
$("form").submit(function(evt){
evt .preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax(url, {
data: formData,
type: "POST",
success: function(response){
if(response == "allrighty"){
$(".update-submit").prop("value", "Done!")
}
else if (response == "charliewegotaproblem") {
$(".update-submit").prop("value", "Something went wrong...")
}
}
}); // Ajax OBJECT END;
});// Submit END
<?php
==> First return success message, if post update query has executed successfully in updatePost function
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$success = false; // Here I changed the code
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
if($query1){ $success = true; } // Here I changed the code
} catch (Exception $e) {
echo $e->getMessage();
}
return $success;
}
==> Now here if $login has return true than an only than "allrighty" will return
// Backend for the authenication and validation (where the form posts to)
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if( isset($post_title) && isset($post_content) && isset($post_id) ){
if( empty($post_title) ){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if($login->updatePost($post_id, $post_title, $post_content)){ // Here I changed the code
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>
I'm using PHP and trying to get values from a MySQL database using jQuery/AJAX.
My mysql table has four columns: id, tail, cg and cw
My php code looks like this:
<?php
$inputvalue = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$addresult = "
SELECT *
FROM `air_cg`
WHERE `tail` = '" . $inputvalue['tail'] . "'
ORDER BY `id` DESC
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
The resulting JSON has this format:
{"result":[["255","Lapdogie","1","2"],["254","Lapdogie","23","234"],["253","Lapdogie","132","454"]],"errors":false}
My javascript code that im using for the ajax function and to parse the resulting JSON looks like this:
function getcgdata(aa){
$.ajax({
type: "POST",
url: "drawchart.php",
data: {tailnumber:taildata},
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
var chartdata=(value);
var cgdata =(cg.value);
console.log(chartdata);
console.log(cgdata);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The console log for chartdata shows this:
["256", "Lapdogie", "232", "333"]
["239", "Lapdogie", "23", "12"]
["238", "Lapdogie", "1232", "1232"]
The console log for cgdata only shows one value many times:
232
232
232
I am not sure if the issue is with my PHP code or with the way im trying to parse the JSON.
i dont see that you define cg.value..
you use
var cgdata =(cg.value);
but cg is where defined?
it should be probably something like chartdata[3] .. ?
Rajdeep Paul's suggestion below worked for me for this particular situation:
Change
var cgdata =(cg.value);
to
var cgdata = value[2];
I'm aware that there are many issues with my code as pointed out by Ludovit Scholtz and Magnus Eriksson and I shall refine it at a later stage.
Thank you all!
Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.