i have 2 pages, one that send data from form and send data to second page.
the first page is html, and the second is php.
So, my problem is i send data from form to the second page to enter to SQL statement, and i get data from fetch array, how can i send data from second page to first page and put it in div.
my JS that i will send
// This function to search aqar
function search_aqar(){
var city = $('#city').val();
var aqar_type = $('#aqar_type').val();
var adv_type = $('#adv_type').val();
var search_btn = $('#search_btn').val();
var show_type = $('#show_type').val();
if (city!='' && aqar_type !='' && adv_type !=''){
$.ajax({
url: "request.php?do=search_aqar",
type: "POST",
data: {
city : city,
aqar_type : aqar_type,
adv_type : adv_type,
show_type : show_type,
search_btn : search_btn
},
dataType: "json",
success: function(data){
if(data.process == "ok"){
}
else
{
}
}
});
}
else
{
}
}
and i get data to page name request.php and put variable to sql statement, i need send data to first page on div
Just put a div in your html file like this:
<div id="msg"></div>
And change this:
success: function(data){
if(data.process == "ok"){
}
To this:
success: function(data){
$('#msg').html(data);
}
you may need to return the data as an json_encoded array from your php script and then use
success: function(data){
var variable = jQuery.parseJSON(data);
$("#yourdiv").html(variable['your_array_identifier']);
}
if you are not sending back an array and just a single item then you don't need to return an array and just simply use
success: function(data){
$("#yourdiv").html(data);
}
Related
I have a php file to validate a form with data that need to get sent through ajax.
The data that I receive back from the php file is unchanged, how can I receive the correct data?
main.js
$("#PersonForm").submit(function()
{
var data = $("form").serializeArray();
$.ajax({
type:"post",
url:"main.php",
act: 'validate',
datatype:"json",
data:data,
function(data){
console.log(data);
}});
return false;
});
main.php
else if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("[A-Za-z]{3,20}$/",$_REQUEST['name'])){
$validateData['name'] = 1;
}else{
$validateData['name'] = 0;
}
echo json_encode($validateData);
The data that originally gets sent in the data array is name:Bob
The expected return is 1 or 0 but I recieve name:Bob back.
Ok, the issue is you have to actually pass that in the data. You are doing this:
$.ajax({
type:"post",
url:"main.php",
act: 'validate', // <--- THIS IS WRONG
datatype:"json",
data:data, // <--- IT SHOULD BE IN THIS
function(data){
console.log(data);
}
});
It has to be in your data variable to be passed. You are using it as an option to the jQuery ajax() method, which doesn't work.
var data = $("form").serializeArray();
data.push({name: 'act', value: 'validate'});
// Then make ajax call here
After serializing your form data, you can add that on as an additional value.
I have javascript to get content from another page, like this :
$.get('disp/run_txt.php?type=andon&dispnm=PS&line=1',function(data){
$('#result').html(data);
});
What I want is the value of id='result' can transfer to variable, i have try :
$result = "<span id='runtxt'></span>";
echo $result;
My question is, how to capture the id='result' to variable?
Try
var resultVariable = $('#result').val(); //For non-text value
OR
var resultVariable = $('#result').text(); //For text value
If you want to pass what you have in data to some PHP code, you will have to do an ajax call to a php page.
$.get('disp/run_txt.php?type=andon&dispnm=PS&line=1',function(data){
$('#result').html(data);
var url = 'your-php-page.php';
// Will now send data to your-php-page.php
// where you can assign it to the variable
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
I have this ajax request that is sent from javascript in my page
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
async: false,
success: function(data) {
alert(data);
}
});
This returns an array of items with some text and ...
Now if the user clicks on a certain button the data needs to be copied to another place on the page(div)
Is there any way I can get the data again from the file (in the network tab "chrome") without resending the request?
Put the response in global variable (dataArray) and every time check that variable has value or not. So that request will not send further time. Also, you can use that global variable (dataArray) in other methods.
var dataArray = "";
function getData(){
if(dataArray != ""){
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
//async: false,
success: function(data) {
//alert(data);
dataArray = data;
}
});
}
}
First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});
i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'¤cy='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated