Ajax.php, Script tag in php file
<script>
success: function(data) {
var message = data.message; //Json data
if ( data.status == 1 ) {
jQuery("#msgError").html(<?php echo JText::_(' + message + ');?>);
}
}
Is it possible to Echo JS variable in php like above?
Here is a best example,
<?php
// In php write following code
JText::script('COM_HELLOWORLD_MESSAGE');
<script>
// Using in Javascript like this
Joomla.JText._('COM_HELLOWORLD_MESSAGE')
// For your example look like
success: function(data) {
if ( data.status == 1 ) {
jQuery("#msgError").html(Joomla.JText._('COM_HELLOWORLD_MESSAGE'));
}
}
;
</script>
I already sent code to merge in joomla to make it more advanced. Please check it here https://github.com/joomla/joomla-cms/pull/6006
Also there are many ways to do it which you will find in above link.
Related
Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.
I'm trying to understand the relationship between a PHP script I'd like to run to keep track of progress and the front end work that has taken place. Its 2 clues in a game practice. Once the clue is inputted correctly everything occurs as below and I want to add a script that sends to MYSQL.
I'm working on the script now, but I'm trying to figure out at what point I'd introduce this. Is there anything I'd need within my PHP to distinguish it as AJAX. As in to run it in the background? Do I just "include" it as I would part of another larger PHP script?
The script in my mind will send a 1 if correct or 0 if still wrong. This way I can easily determine without having to deal with clues. The clues are irrelevant in my thinking, but what is your opinion on this?
// =====clue 1====================////////////////// clue 1 **************
//**********************************========================
$(document).on('click', '.btn-clue', function(){
if($i!=1){
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueTwo: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
});
} else {
$("#mySecondDiv").remove();
var mySecondDiv = $('<div id="mySecondDiv"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongOne').append(mySecondDiv);
}
}
});
// =====clue 2====================////////////////// clue 2*********=========
$(document).on('click', '.btn-clueTwo', function(){
if($i!=1){
//checking if textbox has desired value (1 in this case),
//in your application you would be passing the textbox value to
//ajax here and making the check at server side
var $two = $('#twoClueShow');
var x = $("#clueTwoInput").find('input[type=text]').val();
if(x == 'C' || x == 'CS') {
// if answer correct you should load data from ajax
// and append it to a container
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
} else {
$("#mySecondDivClueTwo").remove();
var mySecondDivClueTwo = $('<div id="mySecondDivClueTwo"><img src="images/check-x-mark.png" /></div>') .show('slow');
$('#clueWrongTwo').append(mySecondDivClueTwo);
}
}
});
Above is where I've been able to get. Now here is where I'm getting confused. I now want to send to the database that the answer has been answered correctly through AJAX, correct? Would I just include_once my php script in the commented area.
I was thinking of creating a script that filled a 1 if correct and 0 if not correct to make life easier. Let this do the work as I don't need to reintroduce the inputs or re use. This way once the page has reloaded I could simply not output the inputs again and use this info to determine what is displayed and where they are at in the clue game. Basically saving progress.
Is there something specific to use when building my normal PHP. I guess that and where to "include" it is where I'm confused.
MY button for reference
<div id="clueOneInput">
<input type="text" id="clue1" class="clue-text form-control" placeholder="Enter Clue 1 here and check"/>
</div>
<input type="button" id="clue1Input"class="btn btn-primary btn-clue" value="Check">
Update :
// =====clue 1====================////////////////// clue 1**********************************************************************========================
$(document).on('click', '.btn-clue', function(){
if($i!=1){
//checking if textbox has desired value (1 in this case),
//in your application you would be passing the textbox value to ajax here and making the check at server side
var $one = $('#oneClueShow');
var x = $("#clueOneInput").find('input[type=text]').val();
if(x == 'd' || x == 'dr')
{
//if answer correct you should load data from ajax and append it to a container
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueOne: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongOne").hide();
$("#mySecondDiv").remove();
$("#clueOne").remove();
$("#clue1Input").remove();
$one.show();
$("#clueOneInputCorrect").slideDown('slow').show();
$i++;
});
}
else
{
$("#mySecondDiv").remove();
var mySecondDiv = $('<div id="mySecondDiv"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongOne').append(mySecondDiv);
}
}
});
// =====clue 2====================////////////////// clue 2**********************************************************************========================
$(document).on('click', '.btn-clueTwo', function(){
if($i!=1){
var $two = $('#twoClueShow');
var x = $("#clueTwoInput").find('input[type=text]').val();
if(x == 'CS' || x == 'CSU')
{
$.ajax({
type: "POST",
url: "includes/post_clue_progress",
data: { clueTwo: "1", usernameClue: "<?php echo $manager; ?>" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongTwo").hide();
$("#mySecondDivClueTwo").remove();
$("#clueTwo").remove();
$("#clue2Input").remove();
$two.show();
$("#clueTwoInputCorrect").slideDown('slow').show();
$i++;
});
}
else
{
$("#mySecondDivClueTwo").remove();
var mySecondDivClueTwo=$('<div id="mySecondDivClueTwo"><img src="images/check-x-mark.png" /></div>').show('slow');
$('#clueWrongTwo').append(mySecondDivClueTwo);
}
}
});
In your Jquery
$.ajax({
type: "POST",
url: "yourScriptToUpdateDB.php",
data: { clue: "Wrong", user: "JoeBob" }
})
.done(function( msg ) {
// msg is any data that is echoed in the php script or output to screen is some way
$("#clueWrongOne").hide();
});
This question already has answers here:
Inserting php into js file
(5 answers)
Closed 9 years ago.
I want to send variable from php to js . I want to work this file like that js sends value php file then php works on this code and return again variable like true or false after that js controls and shows something users.I am Sorry for my poor English :D
<?php
if(!empty($_POST['a']))
{
$value=1;
echo '{"a":"'.$value.'"}';
}
else
{
?>
<script src="assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="assets/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript></script>
<script>
function sendValue($page,$value)
{
$.post($page, $value , function(data)
{
if(data.a==1)
{
alert("its work");
}
else
{
alert("oh no Houston we have a problem !!");
}
}
)};
</script>
<a href="#" onclick='sendValue("a.php",{a:"1"});' >blabla</a>
<?php
}
?>
str=$("input.classname").val();
or
str=$("input#idname").val();
it is inside js
and the easy way to send information by hidden input like this
<input type="hidden" class="classname" value="<?php echo "here the value you want to send"; ?>" />
If I understand correctly, you want to send data to PHP, then have PHP return data accordingly. Here is what I use to make an ajax call:
var sendData = "action=do_action";
sendData += "&value=" + $("input.value").val();
$.ajax({
url: "post.php",//Page to send our data to
global: false,
type: "POST",
data: sendData,
dataType: "html",
async:false,
success: function(data){
//We could return JSON and then just parse that, but I usually just return values like this
//create jquery object from the response html
var $response=$(data);
var results = $response.filter('div.results').text();//Or .html() if we want to return HTML to show
if (results == "true") {
alert("it works");
}else{
var reason= $response.filter('div.reason').text();
alert(reason);
}
}
});
And the PHP would look like:
<?php
$action = $_POST['action'];
if ($action == "do_action") {
if (true) {
echo "<div class='result'>true</div>";
}else{
echo "<div class='result'>false</div>";
echo "<div class='reason'>Houston, we have a problem!</div>";
}
}
?>
Which is the active directory in this case? Is it the one which contains a.php?
Also, you are sending back a string. You must convert that using JSON.parse().
Your response is a string, so it does not have an 'a'.
I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)
so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);