Basically when i insert textarea value into my mysql database, the new lines are not preserved.
At this point people will say use nl2br(). But that is a solution for people that can't get the new lines to display in html. This is not my problem.
I know this because i changed the column value and added newlines directly in phpmyadmin, and they all showed up in rendered html.
Somehow between the Ajax request > Post request > PDO Query Insert > PhpMyAdmin, the new lines are removed.
Thanks.
I found a semi solution.
Basically the new lines were getting removed in the ajax get request, before being
sent to my php script and inserted to db.
The solution is to do a post request with jQuery. Unfortunetly I could not find a vanilla js solution.
$.post(
'../scripts/saveNote.php',
{
note: textarea.val()
},
function (ajaxResponse) {
if ( ajaxResponse == "success" ) {
// Process success
}
}
);
Related
If someone click on clickme div the counter increases in the database. Currently when the page refresh the counter increases.
<div class="Hello">Click Me</div>
<?php
$find_counts = mysqli_query($conn, "SELECT * FROM ad_section");
while($row = mysqli_fetch_assoc($find_counts)){
$current_counts = $row['no_of_clicks'];
$new_count = $current_counts + 1;
$update_count = mysqli_query($conn, "UPDATE `ad_section` SET `no_of_clicks`= $new_count");
}
?>
Alright... so I am going to help you understand what AJAX is in a simplified practical manner.. because once you understand AJAX.. You'll be able to solve this and many other problems.
AJAX is not a 'language' or a 'technology' .. It's just an upgrade to how browsers can interact with servers.
Earlier (before AJAX, long before AJAX), when a browser had to request data/page from the server, it had to either refresh the page or request a whole new page.. and display it on a new window.. but it had absolutely no way of doing so in the "background" .. and then updating the currently displayed HTML page without any disturbance.
This is what AJAX solves.
So now.. through Javascript or Jquery.. (same thing) .. you can send a request to a server (to any end point on any web-server) with data... and the server.. then potentially has the ability to read the data you sent, process it in any way..and return back result in the form of data ..
The data going and coming is in the format of JSON (Javascript Object Notation) ..which is nothing but a way to encode data and arrays
So you send a JSON and the server gives you a back a JSON or an error page (404, etc.. )
The magic happens now...
Your page.. after receiving back the result from the server.. still on the same function execution that had sent the request ... will be able to open up the result.. and using Javascript/Jquery/DOM Manipulation.. plug in the results to the current HTML page or take any new action.. like display an alert, redirect, animate, etc..
So this is how it works:
Imagine you got a DIV upon which a click should set data update on the server and then get result from the server and refresh itself..
<div id='clickme'>People clicked ... <span id='howmany'>1</span></div>
<script>
//Not accurate code, I'm just writing from what I remember .. jquery
$('#clickme').click(function() {
//event captured on click on 'click me'
var nothing = ''; //there is no data to be sent, really.. because we will be getting the update from the server on how many people have clicked it..
//AJAX NOW... //sending a post request
$.post(
'https://mywebsite/index.php/incrementMe',
{data:nothing},
function(data)
{
//this is the function that will receive in its data the result back from the web-server function incrementMe
var result = JSON.parse(data); //parsing the JSON into javascript object/array
$('#howmany').html(result['updatedInfo']); //updatedInfo is the variable within the result that was sent back from the server.. which I then.. using DOM manipulation, plug it back into the span ID
}
);
//End of AJAX request... you didn't have to refresh the page..
</script>
On the server.. you'd have something like this: (writing PHP YII style)
public function actionincrementMe()
{
$data = json_decode($_POST['data']); //got the posted variable and decoded using a PHP function .. to get a PHP array/object
//well in fact, you don't even need this.. because.. there is no info coming to you from the front end .. but if you had, then this is how you'd receive it..
$newnumber = SQL to find out latest number + 1;
print json_encode($newnumber); //this is the function that will just answer back the front-end with a json formated data point..which is the variable new number..which you would then have received in the javascript function.
}
One of the ways is by doing it like this (only the steps i have included)
- Create a table with image id and click counter
- Implement a function on the image click or div click (if there are more images then you can use a generalized image click function
- Inside the function use ajax to implement the count increasing functionality
I'm a bit out of depth on this one so I hope someone has some insight. :)
I'm attempting to update a div using AJAX. The AJAX call sends a dropdown selection's value to a PHP file, which will be performing a pgsql query to grab some data. I've read in the RGraph tutorials that this data needs to be formatted to a JSON format so that RGraph can interpret it, and then fed to the JS that runs the RGraph views.
This question might actually be 2 separate questions, but I'll ask anyway:
Is there a standard way to grab the query's results in PHP and output them into a JSON format?
Where would I want to trigger the JS that uses the JSON data? I've tried hardcoding some initial data but the graphs don't seem to show up. However, I know the jQuery is performing the AJAX calls correctly because I see the div update (with an in-between "Loading..." message and then back to blank, indicating to me a null response), so I think I'm just not scoping this properly.
P.S. No, this time I'm not making a $_POST/$_GET mistake.
Any help would be appreciated. Thanks!
EDIT 1: Got this one. It was actually way easier than I thought. Still not scoping properly, however. Any help with how RGraph grabs a JSON object and displays it as a graph, and how to use AJAX to refresh the div with a new graph?
There's some SVG based AJAX demo pages here:
There was a bunch of links to the SVG basic AJAX demos here, but now the demos are no longer online - they are in the download archive. So download it here: https://www.rgraph.net/download.html#stable
There's a JSON documentation page here:
https://www.rgraph.net/svg/docs/the-svg-ajax-functions.html
And the code example from it is this:
<script>
GLOBALS = {};
function draw()
{
RGraph.SVG.AJAX.getJSON('/ajax/getdata.html?json', function (json)
{
if (GLOBALS.bar) {
RGraph.SVG.clear(GLOBALS.bar.svg);
}
GLOBALS.bar = new RGraph.SVG.Bar({
id: 'chart-container',
data: json.data,
options: {
// Add your own options to configure the chart
}
}).draw();
});
}
draw();
</script>
If you follow this example, create a page on your website that gets the data from your database and outputs it like this page does:
https://www.rgraph.net/getdata.html?json
Note that there's no HTML output by that page - just the JSON.
Then you can fetch that page using the RGraph.SVG.AJAX.getJSON() function like the code above does - from your webpage that has the chart on it - eg foo.html
So the foo.html is what would contain that RGraph code above.
And if you wanted it to repeat then you could add a timer so that subsequent fetches update it:
setTimeout(function ()
{
draw();
}, 1000);
I think that covers everything. I've probably left something out though.
Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.
I've got a PHP/Mysql app that lets users post text from a form. When I insert text from an HTML textarea into my mysql table, it's not keeping the carriage returns/line breaks. The text is not stored in the DB as "Hey SO, \n This is a new line". It's stored with white space in the column (exactly like it's typed), but there is no way for me to output it with nl2br() and keep the breaks. I'm escaping before inserting the text like so:
$foo_text = mysql_real_escape_string(ucfirst($_POST['foo_text']));
But even if I remove everything and just use the POST parameter, it still does the same thing. Would this have anything to do with me serializing and posting this form via ajax (I'm using JQUERY)? I found this on stackoverflow, but I don't really see a solution. I'm posting with:
$.ajax({
type: "POST",
url: "insertFooBar.php",
data: $("#foo_form").serialize(),
success: function(msg) {
ETC...
}
})
Is there something really obvious I'm missing here? I'm stuck...
Thanks in advance for any help!
The problem is that serialization should encode a line break as %D0%DA, but jQuery encodes it as %0A.
The only (graceless) solution i found was to get the form serialized string, then modify it with a replacement function such as :
function keepLB (str) {
var reg=new RegExp("(%0A)", "g");
return str.replace(reg,"%0D$1");
}
Once the serialized string is modified, i send it using the $.post() function.
Hope it will help !
Thanks for the answers. I ended up removing the serialize() and sending each parameter manually as a string. I added $("#foo_bar").replace( /\n/g, '<br>' )) to my textarea as a workaround and now I'm getting my breaks. Wish I didn't have to hack this to make it work, but it gets the job done.
I never got any problems inserting data from a HTML Form into database, either the form submitted normally or using AJAX.
Have you try to submit the form without AJAX? What is the result? I want to suggest you to use jQuery form plugins so you don't have to do the AJAX request manually.
I'm also want to suggest you to use AdoDB to save the data into database. This library provide a great cross-database abstraction. I haven't found any problems when insert/update the data, all value escaping is done automatically. Here is the example way to do update using AdoDB:
$data['foo_text'] = ucfirst($_POST['foo_text']);
$adodb->AutoExecute($tablename, $data, 'UPDATE', "id=$id");
I hope this libraries will help you.
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.