Ajax not fully posting data to php file - javascript

Getting a really strange error with Ajax not sending the entire string data across to the php script.
The string is
"<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-font-size:11.0pt;
font-family:"Verdana",sans-serif;mso-ansi-language:DE">Gold GoldGold Gold Gold Gold<o:p></o:p></span></u></b></p>
<p class="MsoNormal" style="text-align:justify"><span lang="EN-GB" style="font-size:10.0pt;mso-bidi-font-size:11.0pt;font-family:"Verdana",sans-serif"> </span></p>"
but what arrives at the php script is only (Seen through DB submission and the php $result test.
"<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-font-size:11.0pt;
font-family:"
I have tried to check through multiple methods of why this is happening but just cant figure it out at all.
Here is my Javascript code and php code.
JS:
function Send_upload_news()
{
get_title = document.getElementById('Germ_title');
get_date = document.getElementById('Germ_date');
input_title = get_title.value;
input_date = get_date.value;
input_content = $("div.nicEdit-main").html();
//console.log(input_content);
var Data = '&input_title='+input_title+'&input_date='+input_date+'&input_content='+input_content;
//console.log(Data);
$.ajax({
url : "uploadNews.php",
type: "POST",
dataType: 'text',
data : Data,
success: function(result){alert(result);},
/* success: function() {
alert('Post has been uploaded to Database');
}, */
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('There is an error, screenshot this error and send to Admin : ' +textStatus+" - "+errorThrown);
}
});
nicEditors.findEditor( "Germ_content" ).setContent( '' );
get_title.value = "";
get_date.value = "";
$('html, body').animate({ scrollTop: 0 }, 'slow');
};
pHp:(uploadNews.php)
<?php
//Database info
$db_host = "localhost";
$db_username = "";
$db_pass = "";
$db_name = "";
//connect db
$connMS = new mysqli ( $db_host, $db_username, $db_pass, $db_name );
//grab data
$this_title = $_POST['input_title'];
$this_date = $_POST['input_date'];
$this_content = $_POST['input_content'];
$result = file_put_contents ( "test.txt", $this_content);
//create query and execute
$sqlupdate_news = "INSERT into news_content(germ_title, germ_date, germ_content) values ('$this_title','$this_date','$this_content')";
mysqli_query ($connMS,$sqlupdate_news);
//close
mysqli_close($connMS);
?>
Im using WYSWYG Nicedit as my text area
If there is somebody that can help me figure this out I would be very grateful.

The problems with your code is you are not encoding the values. So that will mess up the values. Plus you have a leading & which makes no sense. You can manually encode all the values with encodeURIComponent or you can let jQuery handle that for you.
jQuery does the encoding for you when you use an object.
function Send_upload_news() {
var get_title = document.getElementById('Germ_title');
var get_date = document.getElementById('Germ_date');
var Data = {
input_title : get_title.value,
input_date : get_date.value,
input_content : $("div.nicEdit-main").html()
};
$.ajax({
url : "uploadNews.php",
type: "POST",
dataType: 'text',
data : Data,
success: function(result){alert(result);},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('There is an error, screenshot this error and send to Admin : ' +textStatus+" - "+errorThrown);
}
});
nicEditors.findEditor( "Germ_content" ).setContent( '' );
get_title.value = "";
get_date.value = "";
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
And you really should use var so your application is not full of global variables.

You have to escape(encode) sent parameters to the server, to avoid confusion of characters like ampersand(&)
Change this:
var Data = '&input_title='+input_title+'&input_date='+input_date+'&input_content='+input_content;
To this:
var Data = '&input_title='+encodeURIComponent(input_title)+'&input_date='+encodeURIComponent(input_date)+'&input_content='+encodeURIComponent(input_content);

