So I have taken a look around and I cannot seem to find the answer!
I'm trying to send a jQuery variable to PHP.
Code will explain it easier:
jQuery:
$error = 0;
$pageName = $(document).find("title").text();
$referrer = document.referrer;
if ($pageName == "Index") {
$('#index').hide();
console.log($pageName);
} else if ($pageName == "Testing") {
$('#testing').hide();
console.log($pageName);
} else if ($pageName == 'Test') {
$('#test').hide();
console.log($pageName);
} else {
$error = 1;
$.ajax({
type: "POST",
url: "../Ajax/post.php",
data: { param: $error, ref: $referrer }
}).done(function (msg) {
alert("Data Saved: " + $pageName + " " + $referrer );
});
}
PHP:
<?php
$error = $_POST['param']; //I have also tried putting '$error' here.
$referrer = $_POST['ref'];
if ($error == 1)
{
error_log("There has been an error with the pageName = " . $error . $referrer,
1,"Email#host.com","From: Email#host.com");
}
?>
TL;DR:
I am checking for the in my pages and then doing some jQuery functions, if the is unknown then email an error.
So the result I am getting in my email is "1" and that is it. Just the number 1 (which I presume is the $error value?
I'm just playing around with some error handling.
Check the if in PHP... the equals operator is ==, not =
if ($error==1)
Related
I'm trying to establish a simple connection between Javascript and my database using ajax and PHP. Javascript is supposed to receive a name from an HTML form, modify it and post it to PHP to check whether the name is already in the database and return true/ false back to javascript for further use.
Everything works fine as long as I don't add the part of code that connects to the database. Calling only the PHP file in Chrome also works and it will correctly print true or false.
As soon as I connect both together, nothing works. Neither success nor error will execute any of the code inside their functions.
JS1 + PHP1: Nothing happens
JS1 + PHP2: Correctly shows result in Alert1 and Alert2
PHP1 alone: Correctly prints either true or false
JS1
var boo = false;
if(str.length > 1) boo = true;
if (boo)
$.ajax ({
url: 's5Check.php',
type: 'post',
data: { str : str },
success: function( result ) {
alert(result); //Alert1
if(result != false){
boo = false;
alert(str + " already exists!"); //Alert2
} else {
boo = true;
alert(str + " doesn't exist!"); //Alert3
}
},
error: function( e ) {
alert("Error: " + e); //Alert4
}
});
PHP1
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$temp = mysqli_real_escape_string($con, $_POST['str']);
$check = "SELECT id FROM handle WHERE name = '$temp'";
$result = $con -> query($check);
if($result->num_rows > 0) {
echo true;
} else{
echo false;
}
} else{
echo "error";
}
?>
PHP2
<?php
echo $_POST['str'];
?>
Thanks.
echo true will output 1. echo false will output nothing. You're not checking for either of these in your success function.
Using JSON is a simple solution to this, and allows for easy enhancement to more complex results.
JS:
$.ajax({
url: 's5Check.php',
type: 'post',
data: {
str: str
},
dataType: 'json',
success: function(result) {
alert(result); //Alert1
if (result === false) {
boo = false;
alert(str + " already exists!"); //Alert2
} else if (result === true) {
boo = true;
alert(str + " doesn't exist!"); //Alert3
} else if (result === "error") {
alert("Error");
} else {
alert("Unknown problem");
}
},
error: function(jqXHR, txtStatus, e) {
alert("Error: " + e); //Alert4
}
});
PHP:
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$check = "SELECT id FROM handle WHERE name = ?";
$stmt = $con->prepare($check);
$stmt->bind_param("s", $_POST['str']);
$result = $stmt->execute();
$response = $result->num_rows > 0;
} else{
$response = "error";
}
echo json_encode($response);
?>
I'm trying to pass two number and check if their product is true or false. I can see call made successfully in network tab and when i click that link, output is correct to. But i m stuck at retrieving that result. It doesn't show anything in data1.
function call(){
console.log(fun);
$.ajax({
url: "http://localhost/mt2/checkanswer.php",
dataType: "jsonp",
type: "POST",
//window.alert("what");
data: {
num1:2,
num2:2,
answer:5
},
success: function( data1 ) {
console.log(data1);
$( "#timeDiv" ).html( "<strong>" + data1 + "</strong><br>");
}
<?php
// get two numbers and the answer (their product) and return true or false if the answer is correct or not.
// using this as an api call, return json data
// calling <your host>/checkanswer.php?num1=4&num2=5&answer=20 will return true
// calling <your host>/checkanswer.php?num1=4&num2=5&answer=21 will return false
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['answer']) && is_numeric($_GET['num1']) && is_numeric($_GET['num2']) && is_numeric($_GET['answer'])) {
$product = $_GET["num1"] * $_GET["num2"];
if ($product === intval($_GET['answer'])) {
$result = true;
} else {
$result = false;
}
header('Content-type: application/json');
echo json_encode($result);
}
?>
https://drive.google.com/open?id=1ocF344ZxG3HXJR0WQha1kOoVM9bCepnI "console"
The issue is your Javascript is submitting the data via JS as a post request and your PHP is looking for a get request.
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['answer']) && is_numeric($_GET['num1']) && is_numeric($_GET['num2']) && is_numeric($_GET['answer'])) {
..
}
So either change method: 'POST' to method: 'GET' or change $_GET[..] to $_POST[..].
Also that's one wild if statement. You could break it up so it's not so long and isn't as hard to read. This also allows you to add some additional information based on where your code 'fails.'
if ( isset($_GET['num1'], $_GET['num2'], $_GET['answer']) ) {
if ( !is_numeric([$_GET['num1'], $_GET['num2'], $_GET['answer']]) ) {
// Our numbers aren't numeric!
$message = 'Not all variables are numeric';
$result = false;
} else {
$message = 'We did it!';
$result = $_GET['num1'] + $_GET['num2'] == $_GET['answer'];
}
} else {
// We didn't have all of our request params passed!
$message = 'We didn\'t have all our variables';
$result = false;
}
header('Content-type: application/json');
echo json_encode([ 'message' => $message, 'result' => $result]);
Edit
Based on epascarello's comment remove dataType: 'jsonp'.
I'm trying to learn JavaScript to code for Cordova.
I read many tutorials, but none of them helped me with the folowing problem.
My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.
Here is my
<?PHP
$response = array();
require_once __DIR__ . '/db_config.php';
$db_link = mysqli_connect (
DB_SERVER,
DB_USER,
DB_PASSWORD,
DB_DATABASE
);
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
die ('keine Verbindung '.mysqli_error());
}
if(isset($_POST['action']) && $_POST['action'] == 'insert'){
$name = $_POST['name'];
$sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
$db_erg = mysqli_query($db_link, $sql);
if (!$db_erg){
echo "error";
}else{
echo "ok";
}
}
if(isset($_POST['action']) && $_POST['action']=='read'){
$sql = "SELECT * FROM testTable";
$db_erg = mysqli_query( $db_link, $sql );
if (!$db_erg )
{
$response["success"] = 0;
$response["message"] = "Oops!";
echo json_encode($response);
die('Ungültige Abfrage: ' . mysqli_error());
}
while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
{
//$response["success"] = $zeile['pid'];
//$response["message"] = $zeile['name'];
$response[]=$zeile;
}
echo json_encode($response);
mysqli_free_result( $db_erg );
}
?>
and here are my 2 functions in the cordova app:
function getNameFromServer() {
var url = "appcon.php";
var action = 'read';
$.getJSON(url, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
function sendNameToServer() {
console.log("sendNameToServer aufgerufen");
var url2send = "appcon.php";
var name = $("#Name").val()
var dataString = name;
console.log(dataString);
if ($.trim(name).length>0) {
$.ajax({
type: "POST",
url: url2send,
data: { action: 'insert', name: dataString },
crossDomain: true,
cache: false,
beforeSend: function () {
console.log("sendNameToServer beforeSend wurde aufgerufen");
},
success: function (data) {
if (data == "ok") {
alert("Daten eingefuegt");
}
if (data == "error") {
alert("Da ging was schief");
}
}
});
}
}
My Questions/Problems:
The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).
How can I pass "action = read" to the PHP script in the getNameFromServer() function?
The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?
Here is one part answer to your question.
$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.
function getNameFromServer() {
$.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
Edit: Since you are using $.getJSON(), the request method is a GET, which means you have to use $_GET in your third if statement in your PHP script.
if(isset($_GET['action']) && $_GET['action'] == 'read'){
I am developping a site and I using ajax to show some messages to the user, like if he inserted something in all inputs, if my database function worked fine, etc. But the problem is, when I return the string 'empty' from php to ajax, it works fine, but when I return the string 'success', my ajax doesn't work, it just redirect me to my php page and shows in the screen 'success'. What can be wrong?
My ajax code:
<script>
$(document).ready(function () {
$("#btn-enviar").click(function () {
var action = $("#novo-artigo-form").attr("action");
var form_data = {
titulo: $("#titulo").val(),
imagem: $('#imagem')[0].files[0],
texto: $("#texto").val()
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function (response) {
if (response == 'success') {
$("#mensagem-artigo-novo").removeClass("alert-danger alert-warning");
$("#mensagem-artigo-novo").addClass("alert alert-success");
$("#mensagem-artigo-novo").html("<p id='login-mensagem-sucesso'>Artigo adicionado!.</p>");
}
if (response == 'error') {
$("#mensagem-artigo-novo").removeClass("alert-success alert-warning");
$("#mensagem-artigo-novo").addClass("alert alert-danger");
$("#mensagem-artigo-novo").html("<p id='login-mensagem-erro'>Houve um erro ao adicionar no banco.</p>");
}
if(response == 'errors'){
$("#mensagem-artigo-novo").removeClass("alert-success alert-warning");
$("#mensagem-artigo-novo").addClass("alert alert-danger");
$("#mensagem-artigo-novo").html("<p id='login-mensagem-erro'>Houve um erro na imagem.</p>");
}
if(response == 'empty'){
$("#mensagem-artigo-novo").removeClass("alert-success alert-danger");
$("#mensagem-artigo-novo").addClass("alert alert-warning");
$("#mensagem-artigo-novo").html("<p id='login-mensagem-aviso'>Preencha todos os campos.</p>");
}
}
});
return false;
});
});
</script>
My php code:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/banco/banco.php';
$titulo = $_POST['titulo'];
$data = date('Y-m-d');
$texto = $_POST['texto'];
$nomeImagem = $_FILES['imagem']['name'];
$imagem = $_FILES['imagem']['tmp_name'];
$formato = strtolower(end(explode('.', $nomeImagem)));
$extensoes = array('.jpg', '.png');
if (empty($titulo) || empty($texto)) {
echo 'empty';
} else if (inserirPublicacao($conexao, $titulo, $data, $imagem, $texto) == 1) {
$id = ultimoId($conexao);
$caminhoBanco = '/imagens/publicacoes/' . $id . '.' . $formato;
$caminho = '../../imagens/publicacoes/' . $id . '.' . $formato;
if (alterarCaminho($conexao, $caminhoBanco, $id) == 1) {
if (move_uploaded_file($imagem, $caminho)) {
echo 'success';
} else {
echo 'errors';
}
}
} else {
echo 'error';
}
?>
So, in my php code, when my titulo and texto are empty, it shows in the screen a message saying that is empty. But when everything works, I am redirected to another screen that is my php file.. So what is wrong? Why only my 'empty' statement works?
Another strange thing is that if I change the 'success' to 'empty' it doesn't work too!
P.S.: All my div ids are right, so the problem isn't there.
PHP return to jquery / ajax not working,
In my edit function error message is displayed yet success function executed and in my delete function nothing is displayed yet success is executed..
Have tried everything :( (well obviously not everything...)
Any ideas?
currentPage.EditItem = function(id) {
if (confirm('Are you sure you wish to edit?')) {
console.log("DetailPage :: edit");
var itemm = $("#itemm").val();
var amount = $("#amount").val();
var statuss = $("#statuss").val();
var Uid = localStorage.getItem("Uid");
console.log(statuss);
if (itemm == "") {
alert("Please enter item");
} else if (amount == "") {
alert("Please enter amount");
} else if (statuss == "") {
alert("Please enter status");
} else {
$.ajax({
type:'POST',
url:'http://www.mywebsite.com/edit.php',
data:{'Uid':Uid,'itemm':itemm,'amount':amount,'statuss':statuss},
success: function(data) {
alert("Edit item success");
window.location.href = "new_up.html";
},
error: function() {
alert("Edit user failure");
},
});
window.location.href = "new_up.html";
};
};
};
PHP
<?php
// Check connection stuff
$itemm_id = $_POST['Uid'];
$itemm_itemm = $_POST['itemm'];
$itemm_amount = $_POST['amount'];
$itemm_statuss = $_POST['statuss'];
print($itemm_statuss );
$qry = "xxxxxxxxxxx";
if (!mysqli_query($con,$qry))
{
die('Error: ' . mysqli_error($con));
}
echo "success";
mysqli_close($con);
?>
DELETE
currentPage.deleteItem = function(id) {
if (confirm('Are you sure you wish to delete?')) {
var Uid = localStorage.getItem("Uid");
$.ajax({
type:'POST',
url:'http://www.mywersite.com/delete.php',
data:{'Uid':Uid},
success: function(data){
if(data == "YES"){
alert("Item deleted!");
window.location.href = "new_up.html";
}
else{
alert("can't delete the row")
}
},
});
};
};
PHP
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$itemm_id = $_POST['Uid'];
$qry = "DELETE FROM balance1 WHERE id ='$itemm_id'";
if (!mysqli_query($con,$qry))
{
die('Error: ' . mysqli_error($con));
}
echo "YES";
mysqli_close($con);
?>
You might want to improve the indentation of your code before posting. It's hard to read this way. Posting a clear question with clear example code will get you more responses.
I didn't check the whole code because of this, but I think this will help you to find the error:
The success function of your ajax call gets fired whenever it manages to send its data to the server and gets a textual reply. This means it is also fired when the server returns an SQL error: this error message is also a reply.
You might want to view the results in the console to see what is going on:
success: function(data) {
console.log(data);
},
Or have the script check the response to see if the expected string 'success' was returned or something else (like an SQL error):
success: function(data) {
if(data == 'success'){
// OK!
}else{
// The server didn't say 'success' so something fishy is going on.
}
},
Also: 'success' will always be echoed the way you've written your code now. You should place it somewhere it will only be triggered when it was actually ok:
if (mysqli_query($con,$qry)){
echo "success";
}else{
die('Error: ' . mysqli_error($con));
}
You could do:
if (!mysqli_query($con,$qry)) {
header("HTTP/1.0 404 Not Found");
exit;
}
which should trigger the error: option in your jQuery call.
The reason why your code won't work is because die('Error: ' . mysqli_error($con)); to jQuery actually means "success": the server returned some text as response with a header 200 - jQuery is not going to parse that text to see if it contains the word "Error".