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.
Related
[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
I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I have one issue with ajax when I get echo success on my php. I don't get execute the first if
if(text[0]==="success")
Code inside php
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
My code in ajax
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
Image console
What is the problem?
Could say me which it is problem?
I have that convert the message success to json too
Replace the success echo with
echo json_encode(["success"]);
or leave echo the same and replace if in ajax
if(text == "success")
The problem could be that it is an array, so you can try this:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
And if you want to see the results:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});
I want to send/get a variable to/from controller action. My codes:
view file
....
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var $radio = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
type: 'POST',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
data: {radio: $radio},
// datatype: "html",
success:function(){
alert($radio);
}
});
$.ajax({
type: 'GET',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
datatype: "json",
data: {change: $sql},
success: function(data) {
alert(data.change);
}
});
});
</script>
....
controller action
public function actionSech ($radio)
{
$sql = Yii::app()->db->createCommand()
->select ('m.maraq')
->from ('maraq m')
->where ('m.idsinif=:ids', [':ids'=>$radio])
->queryAll();
$gonderilen = CJSON::encode(['change'=>$sql]);
}
I read articles from Yii offical site and other forums. But I couldn't understand how can I do it.
Please tell me, how can I send $sql variable to my view file?
Thanks.
I'm not pretty sure what you want. But, I want to pointing out some snippet.
In view file
<?php
Yii::app()->clientScript->registerScript("header-info","
var baseUrl = '".Yii::app()->baseUrl;."';
",CClientScript::POS_HEAD);
?>
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var radioValue = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
url: baseUrl +'/ideyalar/sech',
dataType:'json',
type:'POST',
data:{radioValue:radioValue},
async:false
}).done(function(data){
if(data['status'] == 'OK'){
alert(data['returnValue']);
}else if(data['status'] == 'ERROR'){
alert("HERE WE GO ERROR");
}
});
});
</script>
Your controller action;
public function actionSech()
{
//In my point, I never call db layer in controller. Controller should be routing purpose
If(Yii::app()->request->isAjaxRequest){
$radioValue = isset($_REQUEST['radioValue']) ? $_REQUEST['radioValue'] : "";
$returnObj = array();
if($radioValue !=""){
$query = "SELECT `maraq` FROM maraq WHERE idsinif='$radionValue'";
$result = Yii::app()->db->createCommand($query)->queryScalar();
if($result != "" || $result != null){ //ensure result is correct or not
$returnObj['returnValue'] = $result;
$returnObj['status'] = 'OK';
}else{
$returnObj['status'] = 'ERROR';
}
}else{ //if radiovalue is blank string
$returnObj['status'] = 'ERROR';
}
echo json_encode($returnObj);
}
}
Hope this help! Btw, JavaScript variable can't not initialize with $. Just only var yourVar="";
acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}