Mysql not retaining line breaks from Jquery ajax post? - php

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.

Related

Linebreaks from textarea not preserved in mysql

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

html object to call php and return string

I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">
where object.php just returns a string, like
<?php print "firstText:Hello World";?>
I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with re-submitting with POST/GET.
Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent
which I can then work with.
Thanks
Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
// response contains the string returned by your PHP page.
});
PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?

Upload file using jQuery and Ajax

I have a form that I am sending to the server using jQuery $.post method. I am sending several fields with something like:
var myName = "Pedro";
var myDescription = "Description of Pedro";
$.post("~/insert_user", { name: myName, description: myDescription }, function(data){
alert("Successfully inserted " + data.name + " in DB");
}, "json");
This works great, as I take the values in insert_user.php and treat and insert the in the data base.
What if I need to add a field to my form to let the user upload an image?
How would I do that in my $.post call and how would I get it in the PHP?
I am using Symfony2.0, by the way, just in case it changes something. But the important part is how to add a file typed field to the ajax call.
Thanks in advance.
Pedro
You will find it would be a lot easier to use a pre built jquery plugin. My favourite is uploadify http://uploadify.com.
Its simple and easy to use and it will save you a lot of time trying to figure out a method of your own <>
$.post is the same as the code block bellow. In order for you to do what you need to you need to change it to use this atleast and then things will become simpler. So start by changing the $.post to this
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Then add a parameter in the ajax block contentType : "multipart/form-data" or try mimeType (cant remember so clearly) and in the data : $("#form").serialize(), that should work.
please tell me if it didn't work
--NEW EDIT LOL-- Excuse my blind coding, you may need to test this
I did a bit more research and came across this. You need to build this array and add it to the data in your ajax block
var files = new FormData($('#fileinputid'));
jQuery.each($('#fileinputid')[0].files, function(i, file) {
files.append(i, file);
});
If what i read was accurate you should be able to pass that array with the rest of the ajax data. Although i am not completely sure how to add it to the serialized data.
Please test this and let me know. if it doesn't work ill do a full javascript script test for you and then post it here
This tutorial might help: Nettuts+: Uploading Files With AJAX
Make iframe and put form in it, submit the form and voila. Or you can use one of these AJAX File upload scripts
I finally used this:
http://malsup.com/jquery/form/#faq
It just works great for what I need.
Thank you guys for your help.

A clean way of obtaining values from inputs and sending them to php file

I am looking for a really simple way of getting all the values from all input elements (and some dividers as well) and then quickly sending them to a PHP file with an already prepared submit function.
I have came up with a very crude solution but it needs to be heavily optimized.
For now when I click submit button I call a function
function $('#submit').click(function(){
var $divValues = new Array();
$divValues[0] = $('#divName').html();
$divtValues[1] = $('#divImgName').html();
var $values;
$values = $(':input').serializeArray();
$fileName = "php.php?firstVal=\""+$divValues[0]+"\"&secondVal=\""+$divtValues[1]+"\"&thirdVal=\""+$values['firstValName']+"\"&ect..."
//then i simply call the ajax function which will send the information to the php file
fetch($fileName);
});
maybe i could use the fact that the names of values in my associative array and the names of variables retrieved in my php file match and instead of setting my filename to ..."&thirdVal=\"" ... I would instead use the name of the $values['firstValName'] which in this example would be third value (although i have no idea how to do that)
or maybe there is an even easier way to accomplish what im trying to.
Any ideas on how to implement this piece of code in a nice manner??
Update:
For now I don't have a form element in my html but I can easily add one as soon as I see a solution that requires it to make the code simpler...
I know I can use serialize() function but my questions is about a nice way of dealing with the array that gets returned. (or maybe using 2 arrays one with name other with value or a 2 dimensional array)
Either way I just wish to see what is an easy way of both getting the data and creating the $fileName with correct values for the PHP file
I would appreciate some code or pseudocode in the answer that shows a simple way of creating the fileName with all the values
If anybody doesn't understand what I am asking or needs some clarification then they should feel free post a comment below so I can try to make myself clear.
Since you're using jQuery, you could use its AJAX methods with serialize() applied to the entire form. You can read documentation about it by clicking here. Also you can read documentation about jQuery's AJAX methods by clicking here, here and here.
In response to your request, here is a really simple example:
$.post("test.php", $("#testform").serialize());
You could really get the rest of what you need on how to use $.post or $.get functions from the documentation I referenced.
Serialize also takes care of urlencoding all the variables so you don't have to worry about that.
EDIT:
It's not really necessary to have a form. You could just do what you are trying to do with serializeArray() above, except (a) $(':input') does not select anything and (b) you should use serialize() and not serializeArray(). So without a form, the code would look as follows:
$.post("test.php", $("input,select,textarea").serialize());
This will properly request the script with the data encoded correctly and you can then read it in PHP script from $_POST or $_GET depending on whether you used $.post or $.get to request the script.

Sending PHP json_encode array to jQuery

ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})

Categories