Error using Ajax in PHP and JQuery - javascript

i got a problem when i try to use ajax in a php file, which calls to another php file.
Here is the code of the php file:
<script>
function obtenerProductos(cat) {
parametros = {"idCat": cat};
$.ajax({
data: parametros,
url: '/bin/getProductos.php',
type: 'post',
beforeSend: function() {
$(".prods > form").html("Procesando, espere por favor...");
},
success: function(respuesta) {
$(".prods > form").html(respuesta);
}
});
}
function obtenerProducto(prod) {
parametros2 = {"idProd": prod};
$.ajax({
data: parametros2,
url: '/bin/getProducto.php',
type: 'post',
beforeSend: function() {
lista = $(".cPreview").html() + "<br/> Añadiendo...";
$(".cPreview").html(lista);
},
success: function(respuesta) {
lista = $(".cPreview").html()+ respuesta.nombre + "\t" + respuesta.precio + "<br/>" ;
$(".cPreview").html(lista);
precio = parseFloat($(".precioT").html()) + respuesta.precio;
$(".precioT").html(precio);
}
});
}
</script>
In the first function of this script i call to the first PHP (getProductos.php) to get all the products of a category and receive a html which print in a form.
The second function calls to another php (getProducto.php) to get all the information of the selected product and print it in another div.
Here you have the PHP files named.
getProductos.php (This works)
<?php
include '../funciones.php';
$recibido = $_POST['idCat'];
echo obtenerProductosCategorias($recibido);
?>
getProducto.php (Dont Works)
<?php
include '../funciones.php';
$recibido = $_POST['idProd'];
echo obtenerProductos($recibido);
?>
And the 2 functions of this code:
function obtenerProductosCategorias($idCat) {
conectDB();
$string = "";
$sql = 'select * from Productos where id_categoria="' . $idCat . '";';
$resultado = mysql_query($sql);
while ($row = mysql_fetch_array($resultado)) {
$string = $string . "<input type='button' onclick='obtenerProducto(" . $row["id_producto"] . ");return false;' value='" . $row['nombre_producto'] . "' />";
}
return $string;
closeDB();
}
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}
I have alerts inside the PHP to check that everything is going fine but the second function doesnt enter in his PHP and it returns undefined undefined without show any alert of the PHP thats why i think that the second function have some problems to reach his PHP but the URL is correct and the file is located in the right place.
Thanks for reading and sorry for my English.

Try defining $resultado as an array prior to assigning anything too it. Not sure but in some configurations this does break PHP.
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
$resultado = array();
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}

Related

Onchange populate different dropdown based on value

I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>

Communication between JavaScript, PHP and MySQL

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'){

PHP Delete from javascript button click

I'm currently doing a PHP page that displays bans and also gives an option to unban users.
I can't seem to get the button to work and run the query to unban. Any help would be much appricated.
It currently does nothing and I'm also unsure as to how to display the Pnotice errors as I get
Uncaught TypeError: Cannot read property 'required' of undefined
Here is the function listed in lightcms.php for banlist.php;
function banListAll() {
global $db;
$getBanListAllQuery = "SELECT * FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
echo "<tr id=\"banID" . $showBanListAll['id'] . "\">";
echo "<td>";
echo $showBanListAll['id'];
echo "</td>";
echo "<td>";
echo $showBanListAll['added_date'];
echo "</td>";
echo "<td>";
echo $showBanListAll['value'];
echo "</td>";
echo "<td>";
echo $showBanListAll['reason'];
echo "</td>";
echo "<td>";
echo $showBanListAll['expire'];
echo "</td>";
echo "<td>";
echo "<button data-id=\"" . $showBanListAll['id'] . "\" type=\"button\" class=\"btn btn-xs btn-danger btn-unban\">Unban</button>";
echo "</td>";
echo "</tr>";
}
}
Here is the javascript on banlist.php
<script type="text/javascript">
$(".btn-unban").click(function(){
var articleId = "#banID"+ $(this).attr("data-id");
var myData = "unban="+ $(this).attr("data-id"); //post variables
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "./engine/post/unban.php",
dataType:"json",
data: myData,
success: processJson
});
function processJson(data) {
// here we will handle errors and validation messages
if (!data.success) {
if (data.errors.required) {
new PNotify({
title: 'Uh oh!',
text: data.errors.required,
type: 'error'
});
}
} else {
new PNotify({
title: 'Success!',
text: data.message,
type: 'success'
});
$(articleId).fadeOut("slow");
}
}
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE users_bans WHERE id = '$id'";// Do Your Insert Query
if($db->query($insert)) {
echo '{"success":true,"message":"User was unbanned!"}';
} else {
echo '{"error":true,"message":"Sorry this has not worked, try another time!"}';
}
//Need to work on displaying the error^
?>
Your JS looks for "errors.required" but your PHP sends "error" with no required.
Here's some code edits that (IMO) clean up the code. (any changes to sql are based on the assumption that you're using mysqli. that assumption based on the use of ->fetch_assoc()) Please consider atlest the change to unban.php as what you currently have is open to sql injection
Your new banListAll function:
function banListAll() {
global $db;
// don't use SELECT * if you can help it. Specify the columns
$getBanListAllQuery = "SELECT id, added_date, value, reason, expire FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
$showBanListAll[] = "<button type='button' class='btn btn-xs btn-danger btn-unban'>Unban</button>";
// array_slice to get ignore the ['id']
echo "<tr data-banid='" . $showBanListAll['id'] . "'><td>" . implode("</td><td>", array_slice($showBanListAll,1)) . "</td></tr>";
}
}
New JS on banlist.php
<script type="text/javascript">
function processJson(data) {
// here we will handle errors and validation messages
if (data.error === false) {
row.fadeOut("slow");
}
// assuming we always get a "message"
new PNotify({
title : 'Uh oh!',
text : data.message,
type : 'error'
});
}
$(".btn-unban").click(function() {
var $this = $(this); // creating jQuery objects can be costly. save some time
var row = $this.closest('tr');
var banID = row.data('banid');
var postData = { unban: banID };
var formData = new FormData(this);
$.ajax({
type : "POST",
url : "./engine/post/unban.php",
dataType : "json",
data : postData,
success : processJson
});
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
// Don't just concat variables that came from users into your DB queries.
// use paramterized queries. If $db is a mysqli connection
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
$deleteStmt = $db->prepare($insert);
// if id is a number change "s" to "i" below
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
// add this function to return results to your JS functions
// should make it harder to put "errors" instead of "error" ;)
function jsonResult($hasErrors, $msg) {
return json_encode(array("error"=>$hasErrors,"message"=>$msg));
}
and just in case you thought unban.php was getting unnecessarily long, here it is without comments
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
if ($deleteStmt = $db->prepare($insert)) {
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
}
else {
print_r($db->error);
}
// the function should go into your general functions file
?>

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

PHP Ajax returning HTML twice

I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)

Categories

Resources