I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?
Related
I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});
I'm new to AJAX and not so good at PHP. I'm trying to simply send a string saying "Hello" to my PHP page using the JQuery $.AJAX function. So far I have successfully got AJAX to send the information to the page and log it in the console but the data doesn't get stored into the POST variable.
Please keep in mind I'm not being lazy by coming to this forum and asking for help but I have no other choice because I've been searching for about 2 days now on how to fix this problem and haven't found anything that's worked.
Here's my HTML (order.html) - This isn't all my HTML but it's all you will need):
<html>
<body>
<form method="POST">
<button id="order-btn" type="submit" formaction="PHP/sendMail.php">Order</button>
</form>
<!-- JavaScript/JQuery links -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="JS/order.js"></script>
</body>
</html>
Here's my JavaScript (order.js - Once again, I'm only providing necessary code)
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "PHP/sendMail.php",
type: "POST",
data: {data: txt},
dataType: "html",
asyc: true,
success: function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
Here's my PHP(sendMail.PHP - I'm only providing necessary code)
<?php
if(isset($_POST['data'])) {
$data = $_POST['data'];
echo $data;
} else {
echo "Failed to grab data.";
}
Just to clarify, in my actual code the URL is the full URL of my website page.
Let me know in the comments if you would like to see the site to get a better understanding of how and why I need this feature to work.
UPDATE & SOLUTION:
From the help I received I now understand that AJAX will only update information on the current page (So, for example, if you have an AJAX function on index.html then you can only run AJAX on that page and can't transfer information across pages)
To solve my problem I stopped sending users to the sendMail.php page and instead changed the HTML content of the page I was currently on (order.html) in the $.ajax success method.
Here's the updated JavaScript code:
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "order.html",
type: 'POST',
data: {data: txt},
dataType: 'html',
success: function(data){
if(parseInt(data)!=0) {
$("body").html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
I'd like to thank everyone that helped :)
$.ajax({ //create an ajax request to load_page.php
type: “POST”,
url: “load-page.php”,
data: {page:url}, //with the page number as a parameter
dataType: “html”, //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$(‘#pageContent’).html(msg); //load the returned html into
pageContet
$(‘#loading’).css(‘visibility’,’hidden’);//and hide the rotating
gif
}
});
Like in above example load-page.php is called so data returned is going to dispaly in pageContent which is the id of some div etc and this div is not on load-page.php this div is on the page from where this ajax request is sent.
may be it will make sence
reference link: Reference Link!
It's not like this way as you have called sendMail.php this file and the data returned will be available in the page from where it was called.
Let suppose with button click on page A you called sendMail.php, so the ajax response returned to page A not to sendmAil.php.
First thing, garantees that your API is working. Using a toolchain for API, like postman or insomnia.
If your api is returning what you want, then you go to your javascript code, because I don't see any problem in your code. I even used your code and worked.
Then use session
session_start(); //at the top
$_SESSION['mydata'] = $data; // something like it
but as far as I know it's necessary to refresh the page for session to work. please try it
I'm befuddled. I have a JavaScript function that posts to a PHP function. PHP says, "undefined index" on mPicker. Yet if I call var_dump within the same function mPicker is plainly visible.
I've also ran an alert client side in JavaScript to be sure the form data was serialized, and it too shows that mPicker indeed has a value. Yet this line in PHP returns the error:
$es=$_POST["mPicker"];
This is just short hand for all your sake. The longer version of the code tests for SQL injection.
And the error in xdebug:
The JavaScript code:
$.post("./php/adates.php", { atype: apttype, data: $("#apptForm").serialize() })
.done(function(data) {
alert(data);
});
And more of the php function code:
if (isset($_POST["atype"]) && !empty($_POST["atype"])) {
$typ = test_input($_POST['atype'], $con);
} else {
echo "error ln 6: typ is undefined.";
}
$es=$_POST["mPicker"];
echo $es;
exit;
test_input is the function I mentioned that tests for SQL injection, and just for testing, have omitted temporarily on the post on mPicker. As you can see, the line $_POST["atype"] escapes error, and is perfectly resolved in the PHP function. I know I am tired and must be missing something stupid. Help, anyone!
try to use jQuery "ajax" instead of "post"
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: "html",
success: function(html){
console.log(html)
}
});
and set the dataType to "html", then use "echo" or "var_dunmp" in php, you can see ur data in console
This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I want to submit a form information to another php script without leaving the page and show the output in that same page.
Here's my ajax function to load php output in html without leaving the page. It doesn't do that if my form has a submit button. It only works with a normal clickable button.
$('#btnLoad').click(function(){
$.ajax({
type: 'POST',
url: 'page1.php',
success: function(data){
if(data != null) $('#content').text(data);
}
});
});
The problem is that I need to send POST variables to my PHP script but when I do, it goes to my PHP script page. I just want the script to receive the POST variables, run the script and then show the output in my HTML page.
Here's the script that doesn't go to PHP script page. I don't know if the PHP script runs with this function.
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('page1.php', $(this).serialize(), function (data) {
}).error(function() {
});
e.preventDefault();
});
});
How can I combine these two scripts into one, to submit my variables via POST, run the script and show the output in my HTML page?
Combining both Ajax
$("#btnLoad").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "page1.php",
data: $('#myForm').serialize(),
success: function (msg) {
$("#thanks").html(msg);
},
error: function (msg) {
$("#error").html(msg);
}
});
});
HTML to show success message
<div id="thanks"></div>
HTML to show error message
<div id="error"></div>
PHP Server Side
<?php
if (isset($_POST['submit'])) { //assuming you have input with name="submit"
//Do what ever you like to do next
//If everything good
echo "<strong>Success!</strong> This Is Success Thanks Message. If everything go exactly as Planned.";
} else {
echo "<strong>Error!</strong> This Is Error Message. If anything goes south.</div>";
}
?>
Edited: OP asked to show messages in jQuery modal dialog
In Ajax after success call, try like this
success: function(msg) {
$("#thanks").html(msg);
$("#modalId").dialog({
autoOpen:true,
width:500,
title:"Your Error Message",
},
And same for error function
Note: I haven't test this so not sure it will work out of the box or need any debugging.
Why do you not replace the submit buttons with normal buttons then?
What you could do in jQuery is:
$(formSelector).on('submit',function (e) {
e.preventDefault()
//Place your ajax here.
})
you can do something like
$('#btnLoad').click(function(){
$.ajax(url,
{
data: { variable1: $("#variable1").val(), variable2: $("#variable2").val() },
type: "POST",
success: function(data) {
if(data != null) $('#content').text(data);
}
});
});
And normally I don't use a form if I need to send data via ajax, I use just JS.
I have a registration form and am using $.ajax to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database.
I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Put an alert() in your success callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.
You must declare both Success AND Error callback. Adding
error: function(err) {...}
should fix the problem
I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.
In my case the reason was , that the closing tag did not match the opening tag.
<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<result>
<status>$status</status>
<OPENING_TAG>$message</CLOSING_TAG>
</result>";
?>
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
The result was not being returned in JSON format
I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
I tried to return string from controller but why control returning to error block not in success of ajax
var sownum="aa";
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : "JSON",
url : 'updateSowDetails.html?sownum=' + sownum,
success : function() {
alert("Wrong username");
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+val);
}
});
I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.
note using Lavalite framework.
before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me
I had the same problem i solved it in that way:
My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response.
Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working.
PS. Sorry if something is wrong but it is my first comment on this forum :)
in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
Add 'error' callback (just like 'success') this way:
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
So, in my case I saw in console:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.
The success callback takes two arguments:
success: function (data, textStatus) { }
Also make sure that the submit1.php sets the proper content-type header: application/json