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!
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.
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.
ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...
I'm testing a script to automate advertisement read from a txt file) i want to use this because it was the one i already had and was working and only needed a few changes, however, something stopped working and i dont know what's wrong, i'm checking the output and everthing seems fine on the javascript but for some reason it doesn't work, it comes with unexpected token illegal and with the uncaught syntax error
below is the code. Any Help is appreciated
PHP/javascript combined code
<?php
$adsf = "test.txt";
$count = 0;
$frd = fopen ($adsf,'r');
$artest = array();
$artest2 = array();
$artest3 = array();
while(!feof($frd))
{
$artest[$count] = fgets($frd);
$count++;
}
fclose($frd);
$t = 0;
while($t < $count)
{
$artest2[$t] = str_replace("\n" ,'', $artest[$t]);
$artest3[$t] ="\"".$artest2[$t]."\", ";
$t++;
}
unset($artest3[$t - 1]);
shuffle($artest3);
$t = 0;
while ($t < $count)
{
$jsr = $jsr.$artest3[$t - 1];
$t++;
}
//$jsr. = "\"test 1 test 2 test 3\", ";
$jsr = $jsr." \"Advertise Here come to Lot 28 or Click HERE For More Information\" ";
?>
var avs = new Array ( <?echo $jsr; ?>);
//var cron = 60;
var sub = 0;
function show5(){
if (!document.layers&&!document.all&&!document.getElementById)
return
//change font size here to your desire
myclock="<font size='2' face='Arial' ><b>"+avs[sub]+"</b></font>"
if (document.layers){
document.layers.liveclock.document.write(myclock)
document.layers.liveclock.document.close()
}
else if (document.all)
liveclock.innerHTML=myclock
else if (document.getElementById)
document.getElementById("liveclock").innerHTML=myclock
;
sub++;
if(sub > <? echo $count - 1; ?>)
{
sub = 0;
}
setTimeout("show5()",5000)
}
window.onload=show5
and the problem comes on the array, if i put nothing on the txt file everythng works ok but if i try tiping any thing, used to be working but now comes with the "uncaught syntax error unexpected token illegal" and i checked the quotes and are fine.
This is a bad bad bad bad bad BAD idea:
var avs = new Array ( <?echo $jsr; ?>);
Look at all the escaping you have to do while you're building up $jsr in the PHP code. Whereas, if you were doing this properly, with json_encode(), you'd simply build up an array of values in PHP, e.g.
$jsr = array();
$jsr[] = "Look ma, a single quote '!!!!"
$jsr[] = 'Hey pa, double quote here "!!!';
and then
var avs = <?php echo json_encode($jsr) ?>;
I am trying to get some information from our database and then use it in javascript/JQuery and I think I might be doing something wrong with the scope of the coding.
Here is the current segment of code on my phtml page (magento)
<script type="text/javascript">
<?php
echo 'var $image-paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image-paths[';
echo $i;
echo '] = ';
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo ';';
}
?>
document.getElementById('main-image').href = $image-paths[1];
</script>
The bottom getElementById is just for testing to see if it really grabbed that image path. So far the php stuff is working and echo'ing the correct links. However, is simply echo'ing them not enough; does it actually register it into the javascript code?
Here is what my source code looks like on my server:
<script type="text/javascript">
var $image-paths = new Array();
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
$image-paths[1] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64566-a.jpg;
$image-paths[2] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-64568-a.jpg;
$image-paths[3] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/feeds/MrsMeyers/MRM-D43114-a.jpg;
document.getElementById('main-image').href = $image-paths[1];
</script>
But the image link does not change to image-path[1]. Any ideas?
Thanks in advance!
$image-paths[0] = http://staging.greencupboards.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5f b8d27136e95/feeds/MrsMeyers/MRM-64565-a.jpg;
^-- no quote here, or at the end of the string
You're producing invalid javascript. Pop up your javascript console (shift-ctrl-J in chrome/firefox) and you'll see the error.
Producing javascript dynamically is problematic. Anytime you insert something from a PHP variable/function, you should run that through json_encode(), which guarantees you get valid javascript:
echo json_encode($this->helper('catalog/image')->init($_child_products[$i], 'image'));
Or better yet, change the code to:
$links = array();
for ($i = 0; $i < count ($_child_products); $i++)
$links[] = $this->helper('catalog/image')->init($_child_products[$i], 'image');
}
echo '$image-paths = ', json_encode($links);
<script type="text/javascript">
<?php
echo 'var $image_paths = new Array();';
for ($i = 0; $i < count ($_child_products); $i++)
{
echo '$image_paths[';
echo $i;
echo '] = "'; // Here the starting of quotes.
echo $this->helper('catalog/image')->init($_child_products[$i], 'image');
echo '";'; // Here the ending of quotes.
}
?>
document.getElementById('main-image').href = $image_paths[1];
</script>
This should work now. Hope it helps.