I am using ajax call to grab some data from my mysql database. This is my ajax call:
$.ajax({
type: "POST",
url: "fetch.php",
data: id,
success: function(msg) {
var record = JSON.parse(msg);
$("#name").val(record.name);
$("#description").val(record.description);
switch(record.category) {
case ("Residential"):
$("#category").val("residential");
break;
case ("Modernisation & Domestic Extensions"):
$("#category").val("modernisation");
break;
case ("Feasibility Layouts"):
$("#category").val("feasibility");
break;
case ("Master Planning"):
$("category").val("master");
break;
default:
$("category").val("");
};
switch(record.featured) {
case ("y"):
$("#featured").val("y");
break;
default:
$("featured").val("n");
};
}
})
and this is my php file:
<?php
$dbc = mysqli_connect('XX','XX','XX','XX');
$id = $_POST['id'];
if($dbc) {
$row = fetchDataFromRecordWithId($dbc,$id);
}
else {
echo 'Database error';
}
function fetchDataFromRecordWithId($dbc,$id) {
$q = "SELECT * FROM Projects WHERE id = ".$id;
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
mysqli_close($dbc);
return $row;
}
echo json_encode($row);
?>
Everything work flawless but soon when I try to add if statement in my php file to check if there is any POST data than my ajax call is not getting any response. I tried different methods :
<?php if(isset($_POST)) { .. my whole php code here .. } ?>
<?php if(!empty($_POST)) { ..my whole php code here .. } ?>
<?php if($_POST) { .. my whole php code here .. } ?>
<?php if($_POST['id']) { .. my whole php code here .. } ?>
but nothing work! Ajax call is not getting json data back when I will use any of these if statements listed above.
I could not check for POST data and leave it like it is but I want to do is in proper way.
It seems like if statement is not executed (but POST data must be there as I am able to fetch $_POST['id'] value when if statement not used).
I also tried to put echo json_encode($row) outside if statement but it didn't help either. Any ideas what is wrong?
$.ajax({
type: "POST",
url: "fetch.php",
data: id,
http://api.jquery.com/jQuery.ajax/:
data: [...] Object must be Key/Value pairs.
So make that line
data: { id : id },
instead, then it should work.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
die("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
}
if (isset($_POST['id'])) {
... db code here ...
}
also note that your are WIDE open for SQL injection attacks.
you try follow testings on your code
check whether you have have the right request page for php .
see in google chromes right click inspect element then console tab any errors are showing
in your suceess:function(msg) add $("body").append(msg)
add function before success:function(result) {}
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
Related
I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;
For me this is something new, so I am just researching this and trying to understand it.
As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.
Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck.
I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?
The problem is that when I attach a database to it, I would need to consider all inputs that can happen.
How do I specify a specific php function when using jquery & ajax?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:
url: "function.php?action=functionname"
or:
data: {
name: 'myname',
action: 'functionname'
}
Then in PHP, you can access that attribute and handle it:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
Implementation example:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
You are actually quite close to what you want to achieve.
If you want to specify which function will be called in PHP, you can pass a variable to tell PHP. For example, you passed request=save in AJAX, you can write the PHP as follow:
$request = '';
switch(trim($_POST['request'])) {
case 'save':
$player_name = (isset($_POST['playername']) ? trim($_POST['player_name']) : 'No Name'));
saveFunction($player_name);
break;
case 'load':
loadFunction();
break;
default:
// unknown / missing request
}
EDIT: You can even pass along with other parameters
This may not be exactly what you are looking for but it can help some others looking for a very simple solution.
In your jquery declare a variable and send it
var count_id = "count";
data:
{
count_id: count_id
},
Then in your php check if this variable is set
if(isset($_POST['count_id'])) {
Your function here
}
I'm using Select2 3.3.1, and on an event I get access to the changed elements in my multiple text input that serves as a place to create and delete tags for use on my website. I'm having trouble iterating over the objects returned in the event handler. Specifically, I want to do this because I want access to the individual tags, and the event handler return parameter contains these objects organized by whether the tags were added or removed. So, this is excellent. But everything I've tried fails.
.on("change", function(e) {
alert(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
var added = JSON.stringify({added:e.added});
$.each(added, function(){
$.ajax({
url: '/db-interaction/tags.php',
data: {
'action': 'addtag',
'q': this
},
type: 'get',
success: function(output) {
}
});
});
The command on the second line above
alert(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
displays this string
{"val":["newtag"],"added":{"id":"newtag","count":"0"}} in an alert.
In this case, I had just added the word 'newtag' as a tag. I'd like to be able to iterate over these items in this inner list.
I've also tried a double nested loop, like shown below, but I get the same error. I'm not certain what structure the JSON string requires.
$.each(added, function(){
$.each(this, function(){
The ajax request doesn't seem to execute but I can't locate the bug. The success function doesn't execute and there is an error in the firebug console. It says TypeError: invalid 'in' operand e, pointing to the jquery script. It's my bug, I'm sure. Probably to do with the way I'm handling the event handler parameter 'e', but I don't know what I'm doing wrong.
Here's the tag script. FWIW, the addNewTag() method works in other use cases.
<?php
session_start();
include_once "../inc/constants.inc.php";
include_once "../inc/class.tags.inc.php";
$tags = new Tags();
if (isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn']==1)
{
if(!empty($_POST['action']) )
{
switch($_POST['action'])
{
case 'addtag':
echo $tags->addNewTag();
break;
case 'removetag':
echo $tags->removeTag();
break;
case 'getalltags':
echo $tags->getAllTags();
default:
break;
}
}
else if(!empty($_GET['action']))
{
switch($_GET['action'])
{
case 'addtag':
echo $tags->addNewTag();
break;
case 'removetag':
echo $tags->removeTag();
break;
case 'getalltags':
echo $tags->getAllTags();
default:
break;
}
}
}
else
{
header("Location: /");
exit;
}
?>
And the addNewTag() method, which works well in other cases:
/**
* Adds a new tag, increment uses_count if it already exists
*
*
*/
public function addNewTag($name=NULL)
{
if ($name === NULL){
if (isset($_POST['q']) )
$u = $_POST['q'];
else if (isset($_GET['q']))
$u = $_GET['q'];
}
else{
$u = $name;
}
$sql = "INSERT INTO tags(name,uses_count) VALUES (:term,1)
ON DUPLICATE KEY UPDATE uses_count=uses_count+1;";
if($stmt = $this->_db->prepare($sql))
{
$stmt->bindParam(":term", $u, PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
}
Can anyone help me out? If it would be of use, I could describe the other things I've tried and why they haven't worked.
Try something like
$.each(e.added, function(key, value){
alert(key + ' - ' + value )
$.ajax({
url: '/db-interaction/tags.php',
data: {
'action': 'addtag',
'q': this
},
type: 'get',
success: function(output) {
}
});
});
Demo: Fiddle
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).
I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}