I'm performing an Ajax request to a php file called save_tags.php this is the content of the file:
$id = $_POST['id'];
$name = $_POST['name'];
$type = $_POST['type'];
$tags = json_decode(stripslashes($_POST['tags'])); //Should be an Array but is a String...
$removeTags = json_decode(stripslashes($_POST['removeTags']));
//Type can be company, contact, column, supplement, programme.
if($type == 'company'){
$tagObject = new DirectoryCompany($id);
}elseif($type == 'contact'){
$tagObject = new DirectoryContact($id);
}elseif($type == 'column'){
$tagObject = new Column($id);
}elseif($type == 'supplement'){
$tagObject = new Supplement($id);
}elseif($type == 'programme'){
$tagObject = new Programme($id);
}elseif($type == 'list'){
$tagObject = new DirectoryContactList($id);
}
//Add and Remove Tags by looping through the Arrays.
foreach($tags as $tag){
$tagObject->addTag($tag, $id);
}
foreach($removeTags as $tag){
$tagObject->deleteTag($tag, $id);
}
//Get the tags associated with the object
$tagarray = $tagObject->getTags($id);
// Add Tags to All contacts on the list
$tagObject->getAllcontactsAndAddTags($id);
//Build HTML output
$output = "<ul>";
foreach($tagarray as $tag){
$output .= "<li>". $tag .'[X]'."</li>";
}
$output .= "</ul>";
echo $output;
?>
The purpose of the file is to apply the tags a user has checked and apply them to the object being worked on. Currently the above code is working, as in the tags are being applied and saved. however what is not working is that the $output variable is not being echoed and I can't figure out why.
Also when I check my console via the browser window I can see that there was a 500 error when requesting the file.
I'd appreciate any help.
<ul> this is tag html, check source page
and check alert(data)
$.ajax({
type: 'POST',
url: 'url',
data: { },
success: function(data) {alert(data)}
});
$output = "<ul>";
foreach($tagarray as $tag){
$output .= "<li>". $tag .'[X]'."</li>";
}
$output .= "</ul>";
echo $output;
if $tagarray is null echo = <ul></ul> invisible on the page
500 errors usually means that there's something wrong with your php code. Make sure that the code doesn't error out. Try to go to it in your browser and confirm that there are no errors.
First, try to put a few var_dumps here and there to see if you data is correct. An statuscode 500 means that there was most likely a fatal error in your script. This can be either in this php file or in one of your classes.
Most likely you will find the answer in a few minutes. To check if your script even works, try to echo some simple like "test" and comment everything else.
Related
I am designing a php application using AJAX and PHP.
But the if statement in my php file behaves unexpectedly.
The request method is 'POST';
Ajax code is
function fetchData(){
var recipename = document.getElementById("recipe").value;
var calorie = false;
createRequestObject();
//window.alert(calorie);
var url = "reciepinfo.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
window.alert(calorie);
xmlHttp.send("recipe="+recipename+"&calorie="+calorie);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState===4 && xmlHttp.status===200){
document.getElementById("target").innerHTML = xmlHttp.responseText;
}
}
}
And php code is:
<?php
$_SESSION['flag']=false;
if($_SESSION['flag']==false){
session_start();
$_SESSION['flag']=true;
}
$recipename = $_REQUEST['recipe'];
$calorie = $_REQUEST['calorie'];
echo $calorie;
$calorietemp = 0;
//echo $recipename;
$database = "nutrition";
$link = mysqli_connect('localhost','root','',$database);
$query = "select * from recipestb where name='$recipename'";
//$result = mysqli_query($link,$query);
//$obj = mysqli_fetch_object($result);;
if($link){
$result = mysqli_query($link,$query);
$obj = mysqli_fetch_object($result);
//$arr = mysqli_fetch_array($result);
//$names = "";
if(is_object($obj)){
echo "<i/>";
echo "<font size='5'>";
echo "Recipe name: ".$obj->name;
echo '<br/>';
echo "Carbohydrates : ".$obj->carbs." grams";
echo '<br/>';
echo "Proteins: ".$obj->protein." grams";
echo '<br/>';
echo "Fat: ".$obj->fat." grams";
echo '<br/>';
echo "Calories: ".$obj->calorie." cal";
$calorietemp = $obj->calorie;
echo '<br/>';
}else{
echo "non object";
}
}else{
echo "Connection failed";
}
if($calorie==true){
echo $calorie;
$_SESSION['caloriecount'] = $_SESSION['caloriecount'] + $calorietemp;
echo "Total calorie in diet :".$_SESSION['caloriecount'];
}
My session handling is weird i accept, but neglecting that, even the variable calorie is explicitly set to false, the if block executes.The echo $calorie statement also executes and it displays $calorie as false.
And i am not getting what is going wrong exactly.
Almost irritated with this.
Can anybody help?
EDIT1:
The php code is fine...
Ajax code has some problem...
When i set the $calorie to false in php code..
It behaved properly..
Leaving the session handling aside, the $calorie problem ...
You pass the data via AJAX as strings.
$calorie = 'false';
var_dump((true == $calorie));
You will get always bool(true). Using your AJAX example above, try this snippet instead (and use POST instead of REQUEST):
$calorie = ('true' == $_POST['calorie']);
var_dump($calorie);
// produces `bool(false)`
As a beginner i was unaware that the java-script variable with value false is passed as a string "false" to a server side script like PHP.
If we use a boolval(), in PHP this issue can be resolved.
PHP boolval()
I set the $calorie in my java-script to 0 or 1 as per my need.
When i wanted the false value to be sent to PHP script ,i set $calorie in java-script to 0 and the boolval() in corresponding PHP script evaluated it as false.
So the issue was resolved.
This is the HTML/PHP before being stored in the database:<li><?= $item->item['Manufacturer']; ?> <span class="divider">|</span></li>
This is the HTML/PHP after being stored in the database:
<li><a href="<?= dots('duo/'); ?>"><?= $item->item['Manufacturer']; ?></a> <span class="divider">|</span></li>
I assign this result to a variable:
$crumbles = $details['Crumbs'];
I echo the result like so:
<?php echo html_entity_decode($crumbles); ?>
But it returns this when I view source. It's not evaluating any of the PHP in the string.
<li><?= $item->item['Manufacturer']; ?> <span class="divider">|</span></li>
It shows in the browser as <?= $item->item['Manufacturer']; ?> |
How can I get it to evaluate the PHP as well as display the html correctly?
EDIT: Here is the code that handles the input into the DB. It serializes the form data (url, crumbs, meta info, etc) and adds it to an ajax queue.
$("form#seo_add").submit(function(e) {
console.log(this);
var data = $(this).serializeArray(),
$commitBtn = $(this).find("button"),
form_incomplete = false,
queueData = ['seo_add', data];
When fired, the queue controller runs $this->seo->add($seo_add, $user);
Which is modeled like this:
function add($data = null, $username = null) {
if (!is_array($data) || is_null($username)) die("Expecting new pageinfo");
//if a single item is being inserted, add it to a parent array so iteration works
if (!is_array($data[0]))
{
$data = array($data);
}
foreach ($data as $key => $page)
{
if (isset($page['section'])) unset($page['section']);
if (isset($page['action'])) unset($page['action']);
$add = $this->db->insert('pageinfo', $page);
$page = array_merge(array('id'=>$this->db->insert_id()), $page);
$last_queries[$key]['type'] = 'seo_add';
$last_queries[$key]['html'] = "New page: <b>" . $page['page'] . "</b>";
$last_queries[$key]['data'] = $page;
}
if ($this->db->_error_message())
$this->db_error('Unable to insert page');
return log_changes($last_queries, $username, $this->site);
}
Your PHP tags are being double encoded at your PHP tags < so you can run html_entity_decode over it twice.
Even if your php tags were decoded they would never be interpreted by PHP since you're echoing them out straight away, the way around this is to run what your database returns through eval like so:
$crumbles = html_entity_decode(html_entity_decode($crumbles), ENT_QUOTES);
eval("?>{$crumbles}<?");
I suggest using placeholders.
$html = '<li>[item] <span class="divider">|</span></li>';
I suggest not saving the html encoded. This would do the trick for you I guess:
$html = str_replace(['href','item'],[dots('duo/'),$crumbles],$html);
Probably you've to encode the $crumbles or dots('duo/') if that is user input.
So I am having an issue with re-populating data into a dropdown box after the form is submitted with Ajax. This is to remove an object from the dropdown, the initial script works fine, its just getting the new data and populating. My PHP script builds a JSON array to output to Ajax for parsing but when I check the PHP script the only thing that returns is }.
PHP Code:
$jasonData = "{";
include_once("../php_includes/db_connect.php");
$sql = "SELECT * FROM orginfo";
$user_query = mysqli_query($db_connect, $sql);
$count = mysqli_num_rows($user_query);
for($i = 0; $i < $count; $i++){
$rows = mysqli_fetch_array($user_query);
$id = $rows["id"];
$orgname = $rows["orgname"];
$orgphone = $rows["orgphone"];
$jasonData .= '"option'.$id.'":{ "id":"'.$id.'","orgname":"'.$orgname.'","orgphone":"'.$orgphone.'" },';
}
$jsonData = chop($jsonData, ",");
$jsonData .= "}";
echo $jsonData;
AJAX Code:
function getorgs(){
var getorgs = ajaxObj("POST", "engine.php");
getorgs.onreadystatechange = function() {
if(ajaxReturn(getorgs) == true) {
var remresponse = JSON.parse(getorgs.responseText);
alert (remresponse);
}
}
getorgs.send("getorgs");
}
I have been building this off of several tutorials kind of piece meal along with things I have already learned and am using. The current lack of sanitation is because of testing, want to make sure things are working and then add it in to narrow down any issues.
Any help would be appreciated.
Thanks in advance for taking a look.
Try the following:
<?php
header('Content-Type: application/json;charset=UTF-8');// this line must reside on top (before any output)
$jasonData = array();
$user_query = mysqli_query($db_connect, 'SELECT*FROM`orginfo`');
while ($row = mysqli_fetch_assoc($user_query)) {
array_push($jasonData, $row);
}
echo json_encode($jasonData, JSON_FORCE_OBJECT);
mysqli_close($db_connect);
Let me know if the above doesn't work out!
I have a menu which get its items from database.
I want to get the menu id of clicked menu in following for each:
public function gen_menu($menuItems, $pId = 0)
{
$menu = '';
$ulStart = 0;
$base_url = base_url();
$uri = $this->uri->segment(1);
foreach($menuItems as $row)
{
if($row->parent_id==$pId)
{
if($ulStart==0) { $menu .= "<UL>"; $ulStart++; }
$url = $row->item_url;
stripos($url,$base_url)===0 || $url==""?$base_url = base_url():$base_url="";
{
if($row->external==1){
$menu .= '<LI>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
else{
$class = ($uri==$row->custom_url)?"class='selected'":"";
$menu .= '<LI '.$class.'>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
}
}
}
if($ulStart!=0) { $menu .= "</UL>"; }
return $menu;
}`
When I am using onclick in it returns the last id of table always.
Try this:
$menu .= '<LI '.$class.'>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
You had $row->item_id inside the quoted string, so it wasn't expanded. You should have gotten a javascript error from that.
UPDATE:
The problem you're having is that you're confusing server-side and client-side actions. The code in this PHP script all runs on the server when it's creating the page to send to the user. If you're setting a session variable in the loop, the variable will contain the value from the last iteration. Putting PHP code inside onclick doesn't run it when the user clicks, it runs it when the server is composing the onclick attribute to put in the HTML that gets sent to the browser.
If you want to do something on the server when the user clicks, you need to put a Javascript function in the onclick attribute, and that function should use AJAX to call another PHP script.
So I started a question to figure out why my PHP code that is meant to grab the only MP3 URL that exists within each of my Post contents on my Wordpress installation for a custom use of the content here >> Why doesn't my properly defined variable evaluate for length correctly (and subsequently work in the rest of my code)?
I have made several edits and updates and now need to re-formulate both the question and the context. User mrtsherman points out that based on the order I have written code, that I redefine $doc but don't load that into $xpath, however when I try to adjust this my code throws the fatal error "Object of class DOMAttr could not be converted to string" on the line at the very end where I echo the variable $BEmp3s, the end result of all this. Does this mean it cannot convert the attributes to a string I think??
I know I am soo close to the solution here it's nearly killing me but I also think I have been looking at this wayy too much and for too long. Any insight is golden at this point! Here is my code that branches correctly throughout now:
<?php
// Start MP3 URL
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$xpath = new DOMXpath($doc);
// End MP3 URL
$a = 1;
if (have_posts()) :
while ( have_posts() ) : the_post();
?>
<?php
$BEpost_content = get_the_content();
if (strlen($BEpost_content) > 0) {
echo "<div id='debug_content'>get_the_content has something</div>";
} else {
echo "<div id='debug_content'>BEpost_content is empty</div>" ;
};
$success = $doc->loadHTML($BEpost_content);
$xpath = new DOMXpath($doc);
if ($success === FALSE) {
echo "<div id='debug_loadcontent'>loadHTML failed to load post content</div>";
} else {
$hrefs = $xpath->query("//a[contains(#href,'mp3')]/#href");
if ($hrefs->length > 0) {
echo "<div id='debug_xpath'>xpath found something</div>";
} else {
echo "<div id='debug_xpath'>xpath found nothing</div>";
};
$BEmp3s = $hrefs->item(0);
};
?>
<script type="text/javascript">
var myCP<?php echo $a; ?> = new CirclePlayer("#jquery_jplayer_<?php echo $a; ?>",
{
mp3: "<?php echo $BEmp3s; ?>"
}, {
cssSelectorAncestor: "#cp_container_<?php echo $a; ?>",
volume: 0.5
});
</script>
mp3: "<?php echo $BEmp3s->value; ?>"
Try using value?