I have a JQuery that creates an Ajax call to a PHP script. My PHP script echos 2 strings: check_1 and check_2. The alert() is displaying both the strings in the output. How to get only one string in the output?
PHP:
<?php
echo "check_1";
echo "check_2";
?>
JQuery:
$.get("check_ajax.php", function(data) {
alert(data);
});
send the server response as json ... and get it...
try this
jquery
$.get("check_ajax.php", function(data) {
alert(data.check_1); //alert the first object "check_1"
alert(data.check_2); //alert the second object "check_2"
},'JSON');
php
<?php
echo json_encode(array("check_1"=>"check_1","check_2"=>"check_2"));
?>
there is couple of ways to do this. one way is string manipulation and removing the text after the new line char of the first string. The other method is actually send your data from php to javascript using json. So in your php file you would create a data structure like an array.
<?php
$string = array("check_1", "check_2");
echo json_encode($string);
?>
in the javascript side then you can retrieve the first element from that json array.
$.get("check_ajax.php", function(data) {
alert(data[0]);
});
You can use like this : -
<?php
$html = "check_1";
$html1 = "check_2";
echo $html.'~~~'.$html1;
?>
JQuery:
$.get("check_ajax.php", function(data) {
var res = data.split('~~~');
alert(res[0]);
});
We have the same problem before, but what I do as an alternative solution was to have a conditional statement to separate multiple values returned by php
if(your condition here) {
echo "check_ 1";
} else {
echo "check_ 1";
}
Hope it helps :)
PHP:
<?php
$text = array("check_1", "check_2");
die(json_encode($text));
?>
jQuery:
$.get("check_ajax.php", function(data) {
var response = JSON.parse(data);
alert(response[0]); // for "check_1"
alert(response[1]); // for "check_2"
});
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.
How to store PHP session variable in JQuery variable.
I have one php file where i am using session variable as
$local_session = $_SESSION['sessionusername'];
and that PHP falls also using one .js file where i want to store this $local_session which is PHP variable to JQuery variable
It is as
session_start();
ob_start();
if(!$_SESSION['sessionusername'])
{
header("location:index.php");
}
else
{
include ('connection2.php');
include('PHP/combo_val.php');
$local_session = $_SESSION['sessionusername'];
}
and after this my HTML code starts
You might do something like this in your java script:
var sessionVar = '<?php echo $local_session; ?>';
and then use this global JS variable wherever in your page.
You can write some php-script which return session data, for example
JS:
//my.js
$.getJSON( "myssesiondata.php", function( data )
{
console.log(data);
}
PHP:
<?php
//mysession.php
return json_encode($_SESSION);
?>
# Axel Amthor
My JQuery Code is as
var lgn_usr = '<?php echo $_SESSION["sessionusername"] ?>';
alert(lgn_usr);
and it display
<?php echo $_SESSION["sessionusername"] ?>
as message
# Axel Amthor
My Jquery file code is as:
$(document).ready(function() {
$('#submit').click(function() {
submit_fxn();
$('#form_nuser').submit(function(e) {
return false;
});
});
function submit_fxn(){
var check_flag = 0;
var lgn_usr = '<?php echo $local_session; ?>';
alert(lgn_usr);
};
});
OKay, I got it. $_SESSION is a PHP array, we cannot set it on the client side via Javascript. The value has to be sent to the server to be stored in the array. Now, I am going for other method....
I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>
Your returning data is in the response parameter. You have to echo your data in PHP to get the results
Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax
JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);
You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).
i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it
The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);
I saw many examples related but I'm still confused. I'm using ajax (which I don't know much about) to get the results of a file updated every xxx seconds. It's working perfectly if I pass just one variable, but what is the best way if I need to pass an array from php through it?
Structure is simples:
show_results.php
<?php
include_once('modWhosonlineCustom.inc.php');
$document->addScript("http://code.jquery.com/jquery-latest.js");
$document->addScript("ajax.js");
$array_name = modWhosonlineCustom::getOnlineUserNames();//the array I need to pass to javascript variable
?>
<script>
var whosonline = '<?php echo "$array_name"; ?>';
</script>
<div id="results"></div>
Ajax code than would have more than one param to build in the url load:
ajax.js
$(document).ready(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]");
var refreshId = setInterval(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
And back to PHP response page, how could I use again the array params passed through url?
response.php
<?php
$names = $_GET['array_name'];
foreach ($names as $name) {
//do something
Any suggestions is really appreciated, thanks!
EDIT
Thanks guys, I think I'm the right way now, but ramains the problem to pass this array through a url in the javascript. Or maybe I'm not getting it in the right way in the php end callback file. I'll show you what a modifyed:
show_results.php
...
<?php
$names = modWhosonlineCustom::getOnlineUserNames();
?>
<script>
var whosonline = '<?php echo "json_encode($names)"; ?>';
</script>
ajax.js
$(document).ready(function() {
$("#atendentes").load("response.php?names=" + whosonline);
var refreshId = setInterval(function() {
$("#atendentes").load("response.php?names=" + whosonline + "&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
response.php
$users = $_GET['names'];
$users = json_decode($users);
echo "user: $users";
$names = $users;
foreach ($names as $name) {
...
Here in the other side I'm getting: Warning: Invalid argument supplied for foreach() in response.php on line 33, and the echo is empty
What is missing?
To pass arrays/objects from PHP to JavaScript you may use the json_encode()/json_decode() functions.
Your code wouldn't work. If you have
$arr = array('a', 'b', 'c');
echo $arr;
you actually get
Array
as the output. Not the contents of the array. To "output" an array from PHP to JS, you have to convert it to native Javascript, which is where json_encode comes in:
<?php
$arr = array('a', 'b', 'c');
?>
var js_array = <?php echo json_encode($arr) ?>;
which will produce
var js_array = ["a","b","c"];
As a general rule, anytime you are using PHP to generate javascript code and are filling in Javascript variables with PHP values, you should use json_encode to ensure that you're generating valid Javascript. Any syntax errors and the whole Javascript code block is dead in the water once the client starts trying to execute it.
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'.)