jquery ajax call back request bringing html from php file - php

I am making an ajax request where I will type name in input box to search data from db, It's working fine,
<script>
$(document).ready(function(){
$('input#name-submit').on('click', function() {
var nameVar = $('input#name').val();
if($.trim(nameVar) != ''){
$.post('records.php', {name: nameVar}, function(data){
$('div#name-data').text(data);
});
}
});
});
</script>
----php
if(isset($_POST['name'])){
$name = $_POST['name'];
echo $name;
Now the problem is when I embed the html into php and echo it, It prints the html also
echo "<div class='tblDiv'>";
echo "</div>";
result: <div class='tblDiv'> Name </div>
how to avoid that and get the result in style?

You need to use .html() instead of .text()
$('#name-data').html(data);
.text() will not parse the html content, it will escape the html and print the passed value as it is

Related

Display PHP echo in a textarea using AJAX/jQuery?

I am trying to display a PHP echo in a textarea using AJAX that auto refreshes every second. So far everything I do this doesn't want to work and I get nothing in the textarea.
Here is my code:
<?php
$stmt = mysqli_prepare($db_conx,"SELECT message FROM chat WHERE asker = ?");
$stmt->bind_param('s', $asker);
$stmt->execute();
$stmt->bind_result($message);
/* fetch values */
while ($stmt->fetch()) {
$currvalue[] = array('message'=>$message);
}
echo $message;
echo '333333333';
?>
HTML code:
<textarea id="chattercontent" style="width:90%; height:150px; resize:none;" readonly></textarea>
AJAX/jQuery code:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php",
dataType: "text", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 1000)
}
});
}
load();
});
</script>
What happens with the code above, I get the echo '333333333'; in my textarea like so 333333333 which is good and fine. But I don't get the echo $message; in my textarea.
I have checked to see if the MySQL table and column to see if its not empty and I can confirm that it is not empty and it has some values in it.
I also, viewed the file.php page directly from the browser and it does echo $user_message; properly. But it doesn't get echoed in AJAX call and in my textarea.
Could someone please advise on this issue?
Your $message variable is not being assigned anywere
replace your echo $message; with
print_r($currvalue);
and you will see your output.
In other words, you $message variable contains nothing! (assign it something with $message = 'someting';)

get variable to jQuery from php

this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name, email: email}, function(data){
$('#show').html('settings saved').fadeIn(500).delay(2000).fadeOut(500);
alert(data);
});
});
If you want to communicate between JavaScript and PHP, the best way is to create a hidden-inputfield in fill in the errors-variable. And then you can read out the value with jQuery.
The inputfield:
<input type="hidden" value="<?php echo $error; ?>" id="errors" />
And the jQuery-Code:
var errors = $("input#errors").val();
You can't place PHP code inside "javascript" file, PHP code must be in PHP file.
The below code can work if it's placed in .php file:
<html>
<head>
<title>javascript test</title>
<script>
var error = '<?php echo $error;?>';
alert(error);
</script>
</head>
<body>
</body>
</html>
I am assuming that your $error will by different depending on the $_POST values.
If your response header is in HTML, then you can do something like this.
// in your JS codes.
$.post('settings.php', function(response) {
$('#show').html(response).fadeIn(500).delay(2000).fadeOut(500);
});
// in your php codes.
<?php if(isset($error)) { echo($error); } else { echo("setting saved"); } die(); ?>
Anything you want in your js from server side has to come as AJAX or JSON response. echo it from your php function and get it as AJAX or JSON in javascript.
$.getJSON('url for the php file', function(data){}
And in the php file just echo the value
see http://php.net/manual/en/function.json-encode.php
Or take a hidden input field and put the value there. You can get that value from js using the 'id' or 'class' attribute

How to make JQuery alert only one string from PHP?

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"
});

How to get back data from php variable to jquery variable using jquery $.POST method

In the below code the $.POST method passes two variables to the php file empProfile.php which retrieves the employee profile from the database. Know I want to receive ID and Name from the php file to the jquery variables. Can someone help me.
data = {
personnelNo: $('#personnelNo').val(),
cnic: $('#cnic').val()
} //end of data
$.post(
"checkEmployee.php",
data,
function(data) {
var ID =; Name=;
} // end of function
); // end of post
//} //end of if statement
}); // end of blur
Try this
var ID = '<?php echo $yourId;?>';
var Name='<?php echo $yourname;?>';

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

Categories