Solved

I cant send vars via ajax to php file

Posted on 2014-12-16
4
280 Views
Last Modified: 2014-12-16
im having all kinds of problems with trying to send vars to php as post values

I dont really care how its done just that i can get the post values in the post array
i have all the values reading correctly and i can read the values fine in the php post array

i had it working fine and i noticed i was breaking on & symbol in one of my firm_name fields so i said ok ill wrap it in ' and that didnt work so i started to look at jquery ajax calls and as you can see i tried a few different things...
and apparently i really mucked it up as nothings working now. i get popup with values correctly but the send parts not working... it also encodes the string now with % values so thats not the right way... with the shadow thing.
i simply want to send the post values.
also my done thing never fires too to see if it has any returned message, when mysql doesn't like something

any idea on how to fix this please, im seeing double i been trying to work on it so long, i really need to ask for help soon or something.

Thank you in advance for any code or help you may provide
Johnny

my code so far (really mucked up)
var processURL = "../process_mysql/client_add_process.php";
//var processdata= "{'Location':'"+Location+"','Firm_Name':'"+Firm_Name+"','Geo_Address':'"+Geo_Address+"','Order_Phone':'"+Order_Phone+"','Order_Fax':'"+Order_Fax+"','Billing_Address':'"+Billing_Address+"','Billing_Phone':'"+Billing_Phone+"','Billing_Fax':'"+Billing_Fax+"','Lat_Lng':'"+Lat_Lng+"','CompanyURL':'"+CompanyURL+"'}";
//var processdata= "{'Location':'"+Location+"','Firm_Name':'"+Firm_Name+"','Geo_Address':'"+Geo_Address+"','Order_Phone':'"+Order_Phone+"','Order_Fax':'"+Order_Fax+"','Billing_Address':'"+Billing_Address+"','Billing_Phone':'"+Billing_Phone+"','Billing_Fax':'"+Billing_Fax+"','Lat_Lng':'"+Lat_Lng+"','CompanyURL':'"+CompanyURL+"'}";
var processdata= "{Location:"+Location+",Firm_Name:"+Firm_Name+",Geo_Address:"+Geo_Address+",Order_Phone:"+Order_Phone+",Order_Fax:"+Order_Fax+",Billing_Address:"+Billing_Address+",Billing_Phone:"+Billing_Phone+",Billing_Fax:"+Billing_Fax+",Lat_Lng:"+Lat_Lng+",CompanyURL:"+CompanyURL+"}";
//var params = { width:1680, height:1050 };
//var str = jQuery.param( processdata );
var shallowEncoded = $.param( processdata, true );
var shallowDecoded = decodeURIComponent( shallowEncoded );
alert( shallowDecoded );
//alert(processdata);
    $.ajax({
      traditional: true,
      url: processURL,
      type: 'POST',
      data: shallowDecoded,
      dataType: "json",
      success: function(msg){
        console.log("returned msg: "+msg);
        $("#post-result").html(msg+"<br><STRONG style='color:red;'>This page will continue to Control Panel in a few seconds!</STRONG>");
        $("#post-result").fadeIn('slow');
        //$("#post-result").fadeOut(5000);
        //setTimeout("window.location.href='cp.php';",3000);
      },
      done: function(data){
  	      alert('done');
  	      console.log( "Sample of data:"+data);
	  }
   });//ajax

Open in new window


PS i dont want it to send json just width=1680&height=1050 as an example i wan tto read a normal post value please
like this would send please.
//var processURL = "../process_mysql/client_add_process.php?Location="+Location+"&Firm_Name="+Firm_Name+"&Geo_Address="+Geo_Address+"&Order_Phone="+Order_Phone+"&Order_Fax="+Order_Fax+"&Billing_Address="+Billing_Address+"&Billing_Phone="+Billing_Phone+"&Billing_Fax="+Billing_Fax+"&Lat_Lng="+Lat_Lng+"&CompanyURL="+CompanyURL+"";
0
Comment
Question by:Johnny
  • 2
4 Comments
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40503565
greetings Johnny, , I looked at the code for the Jquery Javascript you have here. . Wooo not much there that is correct for it to work. There are thousands of examples and tutorials for jquery ajax on the web now, you may should spend some time doing some example code and learn this.

