I'm trying to post data with AJAX and insert it into a database table.
The problem is, half of the data is missing and I don't know why. I have checked all the names of parameters etc. because it seemed I had a typo somewhere (I was missing some characters but I fixed that) but still it won't work.
Even console.log() and alerts give me the full data I want to post but it never arrives, the php outputs empty parameters. When deactivating the JavaScript or removing "return false;" the php script is opened as expected and works perfectly well, no data is lost (as expected).
Maybe I'm really just missing one single character somewhere ...
I also tried escaping (escape()) the strings but it didn't change anything.
Here's the code and some logs/alerts/echos
$("#itemspeichern").click(function(){
setVisible("#item-process");
var itemname = escape($("#itemname").val());
if ($("#itemneu").is(":checked")) {
var itemneu = $("#itemneu").val();
} else {
var itemneu = 0;
}
var itembild = escape($("#itembild").val());
var itemkurzb = escape($("#itemkurzb").val());
var theset = escape($("#theset").val());
console.log("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild" + itembild + "&itemkurzb" + itemkurzb + "&theset=" + theset,
success: function(result){
alert("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
document.getElementById("item-process").innerHTML = result;
}
});
return false;
});
What this does is:
- output the data of all fields on the console
- showing all the data in the alert
but when it is done saving it the database is missing the values of itembild and itemkurzb. Getting the query as response from the php file showed that indeed the parameters are empty for those fields. Here's what I did in php (I shortened it a bit, don't comment on SQL injection and stuff :P)
$ergebnis = mysql_query("INSERT INTO mk7_items(id, de, neu, kurzbeschreibung, bild) VALUES(DEFAULT, '".$_POST["itemname"]."', ".$_POST["itemneu"].", '".$_POST["itemkurzb"]."', '".$_POST["itembild"]."')");
the last two fields are empty when I get the response and nothing is saved into the db.
As I said, setting JS to OFF and running it on php only works perfectly well.
Any ideas? Any stupid mistakes I did there?
You're missing a couple = in your data, it should be this:
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset,
Or better, stop using escape (which is deprecated in favor or encodeURIComponent due to escape not handling non-ASCII data very well) and use an object for your data parameter:
var itemname = $("#itemname").val();
//...
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
},
//...
});
That way $.ajax will take care of converting your data to the proper POST (or GET or ...) format and you don't have to worry about the details.
try this in your $.ajax call instead of your selfmade query string:
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
}
By passing the data as Object, jQuery will escape the values for you :)
Edit:
You could also serialize the complete form like this:
data: $('#yourform').serialize()
if you use special characters in posted items, you use this function before every vars...
sample :
var txt = encodeURIComponent(document.getElementById('txt1').value);
Related
We have the following script that works fine on all browsers.
However when the same script is placed inside the Fullcalender eventRecieve function (external events drag, drop and re render) the script does not post data to insert_events.php - but this only happens in Firefox- it does post data as expected in both Chrome and Edge. So in summary we have a situation as follows:
Edge, Chrome, FF - script is standalone --> posts data as expected
Edge and Chrome - script is inside eventRecieve --> posts data as
expected
FF script is inside eventRecieve -->fails to post data as expected
Code:
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
var propertyid = "WR388GG-8621";
$.post("insert_events.php?propertyid=" + propertyid, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
);
We originally thought this issue was down to the Ajax code with FF and
searched high and low for some ideas and spent a day trying to work out what was going on. But actually the problem is only showing up in Firefox and only when the script is triggered by Fullcalendar's eventRecieve function as below.
Code:
eventReceive: function(event) {
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
$.post("insert_events.php?propertyid=" + id, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
$('#calendar').fullCalendar('rerenderEvents');
window.location = 'new place to go';
},
Any ideas?
Credit goes to A Dyson on this one. It would seem that Firefox alone will trigger the redirect (window.location = 'new place to go';) before the Ajax call is made. The same is not true of Chrome or Edge - which handle the Ajax call first. Please upvote A Dyson's comment which should be the accepted answer. Apologies for dismissing A Dysons correct comment to soon.
I am trying to post to a webservice using Titanium HttpClient like so:
var non_data = {
user_id: Facebook_ID,
"friends_ids[0]":friendIds[0],
"friends_ids[1]":friendIds[1]
};
var non_xhr = Ti.Network.createHTTPClient({
onload: function(){
Titanium.API.info('Status: ' + this.status);
Titanium.API.info('ResponseText: ' + this.responseText);
Titanium.API.info('connectionType: ' + this.connectionType);
Titanium.API.info('location: ' + this.location);
alert("Get_Non_Friends response: " +this.responseText);
}
});
non_xhr.open('POST', myURL);
non_xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
non_xhr.send(non_data);
But it doesn't seem to be getting the array elements right. Can anyone tell how to post and array of params.
Also I found a post on TIMOB that says to do something like this, which I am currently trying:
non_xhr.open('POST', myURL);
//non_xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
non_xhr.send('user_id=someData&friends_ids[0]=someData);
Can anyone tell me the best approach for this problem?
The problem seems to be with the send method. The send method should be something like this
non_xhr.send({paramName : non_data});
The paramName is the name which is required by the web service. Ex
non_xhr.send({
file: abc.jpg
});
Also its advised to have onerror method too just like onload method.
I have this ajax call
function addNewRemarksToDataBase(argRemark) {
if (argRemark != '') {
// if not blank
$.ajax({
url: '../AutoComplete.asmx/AddNewRemarks',
type: 'POST',
timeout: 2000,
datatype: 'xml',
cache: false,
data: 'argRemarks=' + argRemark,
success: function (response) {
// update the field that is source of remarks
updateRemarksSource();
},
error: function (response) {
}
});
}
};
The method is defined as
[WebMethod]
public void AddNewRemarks(string argRemarks)
{
BAL.BalFactory.Instance.BAL_Comments.SaveRemarks(argRemarks, Globals.BranchID);
}
The problem is if a user enters something like long & elegant or something like smart & beautiful, something that contains &, I only get the first part before &, long (in the first case), smart (in the second one) (also notice the whitespace!)
I read in jquery ajax documentation that one should set processData to false, because it is something used for querystring or something. I added the
processData: false
but I am still getting the term before the &. I don't want to use encodeURIComponent because it will turn the & to amp; (or something like that). What I need is the full value long & elegant, smart & beautiful that will be saved to the database. How can I do this?
EDIT Doing { argRemarks: argRemark } doesn't helps! The function doesn't event gets called. Running it with firebug, and setting breakpoint in error function, I got this
[Exception... "Component does not have requested interface" nsresult: "0x80004002 (NS_NOINTERFACE)" location: "JS frame :: http://localhost:49903/js/jquery-1.8.1.min.js :: .send :: line 2" data: no]"
UPDATE 2 :
Doing
data: 'argRemarks=' + encodeURIComponent(argRemark)
did the trick. But can anyone help me understand how does this works? I thought it would convert & to & but it didn't? The parameter I am receiving to the method now is just what I wanted, long & elegant, smart & beautiful, doesn't encodeURIComponent() converts special characters?
You do need to encode the argRemark. The easiest way to do this is to let jQuery do the job for you:
data: { argRemarks: argRemark }
This is different than data: 'argRemarks=' + argRemark in that by passing in an object, jQuery assumes that it needs to URL-encode the values of the properties on that object -- while if passing in a string, you are expected to have properly encoded it beforehand.
You have to URL-encode the string first:
data: 'argRemarks=' + encodeURIComponent(argRemark)
I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
type : "POST",
url : "/usermanageajax/",
data : 'key=' + key_value,
success : function (data) {
var element = users.salary[users.salary.length -1];
var hrs = users.hours[users.hours.length -1];
var html = "<span title=\"" + users.name + "\">Name \"" + users.desc(0,50) + "...\" "+ "has " + element + " of "+ hrs + "</span>";
// alert('*');
$('#title').html(html);
chart_s = draw_chart(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?
The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler. You can also check for success there.
I'm trying to run some tests on some Ajax code we have written, now obviously when tested locally it runs very fast and is great. I need to enforce a delay of 3 seconds so that I can see that the loader is being displayed and the user experiance is good enough.
I have tried the following but recieve the error "Useless settimeout" any other suggestions to achieve this? Any browser plugins?
$('#formAddPost').submit(function() {
//Load the values and check them
var title = $(this).find('#Title');
var description = $(this).find('#Description');
var catId = $(this).find('#Categories');
if (ValidateField(title) == false || ValidateField(description) == false) {
$('.error-message').show();
return false;
}
$('.error-message').hide();
//Show the loading icon
$('.add-post').hide();
$('.add-post-loader').show();
//Temp for testing - allows the showing to the loader icon
setTimeout(MakeAJAXCall(title.val(), catId.val(), description.val()), 1500);
return false;
});
function MakeAJAXCall(title, catId, description) {
$.ajax({
url: "/Message/CreatePost/",
cache: false,
type: "POST",
data: ("title=" + title + "&description=" + description + "&categories=" + catId + "&ajax=1?"),
dataType: "html",
success: function(msg) {
$('#TableMessageList').replaceWith(msg);
$('.add-post-loader').hide();
$('.add-post').show();
}
});
}
As you're testing your page for a delay in the server response, can you put a delay in the server side code instead of client side?
You might be able to do that using fiddler.
The examples scripts include some samples that pause the response.
Would this tool from jsFiddle.net be helpful?
Echo Javascript file and XHR requests
http://doc.jsfiddle.net/use/echo.html