How to get POST data using Jquery AJAX - javascript

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.

You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.

You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});

do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

Related

jQuery ajax not passing post data to php page

I try to get post data from using alert() and its worked problem is that data is not passing to php page result is always {"success":false,"result":0}
What I want is send password to php page and hash it using password_hash() and return result
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.ajax({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="spass" >
<h4>Change Your Password</h4>
<input type='password'name="passc" >
<!--<input type='password' name="cpass" id="cpass"> -->
<input type="submit">
</form>
**this my php code**
<?php
header('Content-type: text/javascript');
$json=array(
'success'=>false,
'result'=>0
);
if(isset($_POST['passc']) && !empty($_POST['passc'])) {
$pass=password_hash($_POST['passc'],PASSWORD_DEFAULT);
$json['success']=true;
$json['result']=$pass;
}
echo json_encode($json);
?>
You can test that your data has not actually been passed to a PHP page.
In the PHP code, do the following: echo $ _POST ['YOUR_VARIABLE'].
Check the INSPECT_ELEMENT / NETWORK browser to make sure you actually send data to the correct link. Your link may be relative, so you may be sending data to the wrong link.
So, try to put the entire link in the ajax url
$ .ajax ({
url: 'HTTP: //WHOLE_LINK_IN_HERE.COM/passwordhashing.php',
});
SET method in Ajax: type: "POST"
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
**i used $.post() instead of using $.ajax() and it fix my problem**
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.post({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});

I have to pass data value to controller using ajax

View File product_grid
<div data_id="<?php echo $ro['category_id']; ?>" name="id" class="cbp-filter-item">
<?php echo $ro['category_name']; ?></div>
// try to post data using ajax
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>.index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
Hear i can pass the id to view but not work properly please help me to solved this problem
Controller ::
public function product_grid()
{
$id= $this->input->post('id');
}
You must have to use print or echo otherwise there will be no response sent to client side so use echo like,
public function product_grid(){
$id= $this->input->post('id');
echo 'Data-Id is: '.$id;
}
And use the URL like,
url:"<?=base_url()?>index.php/Home/product_grid", // let there is / in the end of base_url()
AJAX Code,
jQuery.ajax({
url:"<?=base_url()?>index.php/Home/product_grid",
type:'POST',
data: {id:id}, // no need of quotes to JSON Object keys
success:function(data) {
alert(data);
}
});
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>+index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
url:"<?=base_url()?>+index.php/Home/product_grid"
Use + for concatination instead of .

Getting a particular value from ajax response

I am using ajax with masonry
Ajax code: This ajax is used to get data from
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
$items = $(data);
$grid.append( $items )
.masonry('appended', $items);
$(this).find(".loading").hide();
}
}
Php Part: This is just a small or sufficient part of php file to understand the problem
$b= "sv";
echo "asjdgsajd";
echo "a";
echo $b;
now i am getting everything correctly but i want to use say value of $b for setting a attribute value and also other values as content but how can i particularly get value of $b?
Thankyou
Change the dataType to json.
$.ajax({
type: "get",
url: "some.php",
dataType: "json",
success: function(data) {
//data will hold an object with your response data, no need to parse
console.log('Do whatever you want with ' + data.b + '.');
}
In some.php do the following:
$response =array(
'b' => "sv",
'a' => "asjdgsajd",
'c' => "a"
);
echo json_encode($response);
echo $b;
The items of the associative array will end up as properties of a javascript object, that you can use in your success callback (or done function as success is deprecated).
Try using json and change your php to send the json response that way you can send more content and access them on client side as you need it.
PHP Script :
$outArr=array("b"=>"sv","content1"=>"asjdgsajd","content2"=>"a");
$jsonResponse=json_encode($outArr);
echo $jsonResponse;
In AJAX function you can access your data like this:
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
data=$.parseJSON( data ); //parse response string
b=data.b;//value of b
content1=data.content1;//value of content1
$("#exampleDiv").attr("id",b).html(content1); //set the attribute and content here for an example div
}
}
})

form submit in codeigniter using ajax

Here when I submit my form and will check validation in js file and then that will call the kickerLogin() function
Got alert message of datastring, then this is not send to my url which is mentioned in ajax but that will submit..........
function kickerLogin(){
alert('hello friends');
dataString=$('form[name=kickerLog]').serialize();
alert(dataString);
$.ajax({
type:"POST",
url:"<?php echo $GLOBALS['base_url']; ?>ajax/user-ajax.php?mode=kickerLogin",
cache: false,
data: dataString,
dataType: "json",
success: function(data) {
alert(data);
if(data.success == "yes")
{
$('#kickerLog').submit();
}
else if(data.success == "no")
{
if(data.status=="emailfail"){
$('li.log_error').show();
$('li.log_error').html("Email id not verified");
}
else if(data.status=="rejected"){
alert("Your account is inactive by admin");
}
else{
$('li.log_error').show();
$('li.log_error').html("Invalid Email / Password");
$("#loginEmail").css("border","1px solid red");
$("#loginPassword").css("border","1px solid red");
}
}
else {
alert(" Occured internal Error.please check network connection" );
}
}
});
}
You can't use <?php echo $GLOBALS['base_url']; ?> in your js file. Include this in your view may work then. Instead of <?php echo $GLOBALS['base_url']; ?> use <?=base_url()?> in your view.
If your js function kickerLogin() is in a js file you can't use '',
Pass your url as one parameter while calling kickerLogin() function
It is not recommended to call external files in CI.
//Instead of this
url:"<?php echo $GLOBALS['base_url']; ?>ajax/user-ajax.php?mode=kickerLogin",
//Use this
//Where ajax is a controller ajax.php user_ajax is a function in it.
url:"<?php echo site_url();?>/ajax/user_ajax?mode=kickerLogin",
//ajax.php controller
function user_ajax(){
$data['mode'] = $this->input->get('mode');
//Here load the file
$this->load->view('user-ajax');
}

Ajax code for cross-domain request fails

I need to send data through AJAX to another domain. I use the following code which alerts error.
$(document).ready(function(){
$('p').click(function(){
$.ajax({
url:"http://tarjom.ir/demo/javascript/get.php?callback=?",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
type : "GET",
data: "username=mostafa&url="+window.location,
success:function(json){
// do stuff with json (in this case an array)
alert(json);
},
error:function(){
alert("Error");
},
});
});
});
I want each click on <p> tag be reported to a file called get.php on another server. This file would save the click record+the time of the event into a DB.
Due to development stage, I have added an alert(); to the code, to alert whatever received from get.php, but I ONLY get alerted 'error'.
Here is the get.php code:
<?php
if($_POST['username'] != "")
{
$site = new mysqli('localhost', 'tarjomir_mostafa', 'securefiction1916', 'demo');
$stmt = $site->prepare("INSERT INTO demo (url) VALUES(?)");
$stmt->bind_param('s', $a);
$stmt->execute();
$stmt->close();
echo json_encode("success");
}
?>
try this:
$(function(){
$.ajax({
url:"http://tarjom.ir/demo/javascript/get.php",
dataType: 'jsonp',
type : "GET",
data: "username=mostafa&url="+window.location,
jsonpCallback:"myFunction"
})
.done(function(json){
// do stuff with json (in this case an array)
alert('done ' + json);
})
.fail(function(){
alert("Error");
});
});
And the response for http://tarjom.ir/demo/javascript/get.php be something like:
myFunction({"data": "mydata" })

Categories

Resources