Miguel Mas Miguel Mas - 1 month ago 5
Javascript Question

How to show what is needed in retun call and not the whole page

I have in my index.php:

<?php
$sContent.='<script src="https://code.jquery.com/jquery-1.12.4.js"></script>';
$sContent.='<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>';
$sContent.='<script src="in.js" type="text/javascript"></script>';

$id=2;
$sContent.='<div id="agree">Agree to terms: <input type="checkbox" id="agreed" value=1></div>';
$sContent.='<br><br><div class="show"></div>';

if($_GET['f'] == 'showInfo')
{
$sContent.= 'This is the info about item id: '.$_GET['id'];
}

$sAction = $_SERVER['PHP_SELF']."?id=".$id."&f=showInfo";
$sDest.= '<br><input class="'.$id.'" type="button" id="'.$id.'" name="'.$id.'" value="Click to show info about item '.$id.'" onClick="javascript:showInfo(\''.$sAction.'\');">';

$sContent.= $sDest;
echo $sContent;
?>


And in my js file:

function showInfo (action)
{

var aryAction = action.split('?');
params = aryAction[1];
var theUrl = 'index.php';
alert( aryAction[1]);
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
$('.show').html (data);
}
});
}


This shows the whole index.php inside the div with the class 'show'. I don't want thant, I just need 'This is the info about item id: 2' in that div, nothing else.

I've been reading other similar posts and maybe I shouldn't be using the ajax function, any ideas on how to do it?

Thanks a lot !!

Answer

You will have separate HTML content from string. Put both thing in if else clause then it will work:

<?php 
$sContent = '';
if($_GET['f'] == 'showInfo') 
{
    $sContent .= 'This is the info about item id: '.$_GET['id'];
}
else
{
    $sContent .= '<script src="https://code.jquery.com/jquery-1.12.4.js"></script>'; 
    $sContent .= '<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>'; 
    $sContent .= '<script src="in.js" type="text/javascript"></script>';

    $id=2;
    $sContent .= '<div id="agree">Agree to terms: <input type="checkbox" id="agreed" value=1></div>';
    $sContent .= '<br><br><div class="show"></div>';

    $sAction = $_SERVER['PHP_SELF']."?id=".$id."&f=showInfo";
    $sDest .= '<br><input class="'.$id.'" type="button" id="'.$id.'" name="'.$id.'" value="Click to show info about item '.$id.'" onClick="javascript:showInfo(\''.$sAction.'\');">';

    $sContent .= $sDest;
}
echo $sContent;
Comments