Submiting a form via json/ajax/jquery - javascript

Here is my code
function generate_clicked()
{
var txt_text_color = $('#txt_text_color').val();
var url='process.php?';
url+='txt_text_color='+encodeURIComponent(txt_text_color);
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}
This works for my purposes but if I added another form element I would tediousily have to add var example =$('....').val();
and
url+='example'+endcodeU.....
Which I will be having over 100 elements, then I would retreview them on process with
$txt_text_color = $_REQUEST['txt_text_color'];
My question is, how can I serialize this (I think that's what I need to do) so that I don't have to write those two varibles names each time I make a new form object.
I need to save get/post those varibles in process.php to use them.
Sorry if this doesn't make sense, I'm still learning.

Try form.serialize()
http://api.jquery.com/serialize/
Your code would look something like this:
function generate_clicked()
{
var formData = $('#form').serialize();
var url='process.php?';
url+=formData;
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}

Related

Weird behavior under chrome and $.ajax after chrome update

I've an asp.net mvc5 application that on a loginpage does the following Ajax call
$(document).ready(function () {
var formObj = $(".login-form");
$("form input[name=username]").val("user");
$("form input[name=password]").val("password1!");
formObj.submit(function (event) {
event.preventDefault();
console.log("test");
validator = formObj.validate();
if (validator.checkForm()) {
var form = formObj.get();
var rememberMe = $("input:checkbox[name=remember]:checked").val() ? true : false;
$(form.rememberMe).val(rememberMe);
args = {
form: form,
userName: $(form.username).val(),
password: $(form.password).val(),
remember: rememberMe
}
var url = #Url.Content("~/api/auth");
func = $.ajax({
url: url,
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
#if(Request.Params.Get("redirect") != null) {
<text>
window.location = "#Request.Params.Get("redirect")";
</text>
}
else
{
<text>
window.location = "#Url.Content("~/Home")";
</text>
}
}
}
});
}
});
});
If I put this piece of code
var url = #Url.Content("~/api/auth");
it works, otherwise if I quote the url string (as it should be correct)
var url = "#Url.Content("~/api/auth")";
it hangs the browser.
This only happens under chrome as first iussue was reported with Chrome Version 43.0.2357.65 m
What is wrong?
Thanks
UPDATE #1
I've noticed that the problem is there
$.ajax({
url: "/someurl",
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
window.location = "/someotherurl/";
}
}
});
If I sue ajax it breaks...if I use $.post or $.get it works...

Unexpected characters in image url in ajax response Javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?
Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
My issue was solved by using jQuery.parseJSON function.

File not reaching till handler's method

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
var fileUpload = $('[id$=FileUpload1]')[0].value.split(",");
var data = new FormData();
for (var i = 0; i < fileUpload.length; i++) {
data.append(fileUpload[i].name, fileUpload[i]);
}
var options = {};
options.url = "Handler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
This was my jquery and below is my handler file code ......
till end i am getting value while debugging but in motto of making upload multiple images at a while i am unable to have any value in handle
handler code
public void ProcessRequest (HttpContext context) {
string filePath = "FileSave//";
foreach (string file in context.Request.Files)
{
HttpPostedFile filed = context.Request.Files[file];
filed.SaveAs(context.Server.MapPath(filePath + filed.FileName));
context.Response.Write("File uploaded");
}
}
You can try this way if you would like to.
$(document).ready(function () {
$("#Button1").click(function (evt) {
evt.preventDefault();
var formdata = new FormData();
var fileInput = $('#sliderFile'); //#sliderFile is the id of your file upload control
if ($(fileInput).get(0).files.length == 0)
{ //show error
return false;
}
else
{
$.each($(fileInput).get(0).files, function (index,value) {
formdata.append(value.name, value);
});
$.ajax({
url: 'Handler.ashx',
type: "POST",
dataType: 'json',
data: data,
processData: false,
contentType:false,
success: function (data) {
if (data.result) {
//return true or any thing you want to do here
}
else {
//return false and display error
}
},
error: function (data) {
//return false and display error
}
});
}
});//button click close
});//document.ready close
Try it and let me know
EDIT: Remember but, HTML5 FormData is not available in older browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:
if(window.FormData === undefined) {
// The browser doesn't support uploading files with AJAX
// falling back to standard form upload
} else {
// The browser supports uploading files with AJAX =>
// we prevent the default form POST and use AJAX instead
e.preventDefault();
...
}
For more information on this you can see answer I have accepted for one of my questions. It's pretty much clear there what is the issue regarding. Here is the link
EDIT : Just adding these LINK1 and LINK2 for those who come looking for the answer.
use HttpContextBase[] instead of just HttpContext

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

jQuery AJAX works on mobile safari, but not a UIWebView?

I have a basic jQuery ajax function to log the user in via a UIWebView. However, for some reason it returns blank when it's in a UIWebView. It works fine in mobile safari, and chrome and firefox on my computer.
Here's my code:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});
The theRetrievedData just returns blank on the alert.
Please help!
PS: The app is called "Dudles" in the app store (it's free) if you want to try to login. You will get a blank message from the alert.
Can you post your PHP code as well?
I refactored the code you wrote into how I would write it just to see if I could spot any bugs, and nothing seemed glaringly incorrect. Here is what I have so far:
$(document.body).on('click', '#login_button', function () {
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: $(this).closest('form').serialize(),
success: function (response) {
var delimiter = "?!?success?!?";
var isSuccessful = response.indexOf(delimiter) !== -1;
if (!isSuccessful) {
// handle error
return;
}
$('#content').fadeOut(500, function () {
location = response.split(delimiter)[1];
});
}
});
});
try to send ajax request with async:true, like this:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
async:true,
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});

Categories

Resources