rest of the string after single quote is thrown away - javascript

CKEDITOR.instances.content.getData() has a text like This is a' ball .
i send the following data to a php page using ajax to store it to a database
var data="answer_body="+CKEDITOR.instances.content.getData()+"&userpost_post_id=<?php echo $contents[0]->post_id;?>&users_user_id=<?php echo $userdata->user_id; ?>";
But the answer body throws away rest of the text after quote.
$answer=addslashes($_POST['answer_body']);
echo $answer; // it contains only -----------This is a
how i can solve this problem?

Try below Ajax code to send data from client to server
$.ajax({
type: 'POST',
url: "Here_Your_Server_Url",
data: {
answer_body: encodeURIComponent(CKEDITOR.instances.content.getData()),
userpost_post_id: "<?php echo $contents[0]->post_id; ?>",
users_user_id: "<?php echo $userdata->user_id; ?>"
}
})
Try below code in PHP
$strAnswerBody = urldecode($_POST['answer_body']);

Related

transfer data from localstorage to same php file and recall data to variable

I have data in localStorage and POST successfully to the self php file using ajax as code below:
<script type="text/javascript">
var cartID = JSON.parse(sessionStorage.getItem("magiohang"));
console.log("your cart ID is:"+cartID);
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: {cartID: cartID},
success: function(data){alert("data transfered successfully")}
});
</script>
then I want to recall this data to a variable inside this php file so that I can send it to my email. Code as below:
<?php
$name = "";
error_reporting(E_ALL); ini_set('display_errors', 1);
if (isset($_POST["cartID"])) {
$name = $_POST["cartID"];
}
echo $name."\n";
$values = json_decode($name);
echo "your cartID is: ".$values."\n";
?>
I test it in inspect view there is no error message but the variable $name doesnot have recalled data. Please help me to fix it. Thank you.
You are most likely missing the JSON.stringify call on your data:
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: JSON.stringify({cartID: cartID}),
success: function(data){alert("data transfered successfully")}
});

AJAX POST not working, php doesn't create session

