[SOLVED]
That was THE most difficult bug ever - all due to copy/paste stuff up.
This:
$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
should have been that:
$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
The damn '+bUID+' was pasted AFTER the " , not BEFORE!
Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))
Here's the js:
$('form').submit(function(e){
bUID = $(this).find('input[name=bUID]').data("buid");
e.preventDefault();
submitForm(bUID);
alert(bUID);
});
function submitForm(bUID) {
var name = $('#name'+bUID).val();
var email = $('#email'+bUID).val();
var message = $('#message'+bUID).val();
var code = $('#code'+bUID).val();
alert(bUID);
// also tried this
var post_data = {
'name': $('#name'+bUID).val(),
'email': $('#email'+bUID).val(),
'message': $('#message'+bUID).val(),
'code': $('#code'+bUID).val(),
'buid': bUID,
};
alert(Object.keys(post_data).length);
// ALSO tried this instead of ajax:
//$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
alert(response);
$.ajax({
dataType: "json",
type: "post",
data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
//data: post_data,
url: $('#contact_form'+bUID).attr('action'),
success: function(response) {
if (typeof response !== 'undefined' && response.length > 0) {
if (response[0] == "success") {
$('#success'+bUID).append('<p>Success</p>');
}
else {
$('#errors'+bUID).append('<p>' + js_errors + '</p>');
$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
$.each(response, function(i, v){
if (i > 0) {
$('#error_list'+bUID).append('<li>' + v + '</li>');
}
});
}
}
}
});
}
here's the action in view.php:
<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>
<form id="contact_form<?php echo $bUID; ?>"
class="contact-form"
enctype="multipart/form-data"
action="<?php echo $formAction?>"
method="post"
accept-charset="utf-8">
<?php echo $bUID; ?><br />
<input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">
...etc.
and here's the controller.php:
public function action_submit($token = false, $bID = false)
{
$this->form_errors = array();
array_push($this->form_errors, "error");
array_push($this->form_errors, $_POST['name']);
array_push($this->form_errors, $_POST['email']);
array_push($this->form_errors, $_POST['message']);
array_push($this->form_errors, $_POST['code']);
array_push($this->form_errors, $_POST['buid']);
echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
exit;
}
it gets all data and shows it in alert but then trows the following error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg#gmail.commm","gggggggggggggggggggggggg","gggg","171"]
at r (jquery.js:2)
at Function.each (jquery.js:2)
at Object.success (view.js:132)
at j (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at x (jquery.js:5)
at XMLHttpRequest.b (jquery.js:5)
Line 132 of the js file is this: $.each(response, function(i, v){
I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg#gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!
What's wrong here? Why doesn't the form get posted?
Thank you very much.
Have you tried adding return false; to prevent your form from submitting to its desired action?
$('form').submit(function(e){
bUID = $(this).find('input[name=bUID]').data("buid");
//e.preventDefault();
//e.stopPropagation();
submitForm(bUID);
alert(bUID);
return false;
});
Try this way,
function submitForm(bUID) {
var name = $('#name'+bUID).val();
var email = $('#email'+bUID).val();
var message = $('#message'+bUID).val();
var code = $('#code'+bUID).val();
$.post($('#contact_form'+bUID).attr('action'), {name:name, email:email, message:message, code:code, buid:bUID}, function(result){
alert(result);
});
}
Your post_data variable was correct. As it is now your data attribute in your ajax is wrong - it's in GET format (a string), not POST. The correct way (json) is;
$.ajax({
dataType: "json",
type: "post",
data: {
name: nameVar,
email: emailVar,
message: messageVar
},
url: ...,
success: function(data) {
...
}
});
I "renamed" your variables to try and avoid variables with the same names as keys (e.g. you want to post "name", setting a variable "name" might conflict).
Just use
data: form.serializeArray()
Like this:
$.ajax({
url: 'url to post data',
dataType: "json",
method: "post",
data: form.serializeArray(),
success: function(data) {
// another staff here, you can write console.log(data) to see what server responded
},
fail: function(data) {
console.log(data) // if any error happens it will show in browsers console
}
});
Another tips: in server side you can use http_response_code(200) for success, http_response_code(400) for errors, http_response_code(403) if authorisation is required
Related
Racking my brains for hours with this. I have the following PHP AJAX script:
<script type="text/javascript">
$(document).ready(function(){
$("#submitValue").click( function(){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
success: function(data){
$('#results').html('Success').delay(1000).fadeOut();
}
});
});
});
</script>
I am trying to get the message 'Success' to populate this span element;
<span id="results"></span>
But just can't seem to get it to work.
The PHP is as follows (the table is updated just fine);
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
}
Anyone be of assistance please?
dataType: "dataString"
Please comment this part and it will work.
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
echo 'yes';
}
// add echo 'yes'; at php submit page.
change the script as follows
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
// dataType: "dataString",
dataType : "text",
success: function(data){
$('#results').html(data).delay(1000).fadeOut();
return false;
}
});
return false;
In php file change this
$qry = mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
if($qry)
echo "Success";
}
When you make an ajax call and you pass the values to a php file, you will also need to return the response.
So at the end of your query if everything is completed successful you will do something like this:
return Response::json(array(
'success' => true,
'message' => trans('admin.update_success'),
), 200);
And your ajax cal looks something like this:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
})
.done(function(response) {
alert(response.message)
})
.fail(function(response) {
if (response.status == 400) {
var output = '<ul>';
var errors = $.parseJSON(response.responseText).errors;
$.each(errors, function(id, message) {
output += '<li>' + message[0] + '</li>'
});
output += '</ul>'
alert(output)
} else {
alert('UnknownError');
}
})
e.preventDefault();
})
So to recap:
You make the ajax call
The php file will process the data
You pass the response back to the 'done function)
And hier you can make anything you want with your response.
I have just as example inserted an alert message
Hope this helps.
Sorry but the code I have provider for you is for a Laravel framework and I suppose you are not using it. So you don't have the 'Respone::' class.
In the php file:
//if the query has success
$return = array();
$return['responseCode'] = 1;
$return['responseHTML'] = 'Success'
echo json_encode( $return );
And the ajax call:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
})
.done(function(response) {
if( response.responseCode == 0 ) {
//alert(respomse.responseHTML)
$('#results').html(response.responseHTML);
} else if( response.responseCode == 1 ) {
//alert(res.responseHTML)
$('#results').html(response.responseHTML);
}
})
e.preventDefault();
})
So I don't use the response anymore but I will just return an array with the response.
I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);
I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,
any help would be appreciated,
$(function() {
$('form#email input[type=image]').click(function() {
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
var dataString = 'name=' + name + '&enq=' + enq;
$.ajax({
type:'POST',
url:'email.php',
data:dataString,
success:function() {
$('form#email').fadeOut();
}
});
$('form#email')[0].reset();
return false;
});
});
php file
if (isset($_POST['submit_x'])) {
$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);
//echo $name,$enq;
$to = 'amirkarimian#hotmail.co.uk';
//$to = 'tutor#inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;
mail($to,$subject,$message);
if(!mail) {
echo 'failed to send mail';
}
}
the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.
thanks
You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check. Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:
$(function() {
$('#email input[type=image]').click(function() {
$.ajax({
type:'POST',
url:'email.php',
data: { name: $('#name').val(), enq: $('#enq').val() }
success:function() {
$('form#email').fadeOut();
}
});
$('#email')[0].reset();
return false;
});
});
Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }
with data: $('#email').serialize().
try sending 'submit_x' to php :)
You can use a data map to define your data:
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
$.ajax({
type: 'POST',
url: 'email.php',
dataType: 'html',
data: {
submit_x : 1,
name : name,
enq : enq
},
success: function(html){
$('form#email').fadeOut();
},
error: function(e, xhr) { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
});