Why Ajax is not able to send array data? - javascript

Trying to send form data to a PHP page, all parameters are sending successfully except data:imagesBase64
this imagesBase64 is an array which I am trying to send, a few hours ago everything was fine but now it is not working I really don't know why.
All values are Posting successfully only this value is not posting also I am not able to see error in console because it redirected to URL where I am posting the data
var imagesBase64 = ['abcdfd','dhydsu333ud','djhbsd'];
$(function () {
var frm = $("#saveform");
frm.submit(function (ev) {
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: {
data: imagesBase64,
PubId: $("#Publications").val(),
sdate: $("#datepicker").val(),
pnumber: $("#pnumber").val()
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
alert("New message received");
},
});
ev.preventDefault();
});
});
In PHP page -
print_r($_POST['data']);
it gives an error undefined data, though when I tried with postman everything is working fine.

also I am not able to see error in console because it redirected to URL where I am posting the data
That's the problem.
You are submitting data to the server using a regular form submission and not with Ajax. Since your Ajax code isn't used, the data added in from outside the form isn't included.
This is usually caused by the regular form submission interrupting the Ajax request, but since you have ev.preventDefault(); that shouldn't be the case here.
Possible reasons that might apply are:
var frm = $("#saveform") fails to find the form because the selector is wrong or the form is added after the document is loaded with other JS
You don't have jQuery loaded so the call to $ fails
You have jQuery Slim loaded which doesn't include an ajax method (moving the call to preventDefault so it is before the call to ajax would help catch this).
Your browser's developer tools should have an called something like "Persist Logs" which will prevent it from clearing the console when you navigate to a new page. Turn it on to aid your debugging. Here's what it looks like in Firefox:

Related

document.form.submit() is too slow to complete before window.close()

I am having an issue with saving a form. The form itself has about 40 rows with around 12 inputs for each row in this style:
On save, it should POST and then close the window. However, it never truly saves it. This makes me think that it is closing the window before it saves. Here's the code in question:
$('#save-btn').click(function() {
document.form.submit();
window.close();
};
If I remove the window.close() and use the inspector than I see in the parameters field that all the values save correctly. This is again what lead me to think that the window is closing to early.
I have tried using the following in the above #save-btn function:
setTimeout('window.close()',5000)
Yet this never seemed to execute the window.close() after the 5 seconds and all around seems like bad programming to force it to wait 5 seconds and then close when it could take any amount of time.
I then attempted to use an AJAX request like:
var _url = 'submit?nameParam="+nameParam+"&com=editlist&'+$('form').serialize();
console.log(_url); //just to see what its pushing out
$.ajax({
url: _url,
error: function(){
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
This resulted in 414 Request-URI Too Long. I know the case for this is it should be a POST to begin with, but I was just trying to make it work.
Just because, this is how our form is set up:
<form name="form" action="submit" method="post">
Our solution was to close the page from our action page
Remove the serialized data from your _url and instead pass it through the .ajax() request with the data setting:
var _url = 'submit?nameParam="+nameParam+"&com=editlist';
$.ajax({
url: _url,
method: "POST",
data: $('form').serialize(),
error: function() {
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
Your ajax approach is correct because you can understand that form submit done correctly with code, on success post it is easy to close the window.
For sending a POST request, you have to make some small changes in your code...
Don't serialize your form and add URL, it is not safe (not working for your situation).
Post your values as "post data".
Here is documentation about it.
https://api.jquery.com/jquery.post/
Please try and update your question if you cannot understand how.

Ajax POST works in safari, but not in other browsers

I've got an form which posts a form trough an ajax script to some PHP code. Strangely enough everything is working in Safari, but once i try it in either Firefox or Chrome the ajax call handles everything as an error, though the console doesn't show any errors.
$('#newClearance').on("submit", function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
method: 'POST',
url: 'modules/avas/library/avas_functions.php?action=newClearance',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data, status) {
$('#formModal').modal('hide');
$.notify(data, {type: 'success'});
$.get(window.location)
.done(function (r) {
var newDom = $(r);
$('#clearanceList').replaceWith($('#clearanceList', newDom));
});
},
error: function (data,status,error) {
$.notify(error, {type: 'danger'});
}
});
});
If I post the html form directly to the PHP script, everything goes well and the PHP script returns a success. It works in all browsers.
I really can't find the clue, especially as the same script, except for another form, is working perfectly fine in all browsers. Anybody a clue?
Additional info
Good thing to note might be that the form and jquery are placed in a modal, as you might notice form the code.
What do your server logs say when it receives the request?
Part of the solution appears to be the "submit" button of the form, which was required by the PHP script to run. I've removed this condition in the PHP script, but still wondering why firefox/chrome doesn't POST the submit button and safari does.

My Ajax Form Submission script isn't working

I've got all my form areas setup correctly and my Javascript received them. I've tested this with "alert", but for some reason, I don't know why, my form either isn't submitting or the PHP is wrong.
Here's my JavaScript:
//Main Content
var ed = tinyMCE.get('content');
var doc = document.getElementById("docid").value;
//Post Area
ed.setProgressState(1); // Show progress
$.ajax({
type: 'POST',
data: {'docid':document.getElementById("docid").value, 'content':tinyMCE.get('content').getContent()},
url: 'save.php',
success: function () {
ed.setProgressState(0);
$("#notice").fadeIn("slow").fadeOut(3000);
}
});
return false;
Here's save.php:
$id = $_POST['docid'];
$cn = $_POST['content'];
require_once("scripts/php/rq/connect.docs.php");
mysqli_query=($con, "UPDATE wordit_documents SET main_document='".$cn."' WHERE id='".$id."'");
1. ensure client is sending correct data.
Try using the inspector in Google Chrome, and activate the network tab.
Under form data you can see the data sent to the server (the picture shows the text of this answer being sent to stackoverflow to be saved as a draft.).
If not:
Make sure your script is wrapped in a jQuery.ready function.
jQuery(document).ready(function($){
// goes in here
});
Test the output of
console.log(document.getElementById("docid"));
console.log(tinyMCE.get('content'));
console.log(tinyMCE.get('content').getContent());
I Found The Problem it was because of an "=" In The mysqli_query, Thanks For Answers

Using ajaxForm plugin on view that is itself an AJAX response

I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});

using Blobstore Python API with ajax

there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
I wrote a series of posts about exactly this.
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.

Categories

Resources