I want to send id of element to php and create session for this.
This is piece from php file:
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['p_id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php
}
?>
And in this file javascript code:
$(document).on('click', '.open_item', function(event){
var data_item = this.getAttribute("data-id");
$.ajax({
url: 'get_id.php',
type: 'POST',
data-type: 'json',
data: { id: data_item },
contentType: 'application/x-www-form-urlencoded',
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
This is get_id.php:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
?>
I have tried also without content types and without json. "var data_item" prints id correct, but php doesn't create session and in console also clear(nothing).
The reason that you are not getting data in session is, you are not assigning proper value to session. Also it should be json_decode not json_encode.
replace
$_SESSION['item_id'] = json_encode($_POST);
with
if (!empty($_POST['id'])) {
$_SESSION['item_id'] = json_decode($_POST['id']); // use json_decode
}
It seems to me that you are making some small mistake in your code like you are echoing $row['p_id'] while your query should return id instead p_id also you are making mistake in ajax you are sending data-type JavaScript assuming your code is subtracting so try to use this code i code below.
// modify your php code
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php } ?>
// modify your jQuery
$(document).on('click', '.open_item', function(event){
var data_item = $(this).data("id");
$.ajax({
url: 'get_id.php',
type: 'POST',
dataType: 'json',
data: { id: data_item },
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
<?php
session_start();
header("Content-Type: application/json", true);
$_SESSION['item_id'] = json_encode($_POST["id"]);
echo json_encode(['data_id' => $_SESSION['item_id']]);
?>
You can use
$_SESSION['item_id'] = json_encode($_POST['id']);
instead of
$_SESSION['item_id'] = json_encode($_POST);
this will work fine.
I don't know what you are trying to do, but from your JS, it looks like that you are expecting that the PHP script --which you post some data to it-- to return a json with the data you have just posted in it. In that case, try this, change your get_id.php to be like:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
echo $_SESSION['item_id'];
?>
I'd troubleshoot this by making sure the click handler is actually going off. Put alert("clicked"); as the first thing in the in the click handler to make sure.
For the meantime, remove the contentType in the json call. Also remove the dataType (data-type) entirely. On the php side, replace the header() line so (as mentioned) the php is just:
session_start();
$_SESSION['item_id'] = $_POST["id"];
echo $_SESSION['item_id'];
Do not use json_encode/decode right now. From your code, it is not needed.

How to do a AJAX click post on every PHP foreach result

I have read multiple sorts of answers but none works.
what i try to do is to make every result from a PHP foreach loop clickable and then send that data with AJAX to a other PHP file, the problem now is that whatever i do, only the last foreach result always get send and not the result that i clicked on? (without Database)
the loop exist in a function functions.php:
public function getForeachResult ()
{
$response = $this->GetObject($parameters);
include 'template.php';
}
the template that handles the result template.php:
<?php
foreach ($response->Result->List as $key =>$value) {
?><table id="mytable"><tr>
<th>ID</th>
<th>Date</th>
<th>firstname</th>
<th>lastname</th>
</tr>
<?php foreach ($value as $key=>$value) {?>
<tr class="myrow">
<td><?php echo $value->ID; ?></td>
<td><?php echo date("d-m-Y", strtotime($value->Time)); ?></td>
<td><?php echo $value->FullName; ?></td>
<td><?php echo $value->LastName; ?></td>
</tr>
<?php } ?>
</table><br />
<?php } ?>
In template.php the AJAX script is called at the bottom:
<script>
$('.myrow').click(function() {
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: <?php echo $value->ID ?>}
}).done(function( msg ) {
$('.Data').html(msg);
});
});
In post.php where the dat is send i only get the last result of the foreach loop
post.php:
if($_POST['action'] == 'goTo') {
var_dump ($_POST);
}
so how can i make sure AJAX sends the data that i clicked on?
Try:
`<td class="id"><?php echo $value->ID; ?></td>
<script>
$('.myrow').click(function() {
var id = $(this).find('.id').text();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: $(this).find(td:first).text().trim()}
}).done(function( msg ) {
$('.Data').html(msg);
});
});`
I think your php expression in the data field just hold the last id because you looped in your html but in your ajaxcall your are already in the end of the loop.
Edit: took the comment
So, to explain the why, i think you mess up a little things in your head and that causes a confusion. Your PHP file does send nothing in Ajax to another PHP file. Your PHP file builds an HTML page, and the Javascript in this page sends data in Ajax.
Keep that in mind, that in PHP you build a future JS code that is executed later. If dynamic variables have to be retreived during the Ajax call or for its data to send, it will be JS that will do it, not PHP.
So like others answers suggest, you have to retreive the id in JS, not PHP.
Only you need to do is get the clicked id just like this
$('.myrow').click(function() {
var id = $(this).children("td.first").text();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: id}
}).done(function( msg ) {
$('.Data').html(msg);
});
It will work fine no need to change your table html
You need use traverse to find the each row value dynamically on click like this
var clicked_row_id = $(this).find('td:first').text().trim();
Data should be send like this
data: { action: 'goTo', value: clicked_row_id }
Update 1 :
$('.myrow').click(function() {
var clicked_row_id = $(this).find('td:first').text().trim();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value:clicked_row_id }
}).done(function( msg ) {
$('.Data').html(msg);
});
});
At the end of foreach loop you will only have last iteration value only in $value->ID; . so when you echo it in js. so it will echo only last value .

escaping apostrophe in javascript shows extra backslash

I'm using language files with Codeigniter to display any kind of messages, such as:
$lang['home']['msg1'] = "We couldn\'t proceed...";
I'm calling these variables in Javascript (in my footer) with the following code:
var Settings = {
base_url: '<?php echo base_url(); ?>',
hire_text: '<?php echo $this->lang->line('hire'); ?>',
msg1: '<?php echo $this->lang->line('home')['msg1']; ?>'
}
Unfortunately I haven't managed to handle properly sentences with an apostrophe. I've tried the following:
$lang['home']['msg1'] = "We couldn\'t proceed...";
shows:
We couldn\'t proceed...
and
$lang['home']['msg1'] = "We couldn't proceed...";
returns a Javascript error message
After reading multiples questions/posts I still can't figure out the proper way
You are breaking both expressions (JS and PHP) by using single quotes with no escaping. You can escape inside quote mark or use combination of single and double quotes.
var Settings = {
base_url: "<?php echo base_url(); ?>",
hire_text: "<?php echo $this->lang->line('hire'); ?>",
msg1: '<?php echo $this->lang->line(\'home\')[\'msg1\']; ?>'// should be working either way
}

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

Categories

Resources