Making value from PHP show on page requesting AJAX data - php

I have a simple login form and it does return the "success" text in the function, but now I want to be able to add the text provided in the .php file. How can I do this?
html
<script>
$(function(){
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
},
error : function(jqXHR, textStatus, errorThrown){
alert("error " + textStatus + ": " + errorThrown);
}
});
});
});

$.ajax({
type: "POST",
url: "loggnow.php",
data: inputs,
dataType: "html",
success: function (data) {
$("#login").html(data);
},
error : function (jqXHR, textStatus, errorThrown) {
alert("error " + textStatus + ": " + errorThrown);
}
});

The docs on jquery web sites says that the sucess function will be passed the data. (See quoted). So you can just use the content passed back in the "data" variable, and put it in there.
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed
three arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success
setting can accept an array of functions. Each function will be called in
turn.

Related

Not getting response in ajax

I am trying to get ajax response. But my code does not show anything in alert. Here is my ajax code. my form id is contact_form and my submit button id is submit_btn
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
var form= $("#contact_form").val();
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
dataType : 'json',
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
//console.log(textStatus, errorThrown);
}
});
e.preventDefault();
});
});
my email.php
<?php
echo "ok";
?>
I think that your problem is because you are trying to use the serialize method in a wrong way.
The .serialize() method will handle all the fields that are inside the selected target form. In the original code, You've used the .val() method to take the values of the form, but this will not work because that method is intended to be used with a single form element and can't handle the whole form.
Change your code in this way:
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
e.preventDefault();
var form = $("#contact_form");
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});

Ajax: I can't get data from PHP by using json_encode

I am having issues retrieving data from PHP by using Ajax. I am stuck and have been spending lots of time trying to find out where the problem is.
Here is my php code:
<?php //ajax/default_chart_numbers.php
require_once '../core/db_connection.php';
$lotto = new Lotto();
$ultimo_concurso=$lotto->ultimo_concurso('foo');
$ultimos_numeros_m=$lotto->ultimos_numeros('bar');
$R1m=$ultimos_numeros_m[1];
$R2m=$ultimos_numeros_m[2];
$R3m=$ultimos_numeros_m[3];
$R4m=$ultimos_numeros_m[4];
$R5m=$ultimos_numeros_m[5];
$R6m=$ultimos_numeros_m[6];
$R7m=$ultimos_numeros_m[7];
//preparing json
$json=array('y'=>$ultimo_concurso,'n1'=>$R1m,'n2'=>$R2m,'n3'=>$R3m,'n4'=>$R4m,'n5'=>$R5m,'n6'=>$R6m);
print json_encode($json,true);
?>
The output of the PHP file is:
{"y":"2745","n1":"1","n2":"13","n3":"19","n4":"29","n5":"41","n6":"46"}
And here is the jQuery code:
<script>
$(document).ready(function(){
/*Retriving data from PHP file*/
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (response, textS, xhr) {
alert("everything ok :)");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
},
complete: function(data){
y=data.y;
alert('The id number is '+ y);
}
});
});
</script>
When executing, the value is undefined. I mean, the alert i get is The id number is undefined.
What am i missing?
There's no true in json_encode, there is in json_decode to get an array, but now you're creating a string
change
print json_encode($json,true);
to
echo json_encode($json);
and the complete handler doesn't get the data, it has two arguments, the XHR object and the statuscode, the success handler gets the data
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
y=data.y;
alert('The id number is '+ y);
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
On PHP side, send the JSON with:
header('Content-Type: application/json');
echo json_encode($json);
Maybe log the incoming data to the console:
inside success: add an console.log(response)
inside complete: add an console.log(data.y)
This is missing:
https://api.jquery.com/jQuery.parseJSON/
try using:
result = $.parseJSON (data);
result.y has your value

PHP script not running from Jquery/AJAX?

I am trying to pass the user's checked HTML radio button value to a PHP variable using Jquery/Javascript and Ajax.
The following is a simplified version of the HTML/Javascript:
$("input[name=bus_plan]").on('change', function(){
var $postID = "=" + $('input:radio[name=bus_plan]:checked').val();
$.ajax ({
type: "GET",
url: "product-group.php",
data: {"postID" : $postID },
success : function(data){
alert("done");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("problem: " + errorThrown);
}
});
});
The ajax call shows a success (i.e. there is a "done" alert.)
This is the product-group.php:
<?php
echo "hello world<br>";
$postid = $_GET['postID'];
echo "The postID is ".$postid;
?>
Any help in understanding/fixing the fact that product-group.php does not appear to run would be most appreciated.
Thank you.
Try alert(data) instead of alert("done") to see if jQuery is receiving the correct response.
Your echo output is in "data" var, its like the "return" for ajaxcalls.
Tru alert(data) or append the data content on some div.
Try rewriting your ajax call like this-
$("input[name=bus_plan]").on('change', function(){
var postID = $('input:radio[name=bus_plan]:checked').val();
$.ajax ({
type: "GET",
url: "product-group.php?postID="+postID,
success : function(data){
alert("done");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("problem: " + errorThrown);
}
});
});

How to get each value from json method

ajax
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#amount').val(data);
// $(".email_msg").addClass("red");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
Controller code
public function stb_info(){
$stb_no=$this->mso->alldata_stbno($this->input->post('stb_no'));
echo json_encode($stb_no);
}
i am getting out put
[{"sxb_no":"xxxxxx","mzo_name":"xx","cto_name":"xxxxx","area":"xxxxx","name_sxb_owr":"","mobile_no":"xxxxxx","email":"xxxxx#yahoo.com","amount":"xxx"}]
i need to know how to get each values ex:- if i want get email id what i should i do in jquery please help me i new to ajax
Most browsers support JSON.parse(), which is defined in ECMA-262 and is the recommended way. Its usage is simple (I will use your example JSON):
var json = '{"area":"xxxxx",...,"email":"xxxxx#yahoo.com","amount":"xxx"}';
var obj = JSON.parse(json);
Note that obj.email can't be used, because you are parsing an array.
Edit: Checking your comments you need to know that the data parameter is the JSON object, parse it first and then you can do:
$('#amount').val(obj[0].email);
Just add to $.ajax call parameter dataType:"json" and Jquery will parse it in success parameter automatically. Then use it data[0]['email'];
For example :
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#email').val(data[0]['email']);
//OR
var obj = JSON.parse(data);
$('#email').val(obj[0].email);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});

Jquery Ajax Post Error Undefined in Codeigniter

I am implementing a jquery ajax form submission on selecting the checkbox. I am always getting error undefined in the response data. Please find my code as following.
Jquery Post
$.ajax({
type: "POST",
url: filelink+"playlist/add_cart_item",
data: {"product_id":id,"quantity":qty,"ajax":1},
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(textStatus + " " + errorThrown)
}
});
Controller Function
function add_cart_item(){
echo "true";
}
File link is giving me the exact path. Jquery library file is also properly included. Can anybody please help where could be the problem.
I am using HMVC Codeigniter. Is there any other way of calling php file from ajax in it ??
Also When I am changing the type from POST to GET it is returning my ECHO "TEST" ..
Thanks
Several points.
in add_cart_item() try adding the correct header for json data
Try to use console.log instead of alert for debugging javascript.
Try to debug the http request/response using firebug.
You had an insecure ajax call..ill recommend this way
$.ajax({
type: "POST",
url: filelink+"playlist/add_cart_item",
data: {"product_id":id,"quantity":qty,"ajax":1},
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(textStatus + " " + errorThrown)
}
});
function add_cart_item(){
echo $_POST['product_id'];
exit;
}

Categories