Encode your string properly before firing off the Ajax.
var title = encodeURIComponent(input_title);
var date = encodeURIComponent(input_date);
var content = encodeURIComponent(input_content);
var Data = 'input_title='+title+'&input_date='+date+'&input_content='+content;
$.ajax({
...
data : Data,
...
To make your life easier, why not just use object notation and let jQuery handle the encoding?
$.ajax({
...
data : {
input_title: input_title,
input_date: input_date,
input_content: input_content
},
...

Related

JQuery AJAX is unable to execute success function

What I'm using: JQuery, mysql_crud.php class
I have a class for donor, inside the class I created a function to add a donor into the database. Any result made by the function will return an array.
donor-class.php
public function addDonor($foo, $bar, $soap, ){
.
.
$message = array('message' => 'Message for user here');
return $message;
}
The class is then executed by another php file which will return JSON data
add-donor-function.php
$res = $donor->addDonor($foo, $bar, $soap);
header('Content-Type: application/json');
echo json_encode($res);
This PHP file will return JSON data
{
"message" : "Message for user here"
}
I also have a javascript file to run an ajax function
js_add_donor.js
function addDonor() {
var name = $('#name').val();
var ic_no = $('#ic_no').val();
var gender = $('#gender').find(":selected").val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var b_type = $('#b_type').find(":selected").val();
var dob = $('#don').val();
var address = $('#address').val();
var district = $('#district').find(":selected").val();
$.ajax({
url: "/firstblood/php/function/donor-management/add-donor-function.php",
type: "POST",
data: {name:name, ic_no:ic_no, gender:gender, email:email, mobile:mobile, b_type:b_type, dob:dob, address:address, district:district},
dataType: 'json',
success: function(result, status){
// Below codes won't run
alert('heloo');
alert(status);
$('#response').text(success.message);
}, error: function(xhr, status, error) {
// Below codes run
alert(xhr.status);
alert(status);
alert(error);
}
});
return false;
}
addDonor() is used for a button when clicked.
When the code is executed, the window alerts "200", "parseerror", and "SyntaxError: Unexpected token < in JSON at position 0"
Where am i wrong here ?

Inserting a data on a database using AJAX/JSON/Jquery

I'm trying to create a small chat application but for the sake of minifying the bytes being transferred is there any other way on writing this javascript that is less heavy than this code?
Here is my javascript:
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = AjaxRetrieve();
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
Can this also be done on a JSON format too? because I think some says that json is lighter.. not sure though
here is my php code
$con = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt=$con->prepare($sql);
$stmt->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt->execute();
foreach($stmt->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$text=$_POST['message'];
$sql4 = "INSERT INTO $tblname2(msgid,username,message_content,message_time,recipient)VALUES(:aid,:a,:b,NOW(),:c) ";
$stmt5 = $con2->prepare($sql4);
$stmt5->bindParam(':aid',$tblpre,PDO::PARAM_STR);
$stmt5->bindParam(':a',$_POST['name'],PDO::PARAM_STR);
$stmt5->bindParam(':b',$text,PDO::PARAM_STR);
$stmt5->bindParam(':c',$usern,PDO::PARAM_STR);
$stmt5->execute();
As user2401175 saies. Why not use a framework, thats what they are here for.
jQuery is really simple and easy to understand.
You could try adding this, just before your "" tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Under this include of jQuery, you may now use the jQuery Post method to do your ajax request.
In html Use
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
then Create javascript object like this
var changePacket = {
date1:value1,
data2:value2
}
And send Ajax request
$.ajax({
url: "phpFile.php",
dataType: 'json',
type: 'POST',
data: {json:JSON.stringify(changePacket)},
success: function(response) {
alert('hip hip hurray');
},
error: function(response) {
alert('some thing wrong happend');
}
});
In php
$json = $_POST['json'];
$data = json_decode($json);
now user your variable like this $date->data1 and $date->data2

Pass Array FROM Jquery with JSON to PHP

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

How to use the url hash to load a particular page after a refresh?

So, I am using url hashes that helps me to bring particular content up on hashchange. Now when i'm on some particular content and i refresh the whole page, i'm having that hash in the url and still not getting the content indicated by that hash.
Say my url is :
http://localhost/user and i clicked on details and it turned my url into following :
http://localhost/user#!detailsand i'm having the details page.
But having the above as my url when i reload the page, the hash remains same and there is no change in hash which does not invoke the function that i've bind with the hashchange event.
Also i cannot get the hash to the server side without sending ajax request everytime a user reloads using beforeunload.
Any Suggestions?
My code :
var pages = {};
pages['home'] = ""; pages['details'] = ""; pages['reviews'] = ""; pages['favs'] = "";
pages['likes'] = "", pages['gallery'] = "", pages['visited'] = "", pages['coupons'] = "";
$(window).bind('hashchange', function(event) {
var curr_hash = event.target.location.hash;
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
});
function load_page(page, toload){
// alert(pages[toload]);
if(pages[toload] == "") {
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: 'POST',
url: page,
data: post_data,
dataType: "html",
success : function(data) {
page[toload] = data;
$('.right-pane').html(data);
},
error : function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
console.log(xhr.responseText);
alert(thrownError);
}
});
}
else {
$('.right-pane').html(page[toload]);
}
}
You need to run the code attached to hashchange on load, in case someone refreshes the page, or even types it directly in to the browser. Try this:
var hashUpdate = function(curr_hash) {
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
}
$(window).bind('hashchange', function(e) {
hashUpdate(e.target.location.hash);
});
window.location.hash && hashUpdate(window.location.hash); // onload, if there was a fragment in the URL
$(function(){
var curr_hash = window.location.hash;
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
});

Undefined Value in AJAX

I had a function below which stores distances from two locations using google maps api. those results are stored in volunteerDist and there is a defined jid array. Document.write in line 5 showed the contents of each element in the array. Now, when I alert the Object.prototype... of volunteerDist, is says object Array. But when I called $.ajax and transferred volunteerDist into data and alert it (as shown below), it returns undefined and success (meaning data is stored but the contents are undefined). Any help? Thanks
function getABC(){
for(s=0;s<length;s++){
volunteerlocation = new GLatLng(jlat[s], jlng[s]);
volunteerDist[s] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
document.write(volunteerDist[s] + '<br> ');
document.write(jid[s] + '<br> ');
}
alert(Object.prototype.toString.call(volunteerDist));
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(data){
alert(data);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
}
Update:
Below is my toDistance.php
<?php
$distance=array();
$volunteerid=array();
if(empty($_GET)){
echo "Hello";
}
else{
$distance = isset($_GET['distance']) ? $_GET['distance'] : 0;
$volunteerid = isset($_GET['id']) ? $_GET['id'] : 0;
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
for($i=0;$i<$distance.length;$i++){
$updateDistance = mysql_query("
UPDATE volunteerbio
SET volunteerDistance = $distance[$i]
WHERE volunteerID = $volunteerid[$i];
");
}
}
?>
It's now the same data variable! It's in other scope.
The data in the success function is what the server returned. Give it other name if it confuses you.
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(result){ // Data sent from the server. not the data above!
alert(result);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});

Categories

Resources