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
Related
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
}
This question already has answers here:
Calling PHP file using AJAX
(3 answers)
Closed 8 years ago.
I have php website showing/hiding the pages through the nav links.
Im wondering how to call my php functions when clicking on the corresponding page link.
Is it possible to use ajax (jquery?) to call one of all the functions on my function.php file?As i understand it ajax will run the whole code in the php file its calling?
$(document).on("click", ".dbLink", function() {
var sText = $(this).attr("data-variable");
$.ajax({
url: '../ini/functions.php?q='+sText,
type: 'get',
success: function(data){
alert(data);
}
});
});
function.php
function a(){
echo "result";
}
if (isset($_POST['action'])) {
switch($_POST['action']) {
case "a":
a();
break;
case "b":
b();
break;
default:
break;
}
}
Put a string in the AJAX parameters, and have your PHP code run different functions depending on the string, e.g.
switch($_GET['op']) {
case "delete":
do_delete();
break;
case "update":
do_update();
break;
...
default:
// Report unrecognized operation
}
In your jQuery code, the handler function should call event.preventDefault or return false to prevent the normal action of the element you click on (I'm guessing it's a link). Also, you need to match the way you send the AJAX request with the way you retrieve the parameter in PHP -- if you use $_POST, you have to use type: 'post' -- and the parameter names must match (you used q in the Javascript, but action in the PHP).
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var sText = $(this).attr("data-variable");
$.ajax({
url: '../ini/functions.php',
data: { action: sText }
type: 'post',
success: function(data){
alert(data);
}
});
});
You can do ajax request to server with your data in request parameters.
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
json_encode($aResult);
?>
You don't call functions from AJAX. With AJAX you retrieve resources.
PHP is a resource preprocessor (as every server-side language is), so it executes code to bring you the so-called resource (html pages, css, images, ... are resources).
So, AJAX does not issue functions, since AJAX is not related to PHP but to HTTP requests.
In that sense, the AJAX-side could understand that it must issue a resource (and it DOESN'T KNOW that resource will trigger a chunk of server-side logic).
So, what you could expect to do is to send arguments (e.g. via GET or POST) and expect a result. In the other (i.e. the PHP) side you should consider those arguments and process them.
Perhaps sending parameters like functionName=func1¶ms=[1,2,%22a%22] and processing them like:
$func = $_GET['functionName'];
$params = json_decode($_GET['params']);
if (function_exists($func))
{
$result = call_user_func_array($func, $params);
echo json_encode($result);
}
else
{
echo "unexistent function";
}
would do the job but, again, AJAX does not know about this, and never will, since AJAX is not related to PHP.
What is the correct way to handle Ajax success callback events using jquery?
In my code, when I run instead of displaying data, it alerts object:object. However, if I use say msg.box it returns the data correctly.
I am trying to create an if statement where if text equals a certain word then the variable from json is placed in the html of the result div BA_addbox.
I cannot seem to get this to work and would be grateful if someone could point out my error. I have only included the relevant code as the form is posting the correct data and the php code is catching all the posts. Many thanks.
ajax code
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
if(msg == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
//alert(msg);
console.log(msg);
//$("#BA_addbox").html(msg.box);
//$("#formImage .col_1 li").show();
//$("#BA_boxform").get(0).reset();
//$("#boxaddform").hide();
}
});
boxesadd.php
$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";
if (isset($_POST['submit'])) {
if (!empty($box)) {
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);
$result = json_encode($form);
echo $result;
}
else
{
$error = array('boxerrortext'=>$boxerrortext);
$output = json_encode($error);
echo $output;
//echo "You need to input a box";
}
}
In javascript associative arrays are called objects, so there's no bug in the transmitted data.
Why do you compare msg to "You need to input a box"? You cannot compare object and string, this makes no sense.
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
} else {
$("#BA_addbox").html(msg.box);
}
Try this instead:
if(msg.boxerrortext) {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
Hope this will help !!
I have the following JS code:
var dataString = "action=validateUsername"+
"&username="+usernameRegi+
"&lang="+lang;
$.ajax({
type: "POST",
url: "function.php",
data: dataString,
cache: false,
success: function(result)
{
var expl=result.split("|");
if(expl[0]=="1")
alert("1");
else if(expl[0]=="99")
alert("99");
}
});
This is my function.php
if($_POST["action"]=="validateUsername")
{
$username=$_POST["username"];
$lang=$_POST["lang"];
$sqlSelect = "SELECT * FROM user where userName='".$username."'";
$sqlQuery = mysql_query($sqlSelect);
$rowCount = mysql_num_rows($sqlQuery);
if($rowCount>0)
{
if($lang=="BM")
echo "99|My msgA.";
else
echo "99|My msgB.";
}
else
{
if($lang=="BM")
echo "1|My msgC.";
else
echo "1|My msgD.";
}
}
The problem is, my ajax request never alert 1 or 99 on success. And I found the problem is expl[0]==1 instead of expl[0]=="1".
When I turn my code to this one, it run smooth.:-
if(expl[0]==1)
alert("1");
else if(expl[0]==99)
alert("99");
This is happen only when I upload my code to the server. No problem on the localhost. What is the problem, is there any setting on the server that cause that problem?
Could anybody explain me, what is happening here?
It's because:
When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.
while passing values and returning them from function make sure not to add quotes to int values. or add function below to check / convert them to int
function isint( $mixed )
{
return ( preg_match( '/^\d*$/' , $mixed) == 1 );
}
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);
}