Most everyone that tries to do ajax is lost at first, even though some say that jquery ajax makes it easy. My view is = ajax is NOT easy to understand!

as to your code, you have an incorrect Ajax Response, as you have TWO returns the first labeled as -
      success: function(msg){
the next as -
      done: function(data){

These are two different "Names" for the same function (the ajax return response), you should have ONE or the OTHER, but not both! The done: function( ) is the most recent, and what I recommend to use.

Now to the Jquery Ajax   data:   send parameter. You can place TWO different things in this, a "String" with the correct URL string for your post, something like this -
    data: "name=Bill%20Smith&phone=555-1212&id=UID33";

OR it can be a Javascript Object, the same as above would look like -
    data: {name : "Bill Smith", phone : "555-1212", id : "UID33"};
please Notice that the Object notation has NO quotations " for all of it, like you try to do -
      var processdata= "{Location:"+Location+",Firm_Name:"+Firm_Name+",Geo_Address:"+Geo_Address+"}";
somewhat correctly might be -
  var processdata= {Location : Location, Firm_Name : Firm_Name , Geo_Address : Geo_Address};
in Object notation (json), the first is the property name-ID, the second is the Value as
{ nameID : "value" }
you never place quotations " around a property name-ID in json for javascript to work.
just a note, your property and value Variable names can get to be confusing, if you use the SAME names, I see it all the time in Ajax  data:, but in more lengthy objects, I Always use a distinctive variable name -
    data:  {location : locationV, firm_Name : firmNameV, geo_address : geoAddressV}
then I can tell the properties from the values.

I do NOT see if you place a value in the variables like  Billing_Phone , you must have that variable with a value.
it is easier for forms if you use   $("#form1").serialize() to get all of the Inputs in to the data:

here is some code I have used -
//I use an Independent (non Jquery) function doPost( ) for development
function doPost( ) {
  var ajxSend = {
    type: "POST",
    url: "jqy-post.php",
    data: $("#form1").serialize(),
    timeout: 3500}
 
//Get the Debug checkbox to set PHP for NON JSON response
  if($('#check1').prop('checked')) ajxSend.data += "&debug=yes";

  var aj = $.ajax(ajxSend);
        
  aj.done(function( received ) { // ajax return function
// IMPORTANT, you need to understand what should be SENT and RECEIVED by ajax
  if(typeof(received)=='object'){  //IMPORTANT for DEBUG test for JSON Object
    $('#debug1').html("No DEBUG");// erase the DEbug
    if(received.error) { // test for error response
      alert("ERROR="+received.error+"- php value check Invlaid, "+received.message);
      return; // end ALL JS code
      }
// Format your browser output next in the out1 variable string
    var out1 = "Success as <b>"+received.name2+"</b>, gave "+received.age2+", "+received.email2+" and made it around the ajax operations";
    $('#ajaxRe').html(out1);// load formated ajax response to div
    $('#popup').show(); //show div
	$('#debug1').html("jqXHR output is "+aj.responseText);
    } else { // IMPORTANT for DEBUG, Show the entire Ajax RESPONCE in the debug div
    $('#debug1').html(received);
    alert("ERROR- JSON was NOT retutned, see Debug DIV");
    return;
    }
	});

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40503582
Johnny, I have an example article here that shows the general design pattern.  Hope it helps, ~Ray
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
0
 

Author Comment

by:Johnny
ID: 40503861
ok so i read all the replies and redid everything after watching a movie.

i have not had much luck with getting serialize to work right before. I figured i would give it a shot.

the now working code is
var post_str = $( "form" ).serialize();
//alert(post_str);
    $.ajax({
      url: processURL,
      type: 'POST',
      data: post_str,
      success: function(msg){
        console.log("returned msg: "+msg);
        $("#post-result").html(msg+"<br><STRONG style='color:red;'>This page will continue to Control Panel in a few seconds!</STRONG>");
        $("#post-result").fadeIn('slow');
        $('html,body').animate({
	   scrollTop: $("#post-result").offset().top
	 });
        //$("#post-result").fadeOut(5000);
        //setTimeout("window.location.href='cp.php';",3000);
      }
   });//ajax

Open in new window


thanks for the help
0
 

Author Closing Comment

by:Johnny
ID: 40503865
@Slick812: Thank you for the solution with  $("form").serialize()
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now