1
\$\begingroup\$

I have used jQuery AJAX for my development. Below I have added example code for AJAX request and response.

ajax.php

$queView = array();

$queView['time'] = 40;
$queView['name'] = "Level hard";
$queView ['noQuestions'] = 10;
$queView['queDetails'] .= "<h1>Some html content</h1>";
$queView['queDetails'] .= "<img src='root/imag/imag.jpg' />";


foreach($users as $user){
   $queView['queDetails'] .= "<p>".$user['name']."</p>";
   $queView['queDetails'] .=  "<p>".$user['address']."</p>"; 
}

echo json_encode($queView);

JavaScript function with jQuery;

function showQuestions(){

 $.ajax({
        data:{showQues:'1',attemptedQue:queId,selAnswer:checkedAns,timeTaken:timeTaken},
        url:'include/ajaxAttempt.php',
        success: function(data){

            data = $.parseJSON(data);

            $('#time').html(data.time);
            $('#name').html(data.name);
            $('#noQuesitons').html(data.noQuestions);
            $('#queDetails').html(data.queDetails);
        },

        error:function(xhr,err){
            alert("Error");
        }
    });    
}

$queView['queDetails'] has a lot of HTML content.

Is this a good practice?

\$\endgroup\$
2
\$\begingroup\$

If you're passing information, pass only information, not markup. Alternatively completely generate the HTML markup on the server-side, and just apply it on the client side. There's no point in combining the two, and if done wrong you could cause double escaping issues.

Second, don't use alert() as a debug function. Use console.log() and use your console.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.