Send and receive div contenteditable - php

I want to be able to send content editable text to a php file to make some changes using ajax. This is how it is set up:
index.php
<div id="textArea">
<div contenteditable id="textField"></div>
</div>
</body>
</html>
<script>
var storyArea = $("#storyArea");
var textField = $("#textField");
var textArea = $("#textArea");
textField.on("keydown", function(e)
{
if (e.which == 13)
{
e.preventDefault();
var newVal = textField.text();
var exp = /\W/g;
if(!(exp.exec(newVal)))
{
$.ajax(
{
type: 'post',
url: 'story.php',
datatype: "html",
data: newVal,
success: function (data)
{
alert(data);
}
});
}
else
{
textArea.css("border", "2px solid #d45454");
textField.empty();
newVal = '';
}
}
});
</script>
story.php
<?php
$input = $_POST['newVal'];
echo $input;
?>
The problem I'm having is that my alert returns "Undefined index: newVal"
Thanks in advance.

You should use data: {newVal:newVal} to give the variable a name for the posted data. The function expects key:value pairs.

Related

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

Reset results if filter input is empty

I created a simple search as you type that replaces a DIV (which is originally populated by PHP). The function works fine. But I cannot get it to reset to original state if the input field is blank.
Here is the script:
$("#search_user").keyup(function()
{
var search_user = $(this).val();
var dataString = 'keyword='+ search_user;
if(search_user.length>3)
{
$.ajax({
type: "GET",
url: "../functions/search.php",
data: dataString,
success: function(server_response)
{
$('#list_users').html(server_response);
}
});
}
return false;
});
Original DIV code:
<div id="list_users">
<?php echo "
<div class=\"col-md-3\">
<img src=\"../assets/img/avatars/1.jpg\" class=\"user-avatar\">
<div class=\"caption\">
<h5>$rows[user_full_name] <br> <small> Designer</small></h5>
</div>
</div>
" ;?>
</div>
Thank you.
You mean
var $copy = $("#list_users").html();
$("#search_user").keyup(function() {
var search_user = $(this).val();
if(search_user=="") $("#list_users").html($copy);
else {
You can save the state of original html (On DOM ready, before you carry out any operations on it).
var originalState = $("#list_users").html();
$("#search_user").keyup(function() {
var search_user = $(this).val();
if(search_user=="") $("#list_users").html(originalState );

How to get the return value of a php function when calling from jQuery?

I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(data);
}
});
})

How can i load php file after sending ajax data

So I have 2 files file1.php with all the php and ajax, and file2.php with only php.
$_POST["there_id"] will be sent from file1.php page to file2.php through ajax.
file1.php code:
<div class="list_items">
<li><p>content here ...</p>
</div>
<div class="content_area">
//load ajax content here
</div>
$(".box").on("click", function(e) {
e.preventDefault();
var there_id = $(this).attr("id");
$.ajax({
url: "indexnew.php",
type: "POST",
data: { there_id : there_id}
});
});
file2.php code:
<div id="file2content>
<?php
$there_id = $_POST['there_id'];
$user_id = 5;
$fetch_data = regular_query("SELECT * FROM contents WHERE
(user_by = :me or user_by + :them) AND (user_to = :me or user_to = :them)",
["me" => $user_id, "them" = $there_id], $conn);
foreach ($fetch_data as $data) : ?>
<li><p>database data here</p>
<?php
endforeach;
?>
</div>
now what i want to do is when file2.php is done with php and list items are available i want to load file2contents to content_area on file1.php.
$(".box").on("click", function(e) {
e.preventDefault();
var there_id = $(this).attr("id");
$.ajax({
url: "indexnew.php",
type: "POST",
data: { there_id : there_id},
success: function(data) {
$('.content_area').html(data);
}
});
});
However, content_area should really be an id rather than a class so that it's unique.
Since you're just returning html, you can simplify it using the .load() function.
$('.box').on('click', function(e) {
e.preventDefault();
var there_id = $(this).attr('id');
$('.content_area').load('indexnew.php', {there_id: there_id});
});
success: function(data) { $(".content_area").html(data); }
adding the above to your AJAX call should do what you want if I understand you correctly.

jquery passing variables to php file

acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}

Categories